views:

107

answers:

2

Hello,

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

A: 

yes, you can swap these 2 queries

select * from table limit 5, 5

select * from table limit 0, 5
Col. Shrapnel
+2  A: 

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.

Mark Byers
Indeed. Backwards has no meaning if the result isn't ordered.
extraneon
so order by applies before limit?
faya
@faya: In a simple case like this, yes.
Mark Byers