Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(SQL) Delete all rows except the newest one

I have a problem, namely I'm deleting all rows from the table except for the newest one. I do not know too much how to construct the appropriate query.

The look of the table structure:

| column1 | column2 | column3 | column4 |
| --------|---------|---------|---------|
| aaa     | aaa     | aaa     | aaa     | 
| bbb     | bbb     | bbb     | bbb     |
| ccc     | ccc     | ccc     | ccc     |

Suppose line 3 was added last, which is the latest one. After the query:

| column1 | column2 | column3 | column4 |
| --------|---------|---------|---------|
| ccc     | ccc     | ccc     | ccc     |
like image 293
Trawlr Avatar asked Jan 01 '26 10:01

Trawlr


1 Answers

If you want to delete all the rows the SQL is :

Delete  from theTable;

If you want to exclude the newest, hoping that you have an id you write like this:

Delete  from theTable where id <> (Select max (id) from theTable)
like image 128
Claudiu Haidu Avatar answered Jan 05 '26 02:01

Claudiu Haidu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!