What does select @@identity do in MySQL?


The @@identity returns the last inserted value in the auto_increment column in the current session. Let us first create a table −

mysql> create table DemoTable(
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserName varchar(100)
);
Query OK, 0 rows affected (0.67 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(UserName) values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(UserName) values('Mike');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(UserName) values('Carol');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(UserName) values('Robert');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(UserName) values('John');
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 −

+--------+----------+
| UserId | UserName |
+--------+----------+
| 1      | David    |
| 2      | Mike     | 
| 3      | Carol    |
| 4      | Robert   |
| 5      | John     |
+--------+----------+
5 rows in set (0.00 sec)

Now, we will use @@identity −

mysql> select @@identity;

This will produce the following output −

+------------+
| @@identity |
+------------+
| 5          |
+------------+
1 row in set (0.00 sec)

Updated on: 27-Sep-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements