Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Insert (SQL)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|SQL statement}} An [[SQL]] '''INSERT''' statement adds one or more records to any single [[Table (database)|table]] in a [[relational database]]. ==Basic form== Insert statements have the following form: {{pre| INSERT INTO ''table'' (''column1'' [, ''column2'', ''column3'' ... ]) VALUES (''value1'' [, ''value2'', ''value3'' ... ]) }} The number of [[Column (database)|columns]] and values must be the same. If a column is not specified, the default value for the column is used. The values specified (or implied) by the {{mono|INSERT}} statement must satisfy all the applicable constraints (such as [[primary key]]s, [[Check Constraint|{{mono|CHECK}} constraints]], and {{mono|[[Null (SQL)|NOT NULL]]}} constraints). If a syntax error occurs or if any constraints are violated, the new row is not added to the table and an error returned instead. Example: <syntaxhighlight lang="sql"> INSERT INTO phone_book (name, number) VALUES ('John Doe', '555-1212'); </syntaxhighlight> Shorthand may also be used, taking advantage of the order of the columns when the table was created. It is not required to specify all columns in the table since any other columns will take their default value or remain [[Null (SQL)|null]]: {{pre| INSERT INTO ''table'' VALUES (''value1'', [''value2'', ... ]) }} Example for inserting data into 2 columns in the phone_book table and ignoring any other columns which may be after the first 2 in the table. <syntaxhighlight lang="sql"> INSERT INTO phone_book VALUES ('John Doe', '555-1212'); </syntaxhighlight> ==Advanced forms== ===Multirow inserts=== A SQL feature (since [[SQL-92]]) is the use of ''row value constructors'' to insert multiple rows at a time in a single SQL statement: <syntaxhighlight lang="sql"> INSERT INTO tablename (column-a, [column-b, ...]) VALUES ('value-1a', ['value-1b', ...]), ('value-2a', ['value-2b', ...]), ... </syntaxhighlight> This feature is supported by [[IBM Db2]], [[Microsoft SQL Server|SQL Server]] (since version 10.0 - i.e. 2008), [[PostgreSQL]] (since version 8.2), [[MySQL]], [[SQLite]] (since version 3.7.11) and [[H2 (DBMS)|H2]]. Example (assuming that 'name' and 'number' are the only columns in the 'phone_book' table): <syntaxhighlight lang="sql"> INSERT INTO phone_book VALUES ('John Doe', '555-1212'), ('Peter Doe', '555-2323'); </syntaxhighlight> which may be seen as a shorthand for the two statements <syntaxhighlight lang="sql"> INSERT INTO phone_book VALUES ('John Doe', '555-1212'); INSERT INTO phone_book VALUES ('Peter Doe', '555-2323'); </syntaxhighlight> Note that the two separate statements may have different semantics (especially with respect to statement [[database trigger|triggers]]) and may not provide the same performance as a single multi-row insert. To insert multiple rows in MS SQL you can use such a construction: <syntaxhighlight lang="tsql"> INSERT INTO phone_book SELECT 'John Doe', '555-1212' UNION ALL SELECT 'Peter Doe', '555-2323'; </syntaxhighlight> Note that this is not a valid SQL statement according to the SQL standard ([[SQL:2003]]) due to the incomplete subselect clause. To do the same in Oracle use the [[DUAL table]], which always consists of a single row only: <syntaxhighlight lang="sql"> INSERT INTO phone_book SELECT 'John Doe', '555-1212' FROM DUAL UNION ALL SELECT 'Peter Doe','555-2323' FROM DUAL </syntaxhighlight> A standard-conforming implementation of this logic shows the following example, or as shown above: <syntaxhighlight lang="sql"> INSERT INTO phone_book SELECT 'John Doe', '555-1212' FROM LATERAL ( VALUES (1) ) AS t(c) UNION ALL SELECT 'Peter Doe','555-2323' FROM LATERAL ( VALUES (1) ) AS t(c) </syntaxhighlight> Oracle PL/SQL supports the {{mono|INSERT ALL}} statement, where multiple insert statements are terminated by a {{mono|SELECT}}:<ref>{{cite web | url=http://psoug.org/snippet/Oracle-PL-SQL-INSERT-ALL_589.htm | title=Oracle PL/SQL: INSERT ALL | work=psoug.org | access-date=2010-09-02 | archive-date=2010-09-16 | archive-url=https://web.archive.org/web/20100916052854/http://psoug.org/snippet/Oracle-PL-SQL-INSERT-ALL_589.htm | url-status=dead }}</ref> <syntaxhighlight lang="sql"> INSERT ALL INTO phone_book VALUES ('John Doe', '555-1212') INTO phone_book VALUES ('Peter Doe', '555-2323') SELECT * FROM DUAL; </syntaxhighlight> In [[Firebird (database server)|Firebird]] inserting multiple rows can be achieved like this: <syntaxhighlight lang="sql"> INSERT INTO phone_book (name, number) SELECT 'John Doe', '555-1212' FROM RDB$DATABASE UNION ALL SELECT 'Peter Doe', '555-2323' FROM RDB$DATABASE; </syntaxhighlight> Firebird, however, restricts the number of rows than can be inserted in this way, since there is a limit to the number of contexts that can be used in a single query. ===Copying rows from other tables=== An {{mono|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 {{mono|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. <syntaxhighlight lang="sql"> INSERT INTO phone_book2 SELECT * FROM phone_book WHERE name IN ('John Doe', 'Peter Doe') </syntaxhighlight> 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' [[database schema|schema]]s are not the same.) <syntaxhighlight lang="sql"> INSERT INTO phone_book2 (name, number) SELECT name, number FROM phone_book WHERE name IN ('John Doe', 'Peter Doe') </syntaxhighlight> The {{mono|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 {{mono|DEFAULT}} keyword can be used. <syntaxhighlight lang="sql"> INSERT INTO phone_book VALUES ( DEFAULT ) </syntaxhighlight> Sometimes databases also support alternative syntax for this; for example, MySQL allows omitting the {{mono|DEFAULT}} keyword, and T-SQL can use {{mono|DEFAULT VALUES}} instead of {{mono|VALUES(DEFAULT)}}. The {{mono|DEFAULT}} keyword can also be used in normal insertion to explicitly fill a column using that column's default value: <syntaxhighlight lang="sql"> INSERT INTO phone_book VALUES ( DEFAULT, '555-1212' ) </syntaxhighlight> 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 {{mono|INSERT}} statement for use in other SQL statements. Most systems do not allow SQL {{mono|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 {{mono|INSERT}} operation, and finally returns the generated key. For example, in Microsoft SQL Server, the key is retrieved via the {{mono|SCOPE_IDENTITY()}} special function, while in SQLite the function is named {{mono|last_insert_rowid()}}. * Using a database-specific {{mono|[[Select (SQL)|SELECT]]}} statement on a temporary table containing last inserted row(s). Db2 implements this feature in the following way: *:<syntaxhighlight lang="sql"> SELECT * FROM NEW TABLE ( INSERT INTO phone_book VALUES ( 'Peter Doe','555-2323' ) ) AS t </syntaxhighlight> **Db2 for [[z/OS]] implements this feature in the following way. **:<syntaxhighlight lang="sql"> SELECT EMPNO, HIRETYPE, HIREDATE FROM FINAL TABLE ( INSERT INTO EMPSAMP (NAME, SALARY, DEPTNO, LEVEL) VALUES('Mary Smith', 35000.00, 11, 'Associate') ); </syntaxhighlight> * Using a {{mono|[[Select (SQL)|SELECT]]}} statement after the {{mono|INSERT}} statement with a database-specific function that returns the generated primary key for the most recently inserted row. For example, {{mono|LAST_INSERT_ID()}} for [[MySQL]]. * Using a unique combination of elements from the original SQL {{mono|INSERT}} in a subsequent {{mono|SELECT}} statement. * Using a [[GUID]] in the SQL {{mono|INSERT}} statement and retrieving it in a {{mono|SELECT}} statement. * Using the {{mono|OUTPUT}} clause in the SQL {{mono|INSERT}} statement for MS-SQL Server 2005 and MS-SQL Server 2008. * Using an {{mono|INSERT}} statement with {{mono|RETURNING}} clause for [[Oracle database|Oracle]]. *:<syntaxhighlight lang="postgres"> INSERT INTO phone_book VALUES ( 'Peter Doe','555-2323' ) RETURNING phone_book_id INTO v_pb_id </syntaxhighlight> * Using an {{mono|INSERT}} statement with {{mono|RETURNING}} clause for [[PostgreSQL]] (since 8.2). The returned list is identical to the result of a {{mono|INSERT}}. **[[Firebird (database server)|Firebird]] has the same syntax in Data Modification Language statements (DSQL); the statement may add at most one row.<ref>{{cite web | url=http://www.firebirdsql.org/file/documentation/reference_manuals/reference_material/html/langrefupd25-insert.html#langrefupd25-insert-returning |title=Firebird 2.5 Language Reference Update | access-date=2011-10-24 }}</ref> In stored procedures, triggers and execution blocks (PSQL) the aforementioned Oracle syntax is used.<ref>{{cite web | url=http://firebirdsql.su/doku.php?id=returning |title=Firebird SQL Language Dictionary}}</ref> **:<syntaxhighlight lang="postgres"> INSERT INTO phone_book VALUES ( 'Peter Doe','555-2323' ) RETURNING phone_book_id </syntaxhighlight> * Using the {{mono|IDENTITY()}} function in [[H2 (DBMS)|H2]] returns the last identity inserted. *:<syntaxhighlight lang="sql"> SELECT IDENTITY(); </syntaxhighlight> ==Triggers== If [[database trigger|triggers]] are defined on the table on which the {{mono|INSERT}} statement operates, those triggers are evaluated in the context of the operation. {{mono|BEFORE INSERT}} triggers allow the modification of the values that shall be inserted into the table. {{mono|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== {{reflist}} ==External links== *[https://web.archive.org/web/20090915172636/http://download.oracle.com/docs/cd/E11882_01/server.112/e10592/statements_9014.htm Oracle SQL INSERT statement (Oracle Database SQL Language Reference, 11g Release 2 (11.2) on oracle.com)] *[http://www.fmsinc.com/MicrosoftAccess/query/snytax/append-query.html Microsoft Access Append Query Examples and SQL INSERT Query Syntax] *[https://dev.mysql.com/doc/refman/5.5/en/insert.html MySQL {{mono|INSERT}} statement (MySQL 5.5 Reference Manual)] {{SQL}} {{DEFAULTSORT:Insert (Sql)}} [[Category:SQL keywords]] [[Category:Articles with example SQL code]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite web
(
edit
)
Template:Mono
(
edit
)
Template:Pre
(
edit
)
Template:Reflist
(
edit
)
Template:SQL
(
edit
)
Template:Short description
(
edit
)