Information about Insert (sql)

A SQL INSERT statement adds one or more records to a table in a relational database. An INSERT statement can only insert data into a single table.

Basic form

Insert statements have the following form:
  • INSERT INTO table (column1, [column2, ... ]) VALUES (value1, [value2, ...])
The number of 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 INSERT statement must satisfy all the applicable constraints (such as primary keys, CHECK constraints, and 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:

INSERT INTO phone_book (name, number) VALUES ('John Doe', '555-1212');

When values for all columns in the table are specified, then a shorthand may be used, taking advantage of the order of the columns when the table was created:
  • INSERT INTO table VALUES (value1, [value2, ...])
Example (assuming that 'name' and 'number' are the only columns in the 'phone_book' table):

INSERT INTO phone_book VALUES ('John Doe', '555-1212');

Advanced forms

Multirow inserts

An SQL feature (since SQL-92) is the use of row value constructors to insert multiple rows at a time in a single SQL statement:

INSERT INTO table (column1, [column2, ... ]) VALUES (value1a, [value1b, ...]), (value2a, [value2b, ...]), ...

This feature is supported by DB2, PostgreSQL (since version 8.2) and MySQL.

Example (assuming that 'name' and 'number' are the only columns in the 'phone_book' table):

INSERT INTO phone_book VALUES ('John Doe', '555-1212'), ('Peter Doe', '555-2323');

which may be seen as a shorthand for the two statements

INSERT INTO phone_book VALUES ('John Doe', '555-1212'); INSERT INTO phone_book VALUES ('Peter Doe', '555-2323');

Note that the two separate statements may have different semantics (especially with respect to statement 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: INSERT INTO phone_book SELECT 'Prakash Patel', '555-1212' UNION ALL SELECT 'Peter Doe', '555-2323';

Note that this is not a valid SQL statement according to the SQL standard () due to the incomplete subselect clause.

To do the same in Oracle use the DUAL table, which always consists of a single row only: INSERT INTO phone_book SELECT 'Prakash Patel', '555-1212' FROM DUAL UNION ALL SELECT 'Peter Doe','555-2323' FROM DUAL

A standard-conforming implementation of this logic shows the following example, or as shown above: INSERT INTO phone_book SELECT 'Prakash Patel', '555-1212' FROM LATERAL ( VALUES (1) ) AS t(c) UNION ALL SELECT 'Peter Doe','555-2323' FROM LATERAL ( VALUES (1) ) AS t(c)

Copying rows from other tables

An INSERT statement can also be used to retrieve data from other, 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], [phoneNumber] ) SELECT [name], [phoneNumber] 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.

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 a 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.
  • 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
  • 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.
  • 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 an INSERT statement with RETURNING clause for Oracle, which can only be used within a PL/SQL block
INSERT INTO phone_book VALUES ( 'Peter Doe','555-2323' ) RETURNING phone_book_id INTO v_pb_id

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 mechanisms.

References

SQL
Paradigm: multi-paradigm
Appeared in: 1974
Designed by: Donald D. Chamberlin and Raymond F. Boyce
Developer: IBM
Latest release: SQL:2003/ 2003
Typing discipline: static, strong
Major implementations: Many
SQL
..... Click the link for more information.
A relational database is a database that conforms to the relational model, and refers to a database's data and schema (the database's structure of how that data is arranged).
..... Click the link for more information.
In relational database design, a unique key or primary key is a candidate key to uniquely identify each row in a table. A unique key or primary key comprises a single column or set of columns.
..... Click the link for more information.
A check constraint (also known as table check constraint) is a condition that defines valid data when adding or updating an entry in a table of a relational database. A check constraint is applied to each row in the table. The constraint must be a predicate.
..... Click the link for more information.
Null is a special marker used to indicate that a data value is unknown in the Structured Query Language (SQL). Introduced by the creator of the relational database model, Dr. E.F.
..... Click the link for more information.
DB2 is one of IBM's lines of relational database management system (or, as IBM now calls it, data server) software products within IBM's broader Information Management Software line.
..... Click the link for more information.
PostgreSQL is an object-relational database management system (ORDBMS). It is released under a BSD-style license and is thus free software. As with many other open-source programs, PostgreSQL is not controlled by any single company, but relies on a global community of developers
..... Click the link for more information.
MySQL (pronounced (IPA) /mɑɪ ɛs kjuː ɛl/, "my S-Q-L"[1]) is a multithreaded, multi-user SQL database management system (DBMS)[2]
..... Click the link for more information.
A database trigger is procedural code that is automatically executed in response to certain events on a particular table in a database. Triggers can restrict access to specific data, perform logging, or audit data modifications.
..... Click the link for more information.
The DUAL table is a special one-row table present by default in all Oracle database installations. It is suitable for use in selecting a pseudocolumn such as SYSDATE or USER

The table has a single VARCHAR2(1) column called DUMMY that has a value of "X"

Example use


..... Click the link for more information.
A surrogate key in a database is a unique identifier for either an entity in the modeled world or an object in the database. The surrogate key is not derived from application data.
..... Click the link for more information.
An SQL SELECT statement returns a result set of records from one or more tables.

It retrieves zero or more rows from one or more base tables, temporary tables, or views in a database.
..... Click the link for more information.
An SQL SELECT statement returns a result set of records from one or more tables.

It retrieves zero or more rows from one or more base tables, temporary tables, or views in a database.
..... Click the link for more information.
An SQL SELECT statement returns a result set of records from one or more tables.

It retrieves zero or more rows from one or more base tables, temporary tables, or views in a database.
..... Click the link for more information.
A Globally Unique Identifier or GUID (IPA pronunciation: ['gu.ɪd] or [gwɪd]
..... Click the link for more information.
An SQL SELECT statement returns a result set of records from one or more tables.

It retrieves zero or more rows from one or more base tables, temporary tables, or views in a database.
..... Click the link for more information.
Oracle Database (commonly referred to as Oracle RDBMS or simply as Oracle), a relational database management system (RDBMS) software product released by Oracle Corporation, has become a major feature of database computing.
..... Click the link for more information.
PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's proprietary server-based procedural extension to the SQL database language. (Some other SQL database management systems offer languages similar to PL/SQL.) Its syntax strongly resembles that of Ada.
..... Click the link for more information.
A database trigger is procedural code that is automatically executed in response to certain events on a particular table in a database. Triggers can restrict access to specific data, perform logging, or audit data modifications.
..... Click the link for more information.
A database management system (DBMS) is computer software designed for the purpose of managing databases. Typical examples of DBMSs include Oracle, DB2, Microsoft Access, Microsoft SQL Server, PostgreSQL, MySQL, FileMaker and Sybase Adaptive Server Enterprise.
..... Click the link for more information.
database is a structured collection of records or data that is stored in a computer system so that a computer program or person using a query language can consult it to answer queries. The records retrieved in answer to queries are information that can be used to make decisions.
..... Click the link for more information.
A data model is not just a way of structuring data: it also defines a set of operations that can be performed on the data. The relational model, for example, defines operations such as select, project, and join.
..... Click the link for more information.
flat file database describes any of various means to encode a data model (most commonly a table) as a plain text file.

Unordered

Unordered storage typically stores the records in the order they are inserted, while having
..... Click the link for more information.
The relational model for database management is a database model based on predicate logic and set theory. It was first formulated and proposed in 1969 by Edgar Codd with aims that included avoiding, without loss of completeness, the need to write computer programs to
..... Click the link for more information.
A distributed database management system is a software system that permits the management of a distributed database and makes the distribution transparent to the users. A distributed database is a collection of multiple, logically interrelated databases distributed over a computer network.
..... Click the link for more information.
ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee that database transactions are processed reliably. In the context of databases, a single logical operation on the data is called a transaction.
..... Click the link for more information.
Null is a special marker used to indicate that a data value is unknown in the Structured Query Language (SQL). Introduced by the creator of the relational database model, Dr. E.F.
..... Click the link for more information.
A relational database is a database that conforms to the relational model, and refers to a database's data and schema (the database's structure of how that data is arranged).
..... Click the link for more information.
Relational algebra, an offshoot of first-order logic, is a set of relations closed under operators. Operators operate on one or more relations to yield a relation. Relational algebra is a part of computer science.
..... Click the link for more information.
The relational calculus refers to the two calculi, the tuple relational calculus and the domain relational calculus, that are part of the relational model for databases and that provide a declarative way to specify database queries.
..... Click the link for more information.


This article is copied from an article on Wikipedia.org - the free encyclopedia created and edited by online user community. The text was not checked or edited by anyone on our staff. Although the vast majority of the wikipedia encyclopedia articles provide accurate and timely information please do not assume the accuracy of any particular article. This article is distributed under the terms of GNU Free Documentation License.
Herod_Archelaus


page counter