SQLite Tutorial SQLite Advanced SQLite Database SQLite References

SQLite LAST_INSERT_ROWID() Function



The SQLite LAST_INSERT_ROWID() function returns the ROWID of the last row INSERT in the database for the current session.

Syntax

LAST_INSERT_ROWID()

Parameters

No parameter is required.

Return Value

Returns the ROWID of the last row INSERT in the database for the current session

Example:

Consider the example below, where a table called Employee is created. After creating the table, the LAST_INSERT_ROWID() function is used to get the ROWID of the last INSERT record of this database in various scenarios.

sqlite> CREATE TABLE Employee (
  EmpID INTEGER PRIMARY KEY, 
  Name VARCHAR(50));

sqlite> SELECT LAST_INSERT_ROWID();
+---------------------+
| LAST_INSERT_ROWID() |
+---------------------+
|                   0 |
+---------------------+

sqlite> INSERT INTO Employee(Name) Values ('John');

sqlite> INSERT INTO Employee(Name) Values ('Marry');

sqlite> SELECT LAST_INSERT_ROWID();
+---------------------+
| LAST_INSERT_ROWID() |
+---------------------+
|                   2 |
+---------------------+

sqlite> INSERT INTO Employee(Name) Values ('Kim') , ('Jo');

sqlite> SELECT LAST_INSERT_ROWID();
+---------------------+
| LAST_INSERT_ROWID() |
+---------------------+
|                   4 |
+---------------------+

sqlite> SELECT * FROM Employee;
+-------+-------+
| EmpID | Name  |
+-------+-------+
| 1     | John  |
| 2     | Marry |
| 3     | Kim   |
| 4     | Jo    |
+-------+-------+

sqlite> INSERT INTO Employee(Name) Values ('Ramesh');

sqlite> SELECT LAST_INSERT_ROWID();
+---------------------+
| LAST_INSERT_ROWID() |
+---------------------+
|                   5 |
+---------------------+

sqlite> SELECT * FROM Employee;
+-------+--------+
| EmpID | Name   |
+-------+--------+
| 1     | John   |
| 2     | Marry  |
| 3     | Kim    |
| 4     | Jo     |
| 5     | Ramesh |
+-------+--------+

❮ SQLite Functions