Insert (SQL) - Retrieving The Key

Retrieving The Key

Database designers that use a surrogate key as the primary key for every table will run into the occasional scenario where they need to automatically retrieve the database generated primary key from an SQL INSERT statement for use in another SQL statements. Most systems do not allow SQL INSERT statements to return row data. Therefore, it becomes necessary to implement a workaround in such scenarios. Common implementations include:

  • Using a database-specific stored procedure that generates the surrogate key, performs the INSERT operation, and finally returns the generated key. For example, in Microsoft SQL Server, the key is retrieved via the SCOPE_IDENTITY special function, while in SQLite the function is named last_insert_rowid.
  • Using a database-specific SELECT statement on a temporary table containing last inserted row(s). DB2 implements this feature in the following way:
SELECT * FROM NEW TABLE ( INSERT INTO phone_book VALUES ( 'Peter Doe','555-2323' ) ) AS t
DB2 for z/OS implements this feature in the following way.
SELECT EMPNO, HIRETYPE, HIREDATE FROM FINAL TABLE ( INSERT INTO EMPSAMP (NAME, SALARY, DEPTNO, LEVEL) VALUES(’Mary Smith’, 35000.00, 11, ’Associate’) );
  • Using a SELECT statement after the INSERT statement with a database-specific function that returns the generated primary key for the most recently inserted row. For example, LAST_INSERT_ID for MySQL.
  • Using a unique combination of elements from the original SQL INSERT in a subsequent SELECT statement.
  • Using a GUID in the SQL INSERT statement and retrieving it in a SELECT statement.
  • Using the OUTPUT clause in the SQL INSERT statement for MS-SQL Server 2005 and MS-SQL Server 2008.
  • Using an INSERT statement with RETURNING clause for Oracle.
INSERT INTO phone_book VALUES ( 'Peter Doe','555-2323' ) RETURNING phone_book_id INTO v_pb_id
  • Using an INSERT statement with RETURNING clause for PostgreSQL (since 8.2). The returned list is identical to the result of a SELECT.

Firebird has the same syntax; the statement may add at most one row.

INSERT INTO phone_book VALUES ( 'Peter Doe','555-2323' ) RETURNING phone_book_id
  • Using the IDENTITY function in H2 returns the last identity inserted.
SELECT IDENTITY;

Read more about this topic:  Insert (SQL)

Famous quotes containing the word key:

    Japanese mothers credit “effort” as the key determinant of a child’s achievement in school, while American mothers name “ability” as the more important factor.
    Perry Garfinkel (20th century)