Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete the last row in a table using sql query?

Tags:

mysql

I am trying to delete the last record in the table named "marks" in the database using MySql query.
The query I tried for this is as follows:

DELETE MAX(`id`) FROM `marks`;

There are 8 columns in the table. I want to delete the last column without specifying id, as in:

DELETE FROM marks where id=8;

After deleting the 8th record, I want to delete the 7th; after that 6th and so on, up to 1st record without specifying the id manually.

like image 678
Arunkumar G Avatar asked Sep 10 '15 13:09

Arunkumar G


People also ask

How do I select the last row in SQL?

To select the last row, we can use ORDER BY clause with desc (descending) property and Limit 1. Let us first create a table and insert some records with the help of insert command.


2 Answers

If id is auto-increment then you can use the following

delete from marks
order by id desc limit 1
like image 160
Abhik Chakraborty Avatar answered Oct 12 '22 14:10

Abhik Chakraborty


@Abhshek's Answer is right and works for you but you can also try the following code if the id is not increment

DELETE FROM MARKS WHERE ID=(SELECT MAX(id) FROM MARKS)
like image 21
Chintan7027 Avatar answered Oct 12 '22 15:10

Chintan7027