31

Is it available to write a query to use same "LIMIT (from), (count)", but get result in backwards?

In example if I have 8 rows in the table and I want to get 5 rows in two steps I would: first step query:

select * from table limit 0, 5

first step result:

first 5 rows;

second step query:

select * from table limit 5, 5

second step result:

last 3 rows;

But I want to get it vice versa. I mean from the first step I want last 3 rows and from the second I want 5 first rows. Thank you for your answer

4 Answers 4

46

No, you shouldn't do this. Without an ORDER BY clause you shouldn't rely on the order of the results being the same from query to query. It might work nicely during testing but the order is indeterminate and could break later. Use an order by.

SELECT * FROM table1 ORDER BY id LIMIT 5

By the way, another way of getting the last 3 rows is to reverse the order and select the first three rows:

SELECT * FROM table1 ORDER BY id DESC LIMIT 3

This will always work even if the number of rows in the result set isn't always 8.

4
  • Indeed. Backwards has no meaning if the result isn't ordered.
    – extraneon
    Commented Apr 25, 2010 at 17:01
  • so order by applies before limit?
    – faya
    Commented Apr 25, 2010 at 17:13
  • @faya: In a simple case like this, yes.
    – Mark Byers
    Commented Apr 25, 2010 at 17:23
  • Is it possible to use group by and order by in same query..? Commented Jun 8, 2017 at 6:20
3

Let's say we have a table with a column time and you want the last 5 entries, but you want them returned to you in asc order, not desc, this is how you do it:

select * from ( select * from `table` order by `time` desc limit 5 ) t order by `time` asc
0

yes, you can swap these 2 queries

select * from table limit 5, 5

select * from table limit 0, 5
0

This way is comparatively more easy

SELECT doc_id,serial_number,status FROM date_time ORDER BY  date_time DESC LIMIT 0,1;

Not the answer you're looking for? Browse other questions tagged or ask your own question.