Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: How to select all rows from a table EXCEPT the last one

I have a table with N rows, and I wanna select N-1 rows.

Suggestions on how to do this in one query, if it's possible..?

like image 745
Lasse A Karlsen Avatar asked Nov 24 '08 21:11

Lasse A Karlsen


2 Answers

Another technique I don't see listed here is

SELECT * FROM table ORDER BY id DESC LIMIT 10000 OFFSET 1;

This will give you the records ordered by id descendant except first, that is except the last in the original order.
Note that with this method you will only take 10000 records, however this number can be as high as you want but cannot be omitted.
The advantage of this method is that you can order by whatever you want.
The disadvantage is that it gives you the records ordered from last to first.
Finally it worths noting that the other methods here works quite well

like image 163
Redithion Avatar answered Oct 17 '22 02:10

Redithion


Does the last row have the highest ID? If so, I think this would work:

SELECT * FROM TABLE WHERE ID != (SELECT MAX(ID) FROM TABLE)

MySQL does allow subselects in the current version, right?

However, in most cases, it'd probably perform better if you selected all the rows and then filtered the unwanted data out in your application.

like image 34
Joshua Carmody Avatar answered Oct 17 '22 03:10

Joshua Carmody