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.
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:
@@IDENTITYreturns 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@@IDENTITYfaces 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:
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:
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:
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:
Summary Table: Methods of Retrieving Identity in Popular Database Systems
| Database System | Method |
| SQL Server | SCOPE_IDENTITY(), @@IDENTITY |
| MySQL | LAST_INSERT_ID() |
| PostgreSQL | RETURNING clause |
| ORM Tools | Automatic (handled by the framework) |
Additional Points to Consider
- Concurrency and Performance: When using methods like
@@IDENTITYin 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
- How to get the index of an element in an IEnumerable?
- How to get the insert ID in JDBC?
- How to get the max of two values in MySQL?
- How to get the mysql table columns data type?
- How to get the next auto-increment id in mysql
- How to get the nth element of a python list or a default if not available
- How to get the number of days of difference between two dates on MySQL?
- How to get the object id in PyMongo after an insert?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack 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.