Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Query MySQL database to echo highest auto incremented number?
Let us first create a table with Id as auto_increment −
mysql> create table DemoTable ( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserName varchar(20) ); Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(UserName) values('John');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(UserName) values('Larry');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable(UserName) values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(UserName) values('Bob');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(UserName) values('Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(UserName) values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(UserName) values('Robert');
Query OK, 1 row affected (0.20 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+----------+ | UserId | UserName | +--------+----------+ | 1 | John | | 2 | Larry | | 3 | Chris | | 4 | Bob | | 5 | Carol | | 6 | David | | 7 | Robert | +--------+----------+ 7 rows in set (0.00 sec)
Here is the query to echo highest auto incremented number −
mysql> select *from DemoTable order by UserId desc limit 0,1;
This will produce the following output displaying the highest auto incremented value −
+--------+----------+ | UserId | UserName | +--------+----------+ | 7 | Robert | +--------+----------+ 1 row in set (0.00 sec)
Advertisements
