LAST_INSERT_ID() returns the first automatically generated value set for an AUTO_INCREMENT column : LAST_INSERT_ID : Information Functions MySQL TUTORIALS


MySQL TUTORIALS » Information Functions » LAST_INSERT_ID »

 

LAST_INSERT_ID() returns the first automatically generated value set for an AUTO_INCREMENT column


If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only.

mysql>
mysql> CREATE TABLE t (
    ->  id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
    ->  name VARCHAR(10NOT NULL
    -> );
Query OK, rows affected (0.03 sec)

mysql>
mysql> INSERT INTO t VALUES (NULL, 'Bob');
Query OK, row affected (0.00 sec)

mysql>
mysql> SELECT FROM t;
+----+------+
| id | name |
+----+------+
|  | Bob  |
+----+------+
row in set (0.00 sec)

mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                |
+------------------+
row in set (0.00 sec)

mysql>
mysql> INSERT INTO t VALUES (NULL, 'Mary'),
    ->                      (NULL, 'Jane'),
    ->                      (NULL, 'Lisa');
Query OK, rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql>
mysql> SELECT FROM t;
+----+------+
| id | name |
+----+------+
|  | Bob  |
|  | Mary |
|  | Jane |
|  | Lisa |
+----+------+
rows in set (0.00 sec)

mysql>
mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                |
+------------------+
row in set (0.00 sec)

mysql>
mysql> drop table t;
Query OK, rows affected (0.00 sec)



Leave a Comment / Note


 
Verification is used to prevent unwanted posts (spam). .

Follow Navioo On Twitter

MySQL TUTORIALS

 Navioo Information Functions
» LAST_INSERT_ID