Jump to content

Insert (SQL)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 122.255.11.216 (talk) at 09:32, 12 August 2023 (Multirow inserts). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

An SQL INSERT statement adds one or more records to any single table in a relational database.

Advanced forms

Copying rows from other tables

An INSERT statement can also be used to retrieve data from other tables, modify it if necessary and insert it directly into the table. All this is done in a single SQL statement that does not involve any intermediary processing in the client application. A subselect is used instead of the VALUES clause. The subselect can contain joins, function calls, and it can even query the same table into which the data is inserted. Logically, the select is evaluated before the actual insert operation is started. An example is given below.

INSERT INTO phone_book2
SELECT *
FROM   phone_book
WHERE  name IN ('John Doe', 'Peter Doe')

A variation is needed when some of the data from the source table is being inserted into the new table, but not the whole record. (Or when the tables' schemas are not the same.)

INSERT INTO phone_book2 (name, number)
SELECT name, number
FROM   phone_book
WHERE  name IN ('John Doe', 'Peter Doe')

The SELECT statement produces a (temporary) table, and the schema of that temporary table must match with the schema of the table where the data is inserted into.

Default Values

It is possible to insert a new row without specifying any data, using default values for all columns. However, some databases reject the statement if no data is given, such as Microsoft SQL Server, and in this case the DEFAULT keyword can be used.

INSERT INTO phone_book
VALUES ( DEFAULT )

Sometimes databases also support alternative syntax for this; for example, MySQL allows omitting the DEFAULT keyword, and T-SQL can use DEFAULT VALUES instead of VALUES(DEFAULT). The DEFAULT keyword can also be used in normal insertion to explicitly fill a column using that column's default value:

INSERT INTO phone_book VALUES ( DEFAULT, '555-1212' )

What happens when a column does not specify a default value is database dependent. For example, MySQL and SQLite will fill in with a blank value (except when in strict mode), while many other databases will reject the statement.

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 other 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 INSERT.
    • Firebird has the same syntax in Data Modification Language statements (DSQL); the statement may add at most one row.[1] In stored procedures, triggers and execution blocks (PSQL) the aforementioned Oracle syntax is used.[2]
      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();
    

Triggers

If triggers are defined on the table on which the INSERT statement operates, those triggers are evaluated in the context of the operation. BEFORE INSERT triggers allow the modification of the values that shall be inserted into the table. AFTER INSERT triggers cannot modify the data anymore, but can be used to initiate actions on other tables, for example, to implement auditing mechanism.

References

  1. ^ "Firebird 2.5 Language Reference Update". Retrieved 2011-10-24.
  2. ^ "Firebird SQL Language Dictionary".