Database Management
SQL
Programming
Data Insertion
Row Identification

How to get the identity of an inserted row?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

When working with databases, it's often necessary to retrieve the identity or the primary key of a row immediately after it has been inserted. This is particularly useful in applications where you need to use this new unique identifier to perform additional operations or reference the newly created record. Different database systems have various methods to achieve this, and understanding these methods can vastly improve the efficiency and reliability of your application.

1. Retrieving Identity in SQL Server

SQL Server uses the @@IDENTITY, SCOPE_IDENTITY(), and IDENT_CURRENT('<table_name>') functions to fetch the last inserted identity value:

  • @@IDENTITY returns the last identity value generated by an insert statement within the current session and the current scope; however, it might not be suitable if there are triggers that insert rows into another table with its own identity column as it would return the last identity created in the session.
  • SCOPE_IDENTITY() returns the last identity value generated in the same scope. It prevents the issues that @@IDENTITY faces with triggers, making it a safer choice in environments with complex insert operations.
  • IDENT_CURRENT('<table_name>') returns the last identity value generated for a specific table in any session and any scope, providing a more targeted approach than @@IDENTITY.

Example:

sql
INSERT INTO Employees (Name) VALUES ('John Doe');
SELECT SCOPE_IDENTITY() AS NewEmployeeID;

2. Retrieving Identity in MySQL

MySQL uses the LAST_INSERT_ID() function to return the last automatically generated ID in the current session, ignoring other sessions. It's reliable for retrieving the identity of the last inserted row, assuming that no other insert queries have been made to the database after that insertion during the session.

Example:

sql
INSERT INTO Employees (Name) VALUES ('Jane Smith');
SELECT LAST_INSERT_ID() AS NewEmployeeID;

3. Retrieving Identity in PostgreSQL

PostgreSQL manages this through the RETURNING clause, which can be appended to an INSERT statement to directly return fields from the inserted row, including the identity column.

Example:

sql
INSERT INTO Employees (Name) VALUES ('Tom Johnson') RETURNING ID;

4. Using ORM Tools

Object-Relational Mapping (ORM) tools like Entity Framework, Hibernate, or Django's ORM abstract these details and manage identity retrieval internally:

Example with Entity Framework:

csharp
1var employee = new Employee { Name = "Alice Martin" };
2context.Employees.Add(employee);
3context.SaveChanges();
4int id = employee.ID; // The ID is populated after SaveChanges() is called.
Database SystemMethod
SQL ServerSCOPE_IDENTITY(), @@IDENTITY
MySQLLAST_INSERT_ID()
PostgreSQLRETURNING clause
ORM ToolsAutomatic (handled by the framework)

Additional Points to Consider

  • Concurrency and Performance: When using methods like @@IDENTITY in SQL Server, beware of potential issues in a concurrent environment where multiple inserts happen simultaneously.
  • Error Handling: Always include error handling around your database interactions to manage exceptions that may occur during insert operations.
  • Database Security: Ensure that permissions are correctly set on the database to prevent unauthorized access, and consider using parameterized queries or ORM methods to avoid SQL injection attacks.

Conclusion

Retrieving the identity of an inserted row is crucial for maintaining relational integrity and for subsequent database operations involving the new row. By choosing the appropriate method for your database system and incorporating best practices around security and error handling, you can ensure robust and efficient data management in your applications.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.