Transact-SQL - data insertion. SQL query INSERT INTO - fill the database with information How insert works in sql


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 (the square brackets in the syntax description indicate this). 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"),

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

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 covers the INSERT statement, and the other two statements are covered 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 to insert 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.

Hi all! This article will discuss how you can add data to table in Microsoft SQL Server, if you are already at least a little familiar with the T-SQL language, then you probably realized that now we will talk about the INSERT statement, as well as how it can be used to add data to a table.

Let's start, as usual, with a little theory.

INSERT statement in T-SQL

INSERT is a T-SQL instruction that is designed to add data to a table, i.e. creating new records. This instruction can be used both to add a single row to a table and to insert data in bulk. The INSERT statement requires permission to insert data ( INSERT) to the target table.

There are several ways to use the INSERT statement on the piece of data that needs to be inserted:

  • Listing specific values ​​to insert;
  • Specifying a data set as a SELECT query;
  • Specifying a data set in the form of a procedure call that returns tabular data.

Simplified syntax

INSERT [table] ( list of columns...) VALUES ( list of values...) Or SELECT sample request Or EXECUTE procedure

  • INSERT INTO is a command to add data to a table;
  • Table is the name of the target table into which you want to insert new records;
  • The column list is a list of column names of the table into which the data will be inserted, separated by commas;
  • VALUES is a table value constructor with which we specify the values ​​that we will insert into the table;
  • The list of values ​​is the values ​​that will be inserted, separated by commas. They are listed in the order that the columns appear in the column list;
  • SELECT is a query to select data to insert into a table. The result set that the query returns must match the list of columns;
  • EXECUTE is a procedure call to obtain data for insertion into a table. The result set that the stored procedure returns must match the list of columns.

This is roughly what the simplified syntax of the INSERT INTO statement looks like; in most cases, this is how you will add new records to tables.

The list of columns into which you will insert data does not need to be written, in which case their order will be determined based on the actual order of the columns in the table. You must remember this order when you specify values ​​to insert or write a query to select. Personally, I recommend that you still indicate a list of columns into which you plan to add data.

You should also remember that the list of columns and the list of values, respectively, must contain so-called required columns; these are those that cannot contain the NULL value. If you do not specify them, and the column does not have a default value, an error will occur.

I would also like to note that the data type of the values ​​that you will insert must match the data type of the column into which this value will be inserted, or at least support implicit conversion. But I advise you to control the data type ( format) values, both in the list of values ​​and in the SELECT query.

Enough theory, let's move on to practice.

Initial data

In order to add data to the table, we need the table itself, so let's create it and try to add records to it.

Note! All examples will be run in Microsoft SQL Server 2016 Express.

CREATE TABLE TestTable( IDENTITY(1,1) NOT NULL, (100) NOT NULL, NOT NULL)

Our test table will contain a list of products with prices.

Also in the examples we will use a procedure that returns a table value to add data to the table, so let's create that too.

CREATE PROCEDURE TestProcedure AS BEGIN SELECT ProductName, Price FROM TestTable END

For example, it will return data from the newly created TestTable table.

Note!

As you understand, reading this material implies having some knowledge of the T-SQL language, so if something is not clear to you, I recommend that you familiarize yourself with the following materials:

Example 1 – Adding a new record to a table using the table value constructor

First let's try adding one record and immediately look at the result, i.e. Let's write a request for a sample.

INSERT INTO TestTable(ProductName, Price) VALUES ("Computer", 100) GO SELECT * FROM TestTable

You see that after the table name we listed the names of the columns to which we will add data, separated by commas, then we indicated the keyword VALUES and in brackets also, in the same order, separated by commas, we wrote the values ​​that we want to insert.

After the INSERT statement, I wrote a SELECT statement and separated them with a GO statement.

Now let's imagine that we need to add a few lines. We will write the following request for this.

INSERT INTO TestTable(ProductName, Price) VALUES ("Computer", 100), ("Keyboard", 20), ("Monitor", 50) GO SELECT * FROM TestTable


Example 2 - Adding new rows to a table using a SELECT query

Very often there is a need to add a lot of data to a table, for example, based on a select query, i.e. SELECT. To do this, instead of VALUES, we just need to specify the request.

INSERT INTO TestTable(ProductName, Price) SELECT ProductName, Price FROM TestTable WHERE Id >


In this example, we wrote a SELECT query that returns data from the TestTable table, but not all of it, but only those with an ID greater than 2. And the result was inserted into the same TestTable table.

As an example of how you can add records to a table without specifying a list of columns, let's write another data insertion query that will do exactly the same thing as the query above, only it will not list the columns to insert.

INSERT INTO TestTable SELECT ProductName, Price FROM TestTable WHERE Id > 2 GO SELECT * FROM TestTable


In this case, we are sure that in the TestTable table the first column is ProductName, and the second is Price, so we can afford to write it that way. But, again, in practice it is better to specify a list of columns.

If you noticed, in all the examples I did not specify the Id column, but we have it, no errors occurred, since this column has the IDENTITY property, it automatically generates identifiers, so inserting data into such a column simply cannot be done.

Example 3 - Adding new records to a table using a stored procedure

Now let's insert the data into the table that the stored procedure will return to us. The meaning here is the same, instead of VALUES and instead of a request we indicate a procedure call. But as you understand, the order and number of columns returned by the procedure must strictly match the list of columns to be inserted ( even if the column list is not specified).

INSERT INTO TestTable(ProductName, Price) EXEC TestProcedure GO SELECT * FROM TestTable


I hope this material helped you understand the instructions. INSERT INTO, and that’s all I have for now!

This statement adds one or more records to a table (performs an append query).

Syntax

Request to add multiple records:

INSERT INTO final_object [(field1[, field2[, ...]])]
SELECT [ source.]field1[, field2[, ...]
FROM table_expression

Request to add one record:

INSERT INTO final_object [(field1[, field2[, ...]])]
VALUES ( field1[, field2[, ...])

The INSERT INTO statement consists of the following elements:

Part

Description

final_object

The name of the table or query where records are added.

field1, field2

After the argument final_object- names of fields to which data is added; after the argument source- names of the fields from which data is extracted.

external_database

Path to external database. For a description of the path, see the article on the IN clause.

source

The name of the table or query from which records are copied.

table_expression

One or more table names from which you want to retrieve records. This argument can be the name of an individual table, a result expression constructed using an INNER JOIN, LEFT JOIN, or RIGHT JOIN, or a stored query.

value1, value2

Values ​​that will be added to specific fields of the new record. Each value is inserted into the field corresponding to its position in the list: value1 added to field1 new entry, value2- V field2 etc. You must separate values ​​with a comma and enclose text fields in quotation marks (" ").

Notes

The INSERT INTO statement can add a single record to a table using the syntax above. In this case, you specify names and values ​​for each field in the record. You must specify all the fields in the record to which values ​​are assigned and the corresponding values. If you do not specify a field value, it will be assigned the default value or NULL. Records are added to the end of the table.

The INSERT INTO statement can also be used to add a set of records from another table or query using the SELECT... FROM clause as shown above (see Query Syntax for Adding Multiple Records). In this case, the SELECT clause specifies the fields to add to the specified final_object.

Source or final_object can be a table or a query. When a query is given, the Microsoft Access database engine adds records to all tables that it returns.

Using the INSERT INTO statement is optional. If specified, it must precede the SELECT statement.

If the target table contains a primary key, ensure that the values ​​you add to one or more of the primary key fields are unique and distinct from NULL; otherwise the entries will not be added.

If records are added to a table with a Counter field and you want to renumber them, do not include the Counter field in the query. Include the Counter field in the query if you want to preserve the original values ​​from the field.

You can add records to a table in another database using the IN clause.

To create a table, use the SELECT... INTO statement to query to create the table.

Before you run an add query, use a select query with the same selection criteria to use the results to determine which records will be added.

An append query copies records from one or more tables to another table. In this case, the tables containing the added records remain unchanged.

Instead of adding records from another table, you can set the value of each field in a separate new record using the VALUES clause. If a field list is omitted, the VALUES clause must include the corresponding values ​​for each table field; otherwise, the INSERT operation will fail. Use the INSERT INTO statement along with the VALUES clause for each additional record that you want to create.







2024 gtavrl.ru.