How to order by auto_increment in MySQL?


Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(FirstName) values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(FirstName) values('Adam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(FirstName) values('Carol');
Query OK, 1 row affected (0.12 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 | Robert    |  
|  3 | David     |
|  4 | Mike      |
|  5 | Adam      |
|  6 Carol       |
+----+-----------+
6 rows in set (0.00 sec)

Following is the query to order by auto_increment −

mysql> select *from DemoTable order by Id DESC;

This will produce the following output −

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

Updated on: 22-Aug-2019

413 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements