ecosmak.ru

Insert into select oracle syntax. SQL query INSERT INTO - fill the database with information

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.
Inserting a new row into 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');

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 that are assigned values ​​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 the tables 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.

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!

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 make a full copy of a table, SQL provides a separate statement 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.

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

Loading...