MySQL query to delete a record with the lowest ID?


To delete record with the lowest id, you can use the following syntax:

delete from yourTableName order by yourColumnName limit 1;

Let us first create a table:

mysql> create table DemoTable
(
   Id int,
   Name varchar(20)
);
Query OK, 0 rows affected (0.75 sec)

Following is the query to insert records in the table using insert command:

mysql> insert into DemoTable values(10,'Larry');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(100,'Mike');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(30,'Sam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(90,'Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(9,'Carol');
Query OK, 1 row affected (0.19 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output:

+------+-------+
| Id   | Name  |
+------+-------+
| 10   | Larry |
| 100  | Mike  |
| 30   | Sam   |
| 90   | Chris |
| 9    | Carol |
+------+-------+
5 rows in set (0.00 sec)

Following is the query to delete record with lowest id:

mysql> delete from DemoTable order by Id limit 1;
Query OK, 1 row affected (0.18 sec)

Let us display all records from the table to check the lowest id has been deleted or not:

mysql> select *from DemoTable;

This will produce the following output

+------+-------+
| Id   | Name  |
+------+-------+
| 10   | Larry |
| 100  | Mike  |
| 30   | Sam   |
| 90   | Chris |
+------+-------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

577 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements