Order records and delete n rows in MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstName varchar(20)
   -> );
Query OK, 0 rows affected (0.65 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(FirstName) values('Adam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(FirstName) values('David');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(FirstName) values('Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(FirstName) values('Sam');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | Chris     |
|  2 | Adam      |
|  3 | John      |
|  4 | David     |
|  5 | Mike      |
|  6 | Carol     |
|  7 | Sam       |
+----+-----------+
7 rows in set (0.00 sec)

Here is the query to order records and delete n rows −

mysql> delete from DemoTable order by FirstName asc limit 4;
Query OK, 4 rows affected (0.19 sec)

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  3 | John      |
|  5 | Mike      |
|  7 | Sam       |
+----+-----------+
3 rows in set (0.00 sec)
raja
Published on 12-Dec-2019 07:31:25
Advertisements