Оператор sql insert для вставки данных в таблицу бд

Примеры

Хрестоматийные примеры

Список наглядных примеров всех 4-ёх видов синтаксиса SQL-оператора :

Включение имён полей в одном выражении
INSERT INTO tbl_name (col_A, col_B, col_C) VALUES (1, 2, 3);

Включение нескольких строк выражении без указания имён полей

INSERT INTO tbl_name VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);

Включение нескольких строк выражении с одним указанием имён полей

INSERT INTO tbl_name (col_A, col_B, col_C) VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9);

Включение одной строки в выражении без указания имён полей

INSERT INTO tbl_name VALUES (1, 2, 3);

Кастомные примеры

Вставим в базу данных несколько записей, в которых расположена информация о зарегистрированных пользователях:

INSERT INTO authors VALUES (1, 'Maks', '123', '[email protected]', 'site', '', 'programmer', '', '', '', 0, 0);
INSERT INTO authors VALUES (2, 'Igor', '123', '[email protected]', 'site', '', 'programmer', '', '', '', 407, 0);
INSERT INTO authors VALUES (3, 'Sergey', '212', '[email protected]', 'site', '', 'designer', '', '', '', 408, 0);

The Basic INSERT Statement

Let’s start by looking at a basic INSERT statement.

Assume we have a table that looks like this:

STUDENT_ID FIRST_NAME LAST_NAME FEES_REQUIRED FEES_PAID ENROLMENT_DATE GENDER
1 John Smith 500 100 01/Feb/15 M
2 Susan Johnson 150 150 12/Jan/15 F
3 Tom Capper 350 320 06/Mar/15 M
4 Mark Holloway 500 410 20/Jan/15 M
5 Steven Webber 100 80 09/Mar/15 M
6 Julie Armstrong 100 12/Feb/15 F
7 Michelle Randall 250 23/Jan/15 F
8 Andrew Cooper 800 400 04/Mar/15 M
9 Robert Pickering 110 100 30/Jan/15 M
10 Tanya Hall 150 150 28/Jan/15 F

We can use the INSERT statement to insert a new record into the table.

To use the INSERT statement in SQL, we need a few things:

  • The name of the table we want to insert data into
  • The values to insert into the table
  • The columns to insert the values into (this is actually optional)

We don’t need the names of the columns, but it’s good practice to specify them. If we don’t, then there’s a risk that if the table structure changes, the INSERT statements will fail.

Let’s take a look at an INSERT statement for this table.

We start with the INSERT INTO, which are SQL keywords.

Then, we mention the table. In this case, it’s student.

Then, we open the brackets, and inside the brackets, we have a list of columns. These are each of the columns that we want to insert values in to. We don’t need to specify all of the columns (I’ll explain this more shortly), but in this case, I have.

Next comes the keyword VALUES.

Then, we open the brackets and specify the values that we want to insert. Inside this list is a comma-separated list of values. These values align with the columns we specified earlier.

The first value matches the first column, the second value matches the second column, and so on.

The values can be specified as:

  • Numbers, which don’t need to be inside quotes.
  • Strings, which need to be inside single quotes
  • NULL, which means a NULL value will be inserted (which we have done with this example for the enrolment_date column)
  • Functions or other columns, which we will get to later.

Finally, we close the brackets and end with a semicolon.

What will this query do? Let’s run it and find out.

1 row inserted.
STUDENT_ID FIRST_NAME LAST_NAME FEES_REQUIRED FEES_PAID ENROLMENT_DATE GENDER
1 John Smith 500 100 01/Feb/15 M
2 Susan Johnson 150 150 12/Jan/15 F
3 Tom Capper 350 320 06/Mar/15 M
4 Mark Holloway 500 410 20/Jan/15 M
5 Steven Webber 100 80 09/Mar/15 M
6 Julie Armstrong 100 12/Feb/15 F
7 Michelle Randall 250 23/Jan/15 F
8 Andrew Cooper 800 400 04/Mar/15 M
9 Robert Pickering 110 100 30/Jan/15 M
10 Tanya Hall 150 150 28/Jan/15 F
11 Jarrad Winston 700 300 (null) (null)

As you can see, a single record has been added to this table.

INSERT IGNORE statement

INSERT IGNORE is a very interesting keyword. When we insert multiple records in the using INSERT statement or INSERT INTO SELECT keyword, and sometimes the INSERT query failed due to an error, the entire INSERT query gets terminated. Suppose we are inserting thousands of records in a table, and due to error, the entire INSERT query fails and we must re-run the entire query. To avoid such issues, we can use the INSERT IGNORE statement.

If you are using the INSERT IGNORE statement to insert data in tables, even though the query encounters an error, the INSERT query does not fail.

To demonstrate, I have created a table named tbldepartment. The following is the table definition:

1
2
3
4
5

createtabletbldepartment

(

department_idvarchar(10)primarykey,

department_namevarchar(500)

)

Here, Department_ID column is a primary key so you cannot insert a duplicate value in it. Now, let’s insert a few rows by executing the following query:

1
2

insertignoreintotbldepartment (department_id,department_name)values

(‘DEP00001′,’IT’),(‘DEP00001′,’Sales’),(‘DEP00002′,’MARKETING’);

When you insert the record, you will receive the following warning.

Here, we have used the INSERT IGNORE statement; hence two rows must be inserted in the table. To verify that, execute the following SELECT query.

1 Select*fromtbldepartment;

Below is the output:

As you can see, instead of three values, only the DEP00001 and DEP00002 have been inserted.

When we use INSERT INTO IGNORE keyword, the MySQL will issue the warning, but it will try to adjust the value in the column. To understand that, insert another row in the tbldepartment table. The length of the department_id column is 10 characters. In the table, let us try to insert the department_id. The length of the value is higher than the defined length. Execute the following query:

1 insertignoreintotbldepartment(department_id,department_name)values(‘DEP000000001′,’Human Resource’);

The query will give the following warning:

As you can see, the query generates a warning. Now, run the SELECT query to view the data.

1 Select*fromtbldepartment;

Below is the output:

As you can see, that the row has been inserted, but MySQL has trimmed the value of the department_id column.

MySQL AUTO_INCREMENT Conversion to Other Databases

Converting MySQL AUTO_INCREMENT:

Oracle:

Oracle does not support AUTO_INCREMENT (IDENTITY) property on a column, but this functionality can be implemented using a sequence and a trigger:

   CREATE TABLE airlines
   ( 
     id NUMBER(10,0) PRIMARY KEY, 
     name VARCHAR2(90)
   ); 
 
   CREATE SEQUENCE airlines_seq START WITH 100 INCREMENT BY 1; 
 
   CREATE OR REPLACE TRIGGER airlines_seq_tr 
    BEFORE INSERT ON airlines FOR EACH ROW 
    WHEN (NEW.id IS NULL OR NEW.id = 0) 
   BEGIN 
    SELECT airlines_seq.NEXTVAL INTO :NEW.id FROM dual; 
   END; 
   

Note that a trigger is required as Oracle does not allow using NEXTVAL in DEFAULT clause for a column.

SQL Server:

SQL Server supports IDENTITY property and allows you to specify the increment:

   CREATE TABLE airlines
   ( 
     id INT IDENTITY(100, 1) PRIMARY KEY, 
     name VARCHAR(90)
   );

PostgreSQL:

PostgreSQL supports SERIAL data type that allows you to automatically generate IDs. Although SERIAL does not provide options to set the initial and increment values, you can modify the underlying sequence object:

   CREATE TABLE airlines
   ( 
     id SERIAL PRIMARY KEY, 
     name VARCHAR(90)
   );
 
   ALTER SEQUENCE airlines_id_seq RESTART WITH 100;

For more information, see Generating IDs in PostgreSQL.

Copy rows from other tables

You can use the statement to query data from one or more tables and insert it into another table as follows:

In this syntax, you use a SELECT which is called a subselect instead of the  clause . The subselect can contain the joins so that you can combine data from multiple tables. When executing the statement, the database system evaluates the subselect first before inserting data.

Suppose, you have a table named that has the same structure as the table. The following statement copies all rows from the table to the table.

You can verify the insert operation by using the following statement.

Now you should know how to use the SQL INSERT statement to insert one or more rows into a table.

Creating the INSERT INTO Query with dbForge Studio for MySQL

All the data manipulations, including the Create, Select, Insert, Update, Delete, or Drop operations can be easily performed with dbForge Studio for MySQL. The tool offers a rich set of advanced capabilities and features to boost your productivity and save your time when developing, managing, and deploying MySQL database in the easy-to-use interface.

Assume
we need to add a
new
customer to the database. In dbForge Studio for MySQL, we can use the
Generate
Script As feature
to insert one
or multiple
rows in the MySQL table.

To insert information about customers, do the following:

1. In Database Explorer, right-click the required table and select Generate Script As > INSERT > To New SQL Window. The SQL code editor opens containing the automatically generated script.

Оператор SELECT

Оператор  является наиболее часто используемым оператором SQL (и также называется проекцией — projection). Он позволяет извлекать все или некоторые данные из таблицы на основе определенных критериев.

Проще всего оператор  выглядит, когда применяется для извлечения всех данных таблицы:

SQL> SELECT * FROM employees;

Для извлечения только определенных столбцов необходимо указывать имена этих столбцов после ключевого слова , например:

SQL> SELECT first_name, last_name, hiredate FROM employees; 

При желании извлечь только первых десять строк таблицы можно использовать оператор  следующим образом:

SQL> SELECT * FROM employees WHERE rownum <11; 

Если требуется узнать только о том, какое количество строк содержится в таблице, оператор  применяется так:

SQL> SELECT COUNT(*) FROM employees; 

Если в таблице присутствуют дубликаты, можно использовать в операторе  конструкцию для исключения дублированных значений, как показано ниже:

SQL> SELECT DISTINCT username FROM V$SESSION;

С помощью необязательной конструкции  в операторе можно задавать различные условия и тем самым обеспечивать возврат только определенных строк. В таблице А.1 перечислены некоторые наиболее типичные условия, которые можно указывать в конструкции.

Символ Условие
Равно
Больше
Меньше
Меньше или равно
Больше или равно
Не равно

Ниже приведено несколько примеров применения конструкции :

SQL> SELECT employee_id WHERE salary = 50000;
SQL> SELECT employee_id WHERE salary < 50000;
SQL> SELECT employee_id WHERE salary > 50000;
SQL> SELECT employee_id WHERE salary <= 50000;
SQL> SELECT employee_id WHERE salary >= 50000;
SQL> SELECT employee_id WHERE salary ! 50000; 

Условие LIKE

Условие  позволяет ограничивать количество возвращаемых оператором  строк за счет применения операции сопоставления с образцом. Ниже приведен пример использования этого условия: 

SQL> SELECT employee_id, last_name FROM employees
2* WHERE last_name LIKE 'Fa%';
EMPLOYEE_ID  LAST_NAME
-----------  ----------
109          Faviet
202          Fay
SQL>

Образец, с которым должно выполняться сопоставление, должен быть заключен в одинарные кавычки (). В приведенном выше примере знак процента () обозначает, что за буквами может идти любая строка символов. То есть знак процента выступает в роли группового символа, способного замещать один или более символов, и, по сути, делает то же самое, что во многих операционных системах делает символ звездочки ()

Важно обратить внимание на то, что один символ подчеркивания () тоже может выступать групповым символом, но в отличие от знака процента способен замещать только один символ

Приоритет вставки INSERT LOW_PRIORITY / HIGH_PRIORITY

Установление приоритета нужно для решение проблем с конкурентными вставками. При вставках происходит блокировка строк и если 2 INSERT запроса требуют блокировки одних и тех же строк, для своего выполнения, то иногда может потребоваться повысить или понизить приоритет некоторых запросов, по отношению к другим. Это можно сделать указав приоритет LOW_PRIORITY или HIGH_PRIORITY

Наш запрос будет выглядеть так для LOW_PRIORITY:

INSERT LOW_PRIORITY INTO table1 (a, b, c) VALUES(1, 2, 3);

HIGH_PRIORITY:

INSERT HIGH_PRIORITY INTO table1 (a, b, c) VALUES(1, 2, 3);

Помогла ли Вам эта статья?

Да
Нет

MySQL INSERT Examples

Let’s explore some examples of using a MySQL INSERT statement when performing data-related tasks.

To start with, create three tables: Customers, Products01, and Smartphones by executing the following script:

MySQL INSERT command used to insert specified values

This command can be used when it is necessary to add values and columns for the specified rows. For example, add data only for the FirstName and LastName columns of the Customers table.

The command inserts values in the FirstName and LastName columns of the Customers MySQL table. Since the Age column uses Null as a default value, MySQL inserts Null into the Age column if you do not specify explicitly its value in the INSERT statement.

MySQL INSERT command used to insert values to all columns

This command can be used in order to add values to all columns. For example, add values to the Product01 table. Keep in mind that the order of values should match the order of columns in the table.

The statement inserts the specified values into all columns of the Product01 table.

MySQL INSERT command used to insert the default value

This command can be used when the default value is specified for the column. For example, the default value for the ProductCount column of the Products01 table equals 0. To insert the default value, execute either of the following queries:

The statement inserts the default value for the ProductCount column.

MySQL INSERT used to insert a specific value

To insert values into the columns, we can use the SET clause instead of the VALUES clause.

In the output, the statement inserts values into the columns based on the explicitly specified values in the SET clause.

MySQL INSERT used to insert data from another table

Using the SELECT clause in the MySQL INSERT INTO statement allows inserting the rows generated by the SELECT statement into the target MySQL table.

In this case, the INSERT INTO statement copies the rows you retrieved with the SELECT statement from the Smartphones table and inserts them into the Products01 table.

If you want to retrieve specific rows based on the condition, apply filtering options in the WHERE clause. Keep in mind that the structure of both tables should match; otherwise, it won’t work.

This command adds to the Products01 table values from the Smartphones table where the price equals 34000.

You can also copy and insert specified columns from another table. However, in this case, make sure that there is no record with the specified name in the target table; otherwise, it fails, and the error occurs.

MySQL INSERT – ignore errors when inserting data

In case you face errors or any unexpected behavior while executing the insertion of rows into the MySQL table, the statement execution is interrupted. Rows with valid and invalid values are not added to the table. For example, execute the following query:

This statement returns the error because the record with this ID already exists. Now, modify the statement with IGNORE. It allows you to insert rows with valid values but overpass the rows with invalid values.

As a result, the script was executed without errors. MySQL will notify you that rows were added to the table.

Table of contents

Learn MySQL: Querying data from MySQL server using the SELECT statement
Learn MySQL: What is pagination
Learn MySQL: Sorting and Filtering data in a table
Learn MySQL: Add data in tables using the INSERT statement
Learn MySQL: Create and drop temp tables
Learn MySQL: Delete and Update Statements
Learn MySQL: The Basics of MySQL Stored Procedures
Learn MySQL: The Basics of MySQL Views
Learn MySQL: An overview of MySQL Binary Logs
Learn MySQL: An overview of the mysqlbinlog utility
Learn MySQL: Run multiple instances of MySQL Server on Windows 10
Learn MySQL: MySQL String Functions
Learn MySQL: Control Flow functions
Learn MySQL: Install MySQL server 8.0.19 using a noinstall Zip archive
Learn MySQL: MySQL Copy table

Examples

CREATE TABLE t (
  id INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
  f VARCHAR(1)) 
ENGINE = InnoDB;

INSERT INTO t(f) VALUES('a');

SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                1 |
+------------------+

INSERT INTO t(f) VALUES('b');

INSERT INTO t(f) VALUES('c');

SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                3 |
+------------------+

INSERT INTO t(f) VALUES('d'),('e');

SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                4 |
+------------------+

SELECT * FROM t;
+----+------+
| id | f    |
+----+------+
|  1 | a    |
|  2 | b    |
|  3 | c    |
|  4 | d    |
|  5 | e    |
+----+------+

SELECT LAST_INSERT_ID(12);
+--------------------+
| LAST_INSERT_ID(12) |
+--------------------+
|                 12 |
+--------------------+

SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|               12 |
+------------------+

INSERT INTO t(f) VALUES('f');

SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|                6 |
+------------------+

SELECT * FROM t;
+----+------+
| id | f    |
+----+------+
|  1 | a    |
|  2 | b    |
|  3 | c    |
|  4 | d    |
|  5 | e    |
|  6 | f    |
+----+------+

SELECT LAST_INSERT_ID(12);
+--------------------+
| LAST_INSERT_ID(12) |
+--------------------+
|                 12 |
+--------------------+

INSERT INTO t(f) VALUES('g');

SELECT * FROM t;
+----+------+
| id | f    |
+----+------+
|  1 | a    |
|  2 | b    |
|  3 | c    |
|  4 | d    |
|  5 | e    |
|  6 | f    |
|  7 | g    |
+----+------+

Оператор INSERT

Оператор  позволяет добавлять в таблицу новые данные, в том числе и дублированные в случае отсутствия требований уникальности со стороны первичного ключа или индекса. В общем, синтаксис оператора выглядит следующим образом:

INSERT INTO <таблица> 
VALUES (<значение i, ... , значение j>);

Ниже приведен пример применения оператора :

В этом примере имена столбцов были указаны потому, что заполнить данным требовалось только некоторые из столбцов вставлявшейся строки. Остальные столбцы были оставлены пустыми, что вполне приемлемо при условии, что ни один из них не был определен как не допускающий нулевых значений ().

При желании вставить значения во все столбцы таблицы можно использовать более простой оператор , подобный тому, что показан ниже:

SQL> INSERT INTO department
VALUES
(34567, 'payroll', 'headquarters', 'dallas');
1 row created.
SQL>

Если требуется вставить все столбцы из одной таблицы в другую, можно использовать такой оператор :

SQL> INSERT INTO b SELECT * FROM a
WHERE city='DALLAS'; 

В случае если окажется, что таблицы  не существует, можно использовать оператор, как показано ниже: 

SQL> CREATE table b as SELECT * FROM a;

Как вставить значение из другой таблицы INSERT INTO … SELECT …

Допустим у нас есть еще одна таблица которая по структуре точно такая же как и первая. Нам в таблицу table2 нужно вставить все строки из table1.

Вставляем значения из table1 в таблицу table2:

INSERT INTO table2 (a, b, c) SELECT a, b, c FROM table1;

Вам следует позаботиться об уникальности ключей, если они есть в таблице, в которую мы вставляем. Например при дублировании PRIMARY KEY мы получим следующее сообщение об ошибке:

/* ERROR 1062 (23000): Duplicate entry '100' for key 'PRIMARY' */

Если вы делаете не какую-то единичную вставку при переносе данных, а где-то сохраните этот запрос, например в вашем PHP скрипте, то всегда перечисляйте столбцы.

Как не рекомендуется делать (без перечисления столбцов):

INSERT INTO table2 SELECT * FROM table1;

Если у вас со временем изменится количество столбцов в таблице, то запрос перестанет работать. При выполнении запроса MySQL в лучшем случае просто будет возвращать ошибку:

/* Ошибка SQL (1136): Column count doesn't match value count at row 1 */

Либо еще хуже: значения вставятся не в те столбцы.

MySQL INSERT INTO – General Syntax

When inserting a single row into the MySQL table, the syntax is as follows:

In the INSERT INTO query, you
should specify the following information:

  • : A MySQL table to which you want to add a new row.
  • : A list of columns the new row will contain. The columns are separated by a comma in round brackets.
  • : A list of values separated by a comma in round brackets that will be used for each corresponding column.

The number of columns and values should match; otherwise, it fails.

When inserting multiple rows into a MySQL table, the syntax is as follows:

Here you should enter the
following information:

  • : A table into which you want to insert data.
  • : A list of columns to store data. The columns are separated by a comma in round brackets.
  • : A list of values to be inserted in one row. The values are separated by a comma in round brackets. The number of values in each list should match the number of columns specified in .

In addition, rows are separated by commas in the VALUES clause.

Рейтинг
( Пока оценок нет )
Editor
Editor/ автор статьи

Давно интересуюсь темой. Мне нравится писать о том, в чём разбираюсь.

Понравилась статья? Поделиться с друзьями:
Люкс-хост
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: