Insert into select oracle syntax. T-SQL Basics. DML. Inserting multiple rows

In addition to the SELECT statement discussed earlier, the Data Manipulation Language (DML) contains three other statements: INSERT, UPDATE, and DELETE. Like the SELECT statement, these three statements operate on either tables or views. This article discusses the INSERT statement, and the other two statements are discussed in the next article.

INSERT statement inserts rows (or parts of rows) into a table. There are two different forms of this instruction:

INSERT tab_name [(col_list)] DEFAULT VALUES | VALUES (( DEFAULT | NULL | expression ) [ ,...n]) INSERT INTO tab_name | view_name [(col_list)] (select_statement | execute_statement) Syntax conventions

The first form of the instruction allows you to insert one row (or part of it) into the table. And the second form of the INSERT statement allows you to insert into a table the result set of a SELECT statement or a stored procedure executed by an EXECUTE statement. The stored procedure must return data to be inserted into the table. When used with an INSERT statement, a SELECT statement can select values ​​from a different or the same table into which the data is being inserted, as long as the data types of the corresponding columns are compatible.

For both forms, the data type of each inserted value must be compatible with the data type of the corresponding table column. All string and temporary data must be enclosed in quotes; Numeric values ​​do not need to be enclosed in quotation marks.

Inserting a single row

For both forms of the INSERT statement, specifying the column list explicitly is optional. Not listing columns is the same as specifying all columns in the table.

DEFAULT VALUES parameter inserts default values ​​for all columns. Columns with the TIMESTAMP data type or IDENTITY property are inserted by default with values ​​that are automatically generated by the system. For columns of other data types, the corresponding non-null default value is inserted if available, or NULL otherwise. If a column does not allow null values ​​and does not have a default value defined, the INSERT statement fails and a message is displayed.

The example below inserts rows into the Employee table in the SampleDb database, demonstrating the use of an INSERT statement to insert a small amount of data into the database:

USE SampleDb; INSERT INTO Employee VALUES (34990, "Andrey", "Batonov", "d1"); INSERT INTO Employee VALUES (38640, "Alexey", "Vasin", "d3");

There are two different ways inserting values ​​into a new row. The INSERT statement in the example below explicitly uses the NULL keyword and inserts a NULL value into the corresponding column:

USE SampleDb; INSERT INTO Employee VALUES (34991, "Andrey", "Batonov", NULL);

To insert values ​​into some (but not all) columns of a table, you usually need to explicitly specify those columns. Unspecified columns must either allow NULL values ​​or have a default value defined.

USE SampleDb; INSERT INTO Employee(Id, FirstName, LastName) VALUES (34992, "Andrey", "Batonov");

The previous two examples are equivalent. In the Employee table, the only column that allows NULL values ​​is the DepartmentNumber column, and all other columns were disabled by the NOT NULL clause in the CREATE TABLE statement.

Order of values ​​in VALUES offer INSERT statements may differ from the order specified in the CREATE TABLE statement. In this case, their order must match the order in which the corresponding columns are listed in the column list. Below is an example of inserting data in a different order from the original:

USE SampleDb; INSERT INTO Employee(DepartamentNumber, LastName, Id, FirstName) VALUES ("d1", "Batonov", 34993, "Andrey");

Inserting multiple rows

The second form of the INSERT statement inserts one or more rows selected by a subquery into the table. The example below shows how to insert rows into a table using the second form of the INSERT statement. In this case, a query is executed to select the numbers and names of departments located in Moscow, and the resulting result set is loaded into a new table created earlier.

The new MoscowDepartment table created in the example above has the same columns as the existing Department table, except for the missing Location column. The subquery in the INSERT statement selects all rows in the Department table for which the Location column value is "Moscow", which are then inserted into the new table created at the beginning of the query.

The example below shows another way to insert rows into a table using the second form of the INSERT statement. In this case, a query is executed to select personnel numbers, project numbers, and project start dates for all employees with the position “Manager” who work on project p2 and then load the resulting result set into a new table created at the beginning of the query:

USE SampleDb; CREATE TABLE ManagerTeam(EmpId INT NOT NULL, ProjectNumber CHAR (4) NOT NULL, EnterDate DATE); INSERT INTO ManagerTeam (EmpId, ProjectNumber, EnterDate) SELECT EmpId, ProjectNumber, EnterDate FROM Works_on WHERE Job = "Manager";

Before inserting rows using the INSERT statement, the MoscowDepartment and ManagerTeam tables (in the examples above) were empty. If the table already existed and contained rows with data, then new rows would be added to it.

In previous sections, we looked at the work of retrieving data from pre-created tables. Now it’s time to figure out how we can create/delete tables, add new records and delete old ones. For these purposes in SQL There are operators such as: CREATE- creates a table, ALTER- changes the table structure, DROP- deletes a table or field, INSERT- adds data to the table. Let's start getting acquainted with this group of operators from the operator INSERT.

1. Adding entire lines

As the name suggests, the operator INSERT used to insert (append) rows to a database table. Adding can be done in several ways:

  • - add one full line
  • - add part of a line
  • - add query results.

So, to add a new row to a table, we need to specify the table name, list the column names and specify the value for each column using the construct INSERT INTO table_name (field1, field2 ...) VALUES (value1, value2...). Let's look at an example.

INSERT INTO Sellers (ID, Address, City, Seller_name, Country) VALUES("6", "1st Street", "Los Angeles", "Harry Monroe", "USA")

You can also change the order of column names, but at the same time you need to change the order of the values ​​in the parameter VALUES.

2. Adding part of the lines

In the previous example, when using the operator INSERT we have explicitly marked the table column names. Using this syntax, we can skip some columns. This means that you enter values ​​for some columns but do not provide them for others. For example:

INSERT INTO Sellers (ID, City, Seller_name) VALUES("6", "Los Angeles", "Harry Monroe")

In this example, we did not specify a value for two columns Address And Country. You can exclude some columns from the statement INSERT INTO, if this allows the table definition. In this case, one of the conditions must be met: this column is defined as valid NULL(absence of any value) or the specified default value in the table definition. This means that if no value is specified, the default value will be used. If you are missing a column from a table that does not allow values ​​to appear in its rows NULL and does not have a default value defined, the DBMS will generate an error message and the row will not be added.

3. Adding selected data

In the previous example, we inserted data into tables by entering them manually in the query. However, the operator INSERT INTO allows us to automate this process if we want to insert data from another table. For this purpose in SQL there is such a construction as INSERT INTO ... SELECT .... This design allows you to simultaneously select data from one table and insert it into another. Let's assume we have another table Sellers_EU with a list of sellers of our goods in Europe and we need to add them to the general table Sellers. The structure of these tables is the same (the same number of columns and the same names), but the data is different. To do this, we can write the following query:

INSERT INTO Sellers (ID, Address, City, Seller_name, Country) SELECTID, Address, City, Seller_name, Country FROM Sellers_EU

You need to pay attention so that the values ​​of internal keys are not repeated (field ID), otherwise an error will occur. Operator SELECT may also include suggestions WHERE to filter data. It should also be noted that the DBMS does not pay attention to the names of the columns contained in the statement SELECT, only the order in which they are arranged is important to her. Therefore, the data in the first specified column that was selected due to SELECT, will be filled in the first column of the table in any case Sellers, specified after the operator INSERT INTO, regardless of the field name.

4. Copying data from one table to another

Often when working with databases, there is a need to create copies of any tables for the purpose of backup or modification. To do full copy tables in SQL there is a separate operator SELECT INTO. For example, we need to create a copy of the table Sellers, you will need to write the request as follows:

SELECT * INTO Sellers_new FROM Sellers

Unlike the previous design INSERT INTO ... SELECT ... When data is added to an existing table, the design copies the data to the new table. You can also say that the first construct imports data, and the second exports. When using the design SELECT ... INTO ... FROM ... The following should be considered:

  • - you can use any sentences in the operator SELECT, such as GROUP BY And HAVING
  • - you can use a join to add data from multiple tables
  • - data can only be added to one table, no matter how many tables it was taken from.

Team adds rows to the table or main table view.

Sql INSERT Command Syntax

Insert Command Syntax


Basic keywords and parameters of the INSERT command
  • schema- permission identifier, usually matching the name of some user
  • table view- the name of the table into which the rows should be inserted; if a view is specified, the rows are inserted into the view's main table
  • subquery_1- a subquery that the server processes in the same way as a view
  • column- a table or view column into which the value from the phrase is entered for each inserted row VALUES or subquery; if one of the table's columns is omitted from this list, the column value for the inserted row is the default column value defined when the table was created. If a column list is completely omitted, the clause VALUES or the query must determine values ​​for all columns in the table
  • VALUES- defines a string of values ​​that will be inserted into the table or view; the meaning must be defined in the sentence VALUES for each column in the list of columns
  • subquery_2- a subquery that returns rows inserted into the table; the select list of this subquery must have the same number of columns as the statement column list

Statement with the phrase VALUES adds a single row to the table. This line contains the values ​​defined by the phrase VALUES.
Statement with subquery instead of a phrase VALUES adds all the rows returned by the subquery to the table. The server processes subquery and inserts each returned row into the table. If the subquery does not select any rows, the server does not insert any rows into the table.
Subquery can access any table or view, including the target assertion table . The server assigns values ​​to fields in new rows based on the internal position of the columns in the table and the order of the phrase values VALUES or in the query selection list. If any columns are missing from the column list, the server assigns them the default values ​​defined when the table was created. If any of these columns have a NOT NULL constraint then the server returns an error indicating that the constraint was violated and aborts the INSERT statement.
When an INSERT statement is issued, any INSERT trigger defined on the table is enabled.

INSERT INTO Example 1

INSERT INTO dept VALUES(50, "PRODUCTS", "SAN FRANCISCO");

INSERT INTO Customers (city, cname, cnum) VALUES('London', 'Hoffman', 2001);

INSERT INTO Example 2
The following command copies the data of company employees whose commissions exceed 25% of income into the bonus table:

INSERT INTO bonus SELECT ename, job, sal, comm FROM emp WHERE comm > 0.25 * sal;

INSERT INTO Example 3
If you need to insert NULL-value, you must specify it as a normal value as follows:

INSERT INTO Salespeople VALUES (1001,'Peel',NULL,12);

INSERT INTO Example 4
The command can be used to retrieve values ​​from one table and place them in another using a query. To do this, it is enough to replace the sentence VALUES to the corresponding request:

INSERT INTO Londonstaff SELECT * FROM Salespeople WHERE city = 'London';

MySQL INSERT

To insert new rows into a MySQL database, use INSERT command, command examples are given below:
INSERT INTO Example 1.
Insert new line to the table table_name.

INSERT INTO

INSERT INTO Example 2.
Inserting a new row into the table table_name indicating the insertion of data into the columns we need.

INSERT INTO table_name VALUES('1','165','0','name');

In the database MySQL It is possible to insert multiple new lines using one command.
INSERT INTO Example 3.
Inserting multiple rows into table table_name.

INSERT INTO table_name (tbl_id, chislo, chislotwo, name) VALUES ('1′,'159′,'34','name1′), ('2′,'14','61','name2′), ('3 ′,'356′,'8′,'name3');

sql query INSERT INTO makes sense when a database table has been created. That is, the table exists, has a name, created rows and columns. the table is created by the operator: , the table is modified by the operator .

sql query INSERT INTO - query syntax

sql query INSERT INTO has the following syntax:

INSERT INTO table_name (in parentheses, if necessary, insert a list of columns where you want to insert data) VALUES inserted data1, inserted data2, inserted data3.

You can insert an IGNORE option between INSERT and INTRO. It is not required. Needed to protect primary keys when editing a table. Otherwise, if duplication of primary keys occurs during editing, then when inserting the IGNORE option, the first row with the primary key will remain in the table being edited. Other primary keys will be deleted. By default, we omit this option.

There are optional options LOW_PRIORITY and DELAYED. They determine the priorities for adding information to the database. The first specifies waiting for the database to be released, the second means buffering information.

The line in the query: INSERT with the VALUES phrase will allow you to add a single row to the database table. The VALUES clause contains the values ​​of this data.

Subqueries can be specified instead of the VALUES phrase. INSERT with a subquery adds the rows returned by the subquery to the table. The database server processes the subquery and inserts all returned rows into the table. The server does not insert rows unless the subquery selects them.

  • subquery_1 - a subquery that the server processes in the same way as the view
  • subquery_2 is a subquery that returns rows inserted into the table. The list of this subquery must have the same number of columns as the INSERT column list.

Subqueries are practically not used in a MySQL database.

Examples of sql query INSERT INTO in a MySQL database

We insert new rows into the MySQL database using the INSERT INTRO command.

First example.

Insert new rows into table table_name.

INSERT INTO table_name VALUES ('2′,'145′,'1′,'name');

This means that we want to insert the values ​​2,145,1,name into the table table_name columns. Since the columns are not specified, the values ​​are filled in all columns of the table.

Example two.

Insert information into the required (specified) columns of the table_name table.

INSERT INTO table_name (client_customer, client_subclient, client_mail) VALUES ('name1','subname1',' [email protected]′), (‘name2′,’subname2′,’ [email protected]′), (‘name3′,’subname3′,(’ [email protected]′);

Igor Serov especially for the site "".

The INSERT statement inserts new records into a table. In this case, the column values ​​can be literal constants, or be the result of executing a subquery. In the first case, a separate INSERT statement is used to insert each row; in the second case, as many rows will be inserted as are returned by the subquery.

The operator syntax is as follows:

    INSERT INTO [ (,...) ]

    (VALUES(,…))

  1. | (DEFAULT VALUES)

As you can see from the presented syntax, the list of columns is optional (this is said square brackets in the syntax description). If it is missing, the list of inserted values ​​must be complete, that is, provide values ​​for all columns of the table. In this case, the order of the values ​​must correspond to the order specified by the CREATE TABLE statement for the table into which the rows are inserted. In addition, these values ​​must be of the same data type as the columns in which they are entered. As an example, consider inserting a row into the Product table created by the following CREATE TABLE statement:

    CREATE TABLE product

    maker char (1) NOT NULL,

    model varchar(4) NOT NULL,

    type varchar(7) NOT NULL

Suppose you want to add the PC model 1157 from manufacturer B to this table. This can be done with the following statement:

    INSERT INTO Product

    VALUES ("B" , 1157 , "PC" ) ;

If you specify a list of columns, you can change their “natural” order:

    INSERT INTO Product (type, model, maker)

    VALUES ("PC" , 1157 , "B" ) ;

It would seem that this is a completely unnecessary feature, which only makes the design more cumbersome. However, it wins if the columns have default values. Consider the following table structure:

    CREATE TABLE product_D

    maker char (1) NULL,

    model varchar(4) NULL,

    type varchar (7 ) NOT NULL DEFAULT "PC"

Note that here the values ​​of all columns have default values ​​(the first two are NULL and the last column is type - PC). Now we could write:

    INSERT INTO Product_D (model, maker)

    VALUES(1157, "B");

In this case, the missing value when inserting a row will be replaced by the default value - PC. Note that if a column is not given a default value in a CREATE TABLE statement and a NOT NULL constraint is specified to prohibit the use of NULL in that table column, then the default value of NULL is assumed.

The question arises: is it possible not to specify a list of columns and, nevertheless, use the default values? The answer is yes. To do this, instead of explicitly specifying the value, use the reserved word DEFAULT :

    INSERT INTO Product_D

    VALUES ("B" , 1158 , DEFAULT ) ;

Since all columns have default values, to insert a row with default values ​​you could write:

    INSERT INTO Product_D

    VALUES(DEFAULT, DEFAULT, DEFAULT);

However, for this case there is a special construction DEFAULT VALUES (see operator syntax), with which the above operator can be rewritten in the form

    INSERT INTO Product_D DEFAULT VALUES ;

Note that when inserting a row into a table, all restrictions imposed on this table are checked. These could be primary key or unique index constraints, CHECK constraints, or referential integrity constraints. If any constraint is violated, the row insertion will be rejected. Let's now consider the case of using a subquery. Suppose we need to insert into the Product_D table all rows from the Product table related to personal computer models (type = 'PC'). Since the values ​​we need are already in some table, manually generating inserted rows is, firstly, ineffective and, secondly, may allow input errors. Using a subquery solves these problems:

The use of the “*” symbol in the subquery is justified in this case, since the order of the columns is the same for both tables. If this were not the case, a column list would have to be applied in either the INSERT statement, the subquery, or both, which would match the order of the columns:

Here, as before, you can specify not all columns if you want to use the existing default values, for example:

In this case, the type column of the Product_D table will be substituted with the default value PC for all inserted rows.

Note that when using a subquery containing a predicate, only those rows for which the predicate value is TRUE (not UNKNOWN !) will be inserted. In other words, if the type column in the Product table were NULLable, and that value was present in a number of rows, then those rows would not be inserted into the Product_D table.

The artificial technique of using a subquery that forms a row with the UNION ALL clause allows you to overcome the limitation on inserting one row in the INSERT statement when using the row constructor in the VALUES clause. So if we need to insert several rows using one INSERT statement, we can write:

    INSERT INTO Product_D

    SELECT "B" AS maker, 1158 AS model, "PC" AS type

    UNION ALL

    SELECT "C" , 2190 , "Laptop"

    UNION ALL

    SELECT "D" , 3219 , "Printer" ;

Using UNION ALL is preferable to UNION even if the absence of duplicate rows is guaranteed, since in this case no check will be performed to eliminate duplicates.

It should be noted that inserting multiple tuples using the row constructor is already implemented in Relational database management system (DBMS), developed by Microsoft Corporation.Structured Query Language) is a universal computer language used to create, modify and manipulate data in relational databases. SQL Server 2008. Given this possibility, the last query can be rewritten as:

    INSERT INTO Product_D VALUES

    ("B", 1158, "PC"),

    ("C", 2190, "Laptop"),


Top