18

I have the following table, named Example:

id(int 11) //not autoincriment
value (varchar 100)

It has the following rows of data:

0  100
2  150
3  200
6  250
7  300

Note that id values are not contiguous.

I've written this SQL so far:

SELECT * FROM Example WHERE id = 3

However, I don't know how to get the value of previous id and value of the next id...

Please help me get previous value and next value if id = 3 ?

P.S.: in my example it will be: previous - 150, next - 250.

8
  • Do you want the values in one row or 3 rows?
    – Bohemian
    Dec 30, 2013 at 23:11
  • 1
    not the down voter, but what have you tried, why are you trying to do this?
    – Sam
    Dec 30, 2013 at 23:11
  • 1
    @SlyRaskal sorry, i update question now
    – user2881809
    Dec 30, 2013 at 23:11
  • @Bohemian for example i have id=3 (not autoincriment) an now i would like get value for previous id and value for next id.
    – user2881809
    Dec 30, 2013 at 23:13
  • I repeat my question: Do you want one row with 3 values or 3 rows each with one value?
    – Bohemian
    Dec 30, 2013 at 23:19

8 Answers 8

24

Select the next row below:

SELECT * FROM Example WHERE id < 3 ORDER BY id DESC LIMIT 1

Select the next row above:

SELECT * FROM Example WHERE id > 3 ORDER BY id LIMIT 1

Select both in one query, e.g. use UNION:

(SELECT * FROM Example WHERE id < 3 ORDER BY id DESC LIMIT 1)
 UNION
(SELECT * FROM Example WHERE id > 3 ORDER BY id LIMIT 1)

That what you mean?

1
  • This only works if you auto increment your id, which you shouldn't usually do unless you have a really good reason or if you need to build something very quickly and you don't care about silly things like security. /s lol Mar 31 at 16:23
20

A solution would be to use temporary variables:

select 
    @prev as previous,
    e.id,
    @prev := e.value as current
from
    (
        select
            @prev := null
    ) as i,
    example as e
order by
    e.id

To get the "next" value, repeat the procedure. Here is an example:

select 
  id, previous, current, next
from
  (
    select
      @next as next,
      @next := current as current,
      previous,
      id
    from
      (
        select @next := null
      ) as init,
      (
        select
          @prev as previous,
          @prev := e.value as current,
          e.id
        from
          (
            select @prev := null
          ) as init,
          example as e
        order by e.id
      ) as a
    order by
      a.id desc
  ) as b
order by
  id

Check the example on SQL Fiddle

May be overkill, but it may help you

4
  • 1
    thats a good one (y)
    – jafarbtech
    Jun 14, 2017 at 6:07
  • @Barranka It does not work anymore. You can check it on SQL Fiddle with MySQL 5.6. Previous and Next displays some Blob values instead of the correct values.
    – tak3shi
    Feb 25, 2018 at 8:20
  • fixed it by replacing second line with: id, CONVERT(previous USING utf8), current, CONVERT(next USING utf8)
    – tak3shi
    Feb 25, 2018 at 8:32
  • 1
    Note that if the query somehow includes a group by the variable is evaluated differently and this won't work. You will need to wrap your query.
    – Sylvain
    Nov 21, 2019 at 8:30
10

please try this sqlFiddle

SELECT value,
       (SELECT value FROM example e2
        WHERE e2.value < e1.value
        ORDER BY value DESC LIMIT 1) as previous_value,
       (SELECT value FROM example e3
        WHERE e3.value > e1.value
        ORDER BY value ASC LIMIT 1) as next_value
FROM example e1
WHERE id = 3

Edit: OP mentioned to grab value of previous id and value of next id in one of the comments so the code is here SQLFiddle

SELECT value,
      (SELECT value FROM example e2
       WHERE e2.id < e1.id
       ORDER BY id DESC LIMIT 1) as previous_value,
      (SELECT value FROM example e3
       WHERE e3.id > e1.id
       ORDER BY id ASC LIMIT 1) as next_value
FROM example e1
WHERE id = 3
3
  • Looks Very tedious, but actually it's the fastest.. I've compared it with other solutions here Mar 7, 2017 at 9:02
  • Hmm, on my table with approx. 16000 rows, the alternative with variables is much much faster (MySQL 5.5 - 0.09s vs. 17s !)
    – user729103
    Jun 20, 2019 at 8:29
  • This answer is more flexible. You don't actually want to sort on ID anyhow. I'm using UUID's which aren't sortable. I can replace 'value' with 'sequence' and tighten up the inner selects to get the proper Prev/Next rows from Postgres.
    – tlorens
    Feb 27, 2020 at 14:36
6
SELECT *,
       (SELECT value FROM example e1 WHERE e1.id < e.id ORDER BY id DESC LIMIT 1 OFFSET 0) as prev_value,
       (SELECT value FROM example e2 WHERE e2.id > e.id ORDER BY id ASC LIMIT 1 OFFSET 0) as next_value
FROM example e
WHERE id=3;

And you can place your own offset after OFFSET keyword if you want to select records with higher offsets for next and previous values from the selected record.

6
  • 1
    @Strawberry Better answers are welcome at any time! (I had same question and I wanted the best working answer so finally I have found this answer working perfect in my case and I shared it here) hoping it helps somebody to find best answer easier. Jul 14, 2015 at 8:44
  • If you say so. I think the top answer is better than this.
    – Strawberry
    Jul 14, 2015 at 8:46
  • 2
    @Strawberry I respect your choice but in some situations (like when you want diff from two rows or calculations) my answer is more helpful to do calculations on the same row. Jul 14, 2015 at 8:53
  • @Strawberry Assume the chapters of a book! What if you want to show number of pages in current chapter if you have a table with chapter_id and chapter_page_number for example! The formula to calculate this will be next_chapter_page_number - chapter_page_number. Still you use top answer? And if so then HOW? Jul 14, 2015 at 9:14
  • If you have a question, suggest you ask a question - with proper DDLs and a desired result!
    – Strawberry
    Jul 14, 2015 at 9:22
4

Here's my solution may suit you:

SELECT * FROM Example
WHERE id IN (
(SELECT MIN(id) FROM Example WHERE id > 3),(SELECT MAX(id) FROM Example WHERE id < 3)
)

Demo: http://sqlfiddle.com/#!9/36c1d/2

1

A possible solution if you need it all in one row

SELECT t.id, t.value, prev_id, p.value prev_value, next_id, n.value next_value
  FROM
(
  SELECT t.id, t.value,
  (
    SELECT id
      FROM table1
     WHERE id < t.id
     ORDER BY id DESC
     LIMIT 1
  ) prev_id,
  (
    SELECT id
      FROM table1
     WHERE id > t.id
     ORDER BY id
     LIMIT 1
  ) next_id
    FROM table1 t
   WHERE t.id = 3
) t LEFT JOIN table1 p
     ON t.prev_id = p.id LEFT JOIN table1 n
     ON t.next_id = n.id 

Sample output:

| ID | VALUE | PREV_ID | PREV_VALUE | NEXT_ID | NEXT_VALUE |
|----|-------|---------|------------|---------|------------|
|  3 |   200 |       2 |        150 |       4 |        250 |

Here is SQLFiddle demo

0
1

This query uses a user defined variable to calculate the distance from the target id, and a series of wrapper queries to get the results you want. Only one pass is made over the table, so it should perform well.

select * from (
    select id, value from (
        select *, (@x := ifnull(@x, 0) + if(id > 3, -1, 1)) row from (
            select * from mytable order by id
        ) x 
    ) y
    order by row desc
    limit 3
) z
order by id

See an SQLFiddle

If you don't care about the final row order you can omit the outer-most wrapper query.

2
  • Question, how does order by row work when row is not in selected columns?
    – Ejaz
    Sep 7, 2015 at 15:42
  • 1
    @ejay (in all databases) you can order by expressions that are not selected
    – Bohemian
    Sep 7, 2015 at 15:58
1

If you do not have an ID this has worked for me.

Next:

SELECT * FROM table_name
WHERE column_name > current_column_data
ORDER BY column_name ASC
LIMIT 1

Previous:

SELECT * FROM table_name
WHERE column_name < current_column_data
ORDER BY column_name DESC
LIMIT 1

I use this for a membership list where the search is on the last name of the member. As long as you have the data from the current record it works fine.