Insert

SQL References

SQL Keywords
ADD
ADD CONSTRAINT
ALTER
ALTER COLUMN
ALTER TABLE
ALL
AND
ANY
AS
ASC
BACKUP DATABASE
BETWEEN
CASE
CHECK
COLUMN
CONSTRAINT
CREATE
CREATE DATABASE
CREATE INDEX
CREATE OR REPLACE VIEW
CREATE TABLE
CREATE PROCEDURE
CREATE UNIQUE INDEX
CREATE VIEW
DATABASE
DEFAULT
DELETE
DESC
DISTINCT
DROP
DROP COLUMN
DROP CONSTRAINT
DROP DATABASE
DROP DEFAULT
DROP INDEX
DROP TABLE
DROP VIEW
EXEC
EXISTS
FOREIGN KEY
FROM
FULL OUTER JOIN
GROUP BY
HAVING
IN
INDEX
INNER JOIN
INSERT INTO
INSERT INTO SELECT
IS NULL
IS NOT NULL
JOIN
LEFT JOIN
LIKE
LIMIT
NOT
NOT NULL
OR
ORDER BY
OUTER JOIN
PRIMARY KEY
PROCEDURE
RIGHT JOIN
ROWNUM
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
SET
TABLE
TOP
TRUNCATE TABLE
UNION
UNION ALL
UNIQUE
UPDATE
VALUES
VIEW
WHERE

MySQL Functions
String Functions
ASCII
CHAR_LENGTH
CHARACTER_LENGTH
CONCAT
CONCAT_WS
FIELD
FIND_IN_SET
FORMAT
INSERT
INSTR
LCASE
LEFT
LENGTH
LOCATE
LOWER
LPAD
LTRIM
MID
POSITION
REPEAT
REPLACE
REVERSE
RIGHT
RPAD
RTRIM
SPACE
STRCMP
SUBSTR
SUBSTRING
SUBSTRING_INDEX
TRIM
UCASE
UPPER

Numeric Functions
ABS
ACOS
ASIN
ATAN
ATAN2
AVG
CEIL
CEILING
COS
COT
COUNT
DEGREES
DIV
EXP
FLOOR
GREATEST
LEAST
LN
LOG
LOG10
LOG2
MAX
MIN
MOD
PI
POW
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SUM
TAN
TRUNCATE

Date Functions
ADDDATE
ADDTIME
CURDATE
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURTIME
DATE
DATEDIFF
DATE_ADD
DATE_FORMAT
DATE_SUB
DAY
DAYNAME
DAYOFMONTH
DAYOFWEEK
DAYOFYEAR
EXTRACT
FROM_DAYS
HOUR
LAST_DAY
LOCALTIME
LOCALTIMESTAMP
MAKEDATE
MAKETIME
MICROSECOND
MINUTE
MONTH
MONTHNAME
NOW
PERIOD_ADD
PERIOD_DIFF
QUARTER
SECOND
SEC_TO_TIME
STR_TO_DATE
SUBDATE
SUBTIME
SYSDATE
TIME
TIME_FORMAT
TIME_TO_SEC
TIMEDIFF
TIMESTAMP
TO_DAYS
WEEK
WEEKDAY
WEEKOFYEAR
YEAR
YEARWEEK

Advanced Functions
BIN
BINARY
CASE
CAST
COALESCE
CONNECTION_ID
CONV
CONVERT
CURRENT_USER
DATABASE
IF
IFNULL
ISNULL
LAST_INSERT_ID
NULLIF
SESSION_USER
SYSTEM_USER
USER
VERSION

SQL Server Functions
String Functions
ASCII
CHAR
CHARINDEX
CONCAT
Concat with +
CONCAT_WS
DATALENGTH
DIFFERENCE
FORMAT
LEFT
LEN
LOWER
LTRIM
NCHAR
PATINDEX
QUOTENAME
REPLACE
REPLICATE
REVERSE
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
TRANSLATE
TRIM
UNICODE
UPPER

Numeric Functions
ABS
ACOS
ASIN
ATAN
ATN2
AVG
CEILING
COUNT
COS
COT
DEGREES
EXP
FLOOR
LOG
LOG10
MAX
MIN
PI
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SQUARE
SUM
TAN

Date Functions
CURRENT_TIMESTAMP
DATEADD
DATEDIFF
DATEFROMPARTS
DATENAME
DATEPART
DAY
GETDATE
GETUTCDATE
ISDATE
MONTH
SYSDATETIME
YEAR

Advanced Functions
CAST
COALESCE
CONVERT
CURRENT_USER
IIF
ISNULL
ISNUMERIC
NULLIF
SESSION_USER
SESSIONPROPERTY
SYSTEM_USER
USER_NAME

MS Access Functions
String Functions
Asc
Chr
Concat with &
CurDir
Format
InStr
InstrRev
LCase
Left
Len
LTrim
Mid
Replace
Right
RTrim
Space
Split
Str
StrComp
StrConv
StrReverse
Trim
UCase

Numeric Functions
Abs
Atn
Avg
Cos
Count
Exp
Fix
Format
Int
Max
Min
Randomize
Rnd
Round
Sgn
Sqr
Sum
Val

Date Functions
Date
DateAdd
DateDiff
DatePart
DateSerial
DateValue
Day
Format
Hour
Minute
Month
MonthName
Now
Second
Time
TimeSerial
TimeValue
Weekday
WeekdayName
Year

Other Functions
CurrentUser
Environ
IsDate
IsNull
IsNumeric

SQL Quick Ref

Example — Using VALUES keyword

The simplest way to create a SQL Server INSERT query to list the values using the VALUES keyword.

For example:

INSERT INTO employees
(employee_id, last_name, first_name)
VALUES
(10, 'Anderson', 'Sarah');

This SQL Server INSERT statement would result in one record being inserted into the employees table. This new record would have an employee_id of 10, a last_name of ‘Anderson’, and a first_name of ‘Sarah’.

You can also use this syntax to insert more than one record at a time. For example:

INSERT INTO employees
(employee_id, last_name, first_name)
VALUES
(10, 'Anderson', 'Sarah'),
(11, 'Johnson', 'Dale');

This INSERT example shows how to insert more than one record using the VALUES keyword. In this example, two records are inserted into the employees table. The first record has an employee_id of 10, a last_name of ‘Anderson’, and a first_name of ‘Sarah’. The second record has an employee_id of 11, a last_name of ‘Johnson’, and a first_name of ‘Dale’.

This would be equivalent to the following two INSERT statements:

Example — Using INSERT Statement to Insert One Record

The simplest way use the INSERT statement is to insert one record into a table using the VALUES keyword. Let’s look at an example of how to do this in SQL.

In this example, we have a table called categories with the following data:

category_id category_name
25 Deli
50 Produce
75 Bakery
100 General Merchandise
125 Technology

Let’s insert a new category record. Enter the following SQL statement:

Try It

INSERT INTO categories
(category_id, category_name)
VALUES
(150, 'Miscellaneous');

There will be 1 record inserted. Select the data from the categories table again:

SELECT * FROM categories;

These are the results that you should see:

category_id category_name
25 Deli
50 Produce
75 Bakery
100 General Merchandise
125 Technology
150 Miscellaneous

This example would insert one record into the categories table. This new record would have a category_id of 150 and a category_name of ‘Miscellaneous’.

In this example, because you are providing values for all of the columns in the categories table, you could omit the column names and instead write the INSERT statement like this:

Try It

INSERT INTO categories
VALUES
(150, 'Miscellaneous');

INSERT INTO SELECT

The command copies data
from one table and inserts it into another table.

The following SQL copies «Suppliers» into «Customers» (the columns
that are not filled with data, will contain NULL):

Example

INSERT INTO Customers (CustomerName,
City, Country)
SELECT SupplierName, City, Country FROM Suppliers;

The following SQL copies «Suppliers» into «Customers» (fill all
columns):

Example

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country)SELECT SupplierName, ContactName, Address, City, PostalCode,
Country FROM Suppliers;

The following SQL copies only the German suppliers into «Customers»:

Example

INSERT INTO Customers (CustomerName,
City, Country)
SELECT SupplierName, City, Country FROM SuppliersWHERE Country=’Germany’;

Basic syntax

Let’s look at the basic syntax of the INSERT INTO MySQL command:

INSERT INTO `table_name`(column_1,column_2,...) VALUES (value_1,value_2,...);

HERE

  • INSERT INTO `table_name` is the command that tells MySQL server to add a new row into a table named `table_name.`
  • (column_1,column_2,…) specifies the columns to be updated in the new MySQL row
  • VALUES (value_1,value_2,…) specifies the values to be added into the new row

When supplying the data values to be inserted into the new table, the following should be considered:

  • String data types – all the string values should be enclosed in single quotes.
  • Numeric data types- all numeric values should be supplied directly without enclosing them in single or double-quotes.
  • Date data types – enclose date values in single quotes in the format ‘YYYY-MM-DD’.

Example:

Suppose that we have the following list of new library members that need to be added to the database.

Full names Date of Birth gender Physical address Postal address Contact number Email Address
Leonard Hofstadter   Male Woodcrest   0845738767  
Sheldon Cooper   Male Woodcrest   0976736763  
Rajesh Koothrappali   Male Fairview   0938867763  
Leslie Winkle 14/02/1984 Male     0987636553  
Howard Wolowitz 24/08/1981 Male South Park P.O. Box 4563 0987786553 lwolowitz@email.me

Let’s INSERT data one by one. We will start with Leonard Hofstadter. We will treat the contact number as a numeric data type and not enclose the number in single quotes.

INSERT INTO `members` (`full_names`,`gender`,`physical_address`,`contact_number`) VALUES ('Leonard Hofstadter','Male','Woodcrest',0845738767);

Executing the above script drops the 0 from Leonard’s contact number. This is because the value will be treated as a numeric value, and the zero (0) at the beginning is dropped since it’s not significant.

To avoid such problems, the value must be enclosed in single quotes as shown below –

INSERT INTO `members` (`full_names`,`gender`,`physical_address`,`contact_number`)  VALUES ('Sheldon Cooper','Male','Woodcrest', '0976736763');

In the above case, zero(0) will not be dropped

Changing the order of the columns has no effect on the INSERT query in MySQL as long as the correct values have been mapped to the correct columns.

The query shown below demonstrates the above point.

INSERT INTO `members` (`contact_number`,`gender`,`full_names`,`physical_address`)  VALUES ('0938867763','Male','Rajesh Koothrappali','Woodcrest');

The above queries skipped the date of birth column. By default, MySQL will insert NULL values in columns that are omitted in the INSERT query.

Let’s now insert the record for Leslie, which has the date of birth supplied. The date value should be enclosed in single quotes using the format ‘YYYY-MM-DD’.

INSERT INTO `members` (`full_names`,`date_of_birth`,`gender`,`physical_address`,`contact_number`)  VALUES ('Leslie Winkle','1984-02-14','Male','Woodcrest', '0987636553');

All of the above queries specified the columns and mapped them to values in the MySQL insert statement. If we are supplying values for ALL the columns in the table, then we can omit the columns from the MySQL insert query.

Example:-

INSERT INTO `members`  VALUES (9,'Howard Wolowitz','Male','1981-08-24',
'SouthPark','P.O. Box 4563', '0987786553', 'lwolowitzemail.me');

Let’s now use the SELECT statement to view all the rows in the member’s table.

SELECT * FROM `members`;
membership_ number full_ names gender date_of_ birth physical_address postal_ address contct_ number email
1 Janet Jones Female 21-07-1980 First Street Plot No 4 Private Bag 0759 253 542 janetjones@yagoo.cm
2 Janet Smith Jones Female 23-06-1980 Melrose 123 NULL NULL jj@fstreet.com
3 Robert Phil Male 12-07-1989 3rd Street 34 NULL 12345 rm@tstreet.com
4 Gloria Williams Female 14-02-1984 2nd Street 23 NULL NULL NULL
5 Leonard Hofstadter Male NULL Woodcrest NULL 845738767 NULL
6 Sheldon Cooper Male NULL Woodcrest NULL 0976736763 NULL
7 Rajesh Koothrappali Male NULL Woodcrest NULL 0938867763 NULL
8 Leslie Winkle Male 14-02-1984 Woodcrest NULL 0987636553 NULL
9 Howard Wolowitz Male 24-08-1981 SouthPark P.O. Box 4563 0987786553 lwolowitz@email.me

Notice the contact number for Leonard Hofstadter has dropped the zero (0) from the contact number. The other contact numbers have not dropped the zero (0) at the beginning.

Parameters

One or both of the following hints:

  • A load hint, one of the following: , , or

Specifies a schema, by default . If schema is any schema other than , you must supply the schema name. For example:

myschema.thisDbObject

If you specify a database, it must be the current database.

The target table. You cannot invoke on a projection. This can be a flex table.

A comma-delimited list of one or more target columns in this table, listed in any order.  clause values are mapped to columns in the same order. If you omit this list, Vertica maps  clause values to columns according to column order in the table definition.

A list of target columns is invalid with .

Fills all columns with their default values as specified in the table definition.

You cannot specify a list of target columns with this option.

A comma-delimited list of one or more values to insert in the target columns, where each value is one of the following:

  • expression resolves to a value to insert in the target column. The expression must not nest other expressions or include Vertica meta-functions.
  • inserts the default value as specified in the table definition.

If no value is supplied for a column, Vertica implicitly adds a value, if defined. Otherwise Vertica inserts a value. If the column is defined as , returns an error.

Specifies a query that returns the rows to insert. Isolation level applies only to the clauses and works like any query.

Table of contents

Learn SQL: CREATE DATABASE & CREATE TABLE Operations
Learn SQL: INSERT INTO TABLE
Learn SQL: Primary Key
Learn SQL: Foreign Key
Learn SQL: SELECT statement
Learn SQL: INNER JOIN vs LEFT JOIN
Learn SQL: SQL Scripts
Learn SQL: Types of relations
Learn SQL: Join multiple tables
Learn SQL: Aggregate Functions
Learn SQL: How to Write a Complex SELECT Query
Learn SQL: The INFORMATION_SCHEMA Database
Learn SQL: SQL Data Types
Learn SQL: Set Theory
Learn SQL: User-Defined Functions
Learn SQL: User-Defined Stored Procedures
Learn SQL: SQL Views
Learn SQL: SQL Triggers
Learn SQL: Practice SQL Queries
Learn SQL: SQL Query examples
Learn SQL: Create a report manually using SQL queries
Learn SQL: SQL Server date and time functions
Learn SQL: Create SQL Server reports using date and time functions
Learn SQL: SQL Server Pivot Tables
Learn SQL: SQL Server export to Excel
Learn SQL: Intro to SQL Server loops
Learn SQL: SQL Server Cursors
Learn SQL: SQL Best Practices for Deleting and Updating data
Learn SQL: Naming Conventions
Learn SQL: SQL-Related Jobs
Learn SQL: Non-Equi Joins in SQL Server
Learn SQL: SQL Injection
Learn SQL: Dynamic SQL
Learn SQL: How to prevent SQL Injection attacks

SQL Учебник

SQL ГлавнаяSQL ВведениеSQL СинтаксисSQL SELECTSQL SELECT DISTINCTSQL WHERESQL AND, OR, NOTSQL ORDER BYSQL INSERT INTOSQL Значение NullSQL Инструкция UPDATESQL Инструкция DELETESQL SELECT TOPSQL MIN() и MAX()SQL COUNT(), AVG() и …SQL Оператор LIKESQL ПодстановочныйSQL Оператор INSQL Оператор BETWEENSQL ПсевдонимыSQL JOINSQL JOIN ВнутриSQL JOIN СлеваSQL JOIN СправаSQL JOIN ПолноеSQL JOIN СамSQL Оператор UNIONSQL GROUP BYSQL HAVINGSQL Оператор ExistsSQL Операторы Any, AllSQL SELECT INTOSQL INSERT INTO SELECTSQL Инструкция CASESQL Функции NULLSQL ХранимаяSQL Комментарии

Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the «Customers» table:

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico

And a selection from the «Suppliers» table:

SupplierID SupplierName ContactName Address City Postal Code Country
1 Exotic Liquid Charlotte Cooper 49 Gilbert St. Londona EC1 4SD UK
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA
3 Grandma Kelly’s Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA

SQL Справочник

SQL Ключевые слова
ADD
ADD CONSTRAINT
ALTER
ALTER COLUMN
ALTER TABLE
ALL
AND
ANY
AS
ASC
BACKUP DATABASE
BETWEEN
CASE
CHECK
COLUMN
CONSTRAINT
CREATE
CREATE DATABASE
CREATE INDEX
CREATE OR REPLACE VIEW
CREATE TABLE
CREATE PROCEDURE
CREATE UNIQUE INDEX
CREATE VIEW
DATABASE
DEFAULT
DELETE
DESC
DISTINCT
DROP
DROP COLUMN
DROP CONSTRAINT
DROP DATABASE
DROP DEFAULT
DROP INDEX
DROP TABLE
DROP VIEW
EXEC
EXISTS
FOREIGN KEY
FROM
FULL OUTER JOIN
GROUP BY
HAVING
IN
INDEX
INNER JOIN
INSERT INTO
INSERT INTO SELECT
IS NULL
IS NOT NULL
JOIN
LEFT JOIN
LIKE
LIMIT
NOT
NOT NULL
OR
ORDER BY
OUTER JOIN
PRIMARY KEY
PROCEDURE
RIGHT JOIN
ROWNUM
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
SET
TABLE
TOP
TRUNCATE TABLE
UNION
UNION ALL
UNIQUE
UPDATE
VALUES
VIEW
WHERE

MySQL Функции
Функции строк
ASCII
CHAR_LENGTH
CHARACTER_LENGTH
CONCAT
CONCAT_WS
FIELD
FIND_IN_SET
FORMAT
INSERT
INSTR
LCASE
LEFT
LENGTH
LOCATE
LOWER
LPAD
LTRIM
MID
POSITION
REPEAT
REPLACE
REVERSE
RIGHT
RPAD
RTRIM
SPACE
STRCMP
SUBSTR
SUBSTRING
SUBSTRING_INDEX
TRIM
UCASE
UPPER
Функции чисел
ABS
ACOS
ASIN
ATAN
ATAN2
AVG
CEIL
CEILING
COS
COT
COUNT
DEGREES
DIV
EXP
FLOOR
GREATEST
LEAST
LN
LOG
LOG10
LOG2
MAX
MIN
MOD
PI
POW
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SUM
TAN
TRUNCATE
Функции дат
ADDDATE
ADDTIME
CURDATE
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURTIME
DATE
DATEDIFF
DATE_ADD
DATE_FORMAT
DATE_SUB
DAY
DAYNAME
DAYOFMONTH
DAYOFWEEK
DAYOFYEAR
EXTRACT
FROM_DAYS
HOUR
LAST_DAY
LOCALTIME
LOCALTIMESTAMP
MAKEDATE
MAKETIME
MICROSECOND
MINUTE
MONTH
MONTHNAME
NOW
PERIOD_ADD
PERIOD_DIFF
QUARTER
SECOND
SEC_TO_TIME
STR_TO_DATE
SUBDATE
SUBTIME
SYSDATE
TIME
TIME_FORMAT
TIME_TO_SEC
TIMEDIFF
TIMESTAMP
TO_DAYS
WEEK
WEEKDAY
WEEKOFYEAR
YEAR
YEARWEEK
Функции расширений
BIN
BINARY
CASE
CAST
COALESCE
CONNECTION_ID
CONV
CONVERT
CURRENT_USER
DATABASE
IF
IFNULL
ISNULL
LAST_INSERT_ID
NULLIF
SESSION_USER
SYSTEM_USER
USER
VERSION

SQL Server функции
Функции строк
ASCII
CHAR
CHARINDEX
CONCAT
Concat with +
CONCAT_WS
DATALENGTH
DIFFERENCE
FORMAT
LEFT
LEN
LOWER
LTRIM
NCHAR
PATINDEX
QUOTENAME
REPLACE
REPLICATE
REVERSE
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
TRANSLATE
TRIM
UNICODE
UPPER
Функции чисел
ABS
ACOS
ASIN
ATAN
ATN2
AVG
CEILING
COUNT
COS
COT
DEGREES
EXP
FLOOR
LOG
LOG10
MAX
MIN
PI
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SQUARE
SUM
TAN
Функции дат
CURRENT_TIMESTAMP
DATEADD
DATEDIFF
DATEFROMPARTS
DATENAME
DATEPART
DAY
GETDATE
GETUTCDATE
ISDATE
MONTH
SYSDATETIME
YEAR
Функции расширений
CAST
COALESCE
CONVERT
CURRENT_USER
IIF
ISNULL
ISNUMERIC
NULLIF
SESSION_USER
SESSIONPROPERTY
SYSTEM_USER
USER_NAME

MS Access функции
Функции строк
Asc
Chr
Concat with &
CurDir
Format
InStr
InstrRev
LCase
Left
Len
LTrim
Mid
Replace
Right
RTrim
Space
Split
Str
StrComp
StrConv
StrReverse
Trim
UCase
Функции чисел
Abs
Atn
Avg
Cos
Count
Exp
Fix
Format
Int
Max
Min
Randomize
Rnd
Round
Sgn
Sqr
Sum
Val
Функции дат
Date
DateAdd
DateDiff
DatePart
DateSerial
DateValue
Day
Format
Hour
Minute
Month
MonthName
Now
Second
Time
TimeSerial
TimeValue
Weekday
WeekdayName
Year
Другие функции
CurrentUser
Environ
IsDate
IsNull
IsNumeric

SQL ОператорыSQL Типы данныхSQL Краткий справочник

SQL INSERT INTO SELECT Examples

The following SQL statement copies «Suppliers» into «Customers» (the columns
that are not filled with data, will contain NULL):

Example

INSERT INTO Customers (CustomerName,
City, Country)
SELECT SupplierName, City, Country FROM Suppliers;

The following SQL statement copies «Suppliers» into «Customers» (fill all
columns):

Example

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country)SELECT SupplierName, ContactName, Address, City, PostalCode,
Country FROM Suppliers;

The following SQL statement copies only the German suppliers into «Customers»:

Example

INSERT INTO Customers (CustomerName,
City, Country)
SELECT SupplierName, City, Country FROM SuppliersWHERE Country=’Germany’;

❮ Previous
Next ❯

SQL INSERT

Команда INSERT добавляет строки в таблицу или представление основной таблицы.

Синтаксис команды Sql INSERT

Синтаксис команды Insert

Основные ключевые слова и параметры команды INSERT

  • schema — идентификатор полномочий, обычно совпадающий с именем некоторого пользователя
  • table view — имя таблицы, в которую строки должны быть вставлены; если указано представление, то строки вставляются в основную таблицу представления
  • subquery_1 — подзапрос, который сервер обрабатывает тем же самым способом как представление
  • column — столбец таблицы или представления, в который для каждой вставленной строки вводится значение из фразы VALUES или подзапроса; если один из столбцов таблицы опускается из этого списка, значением столбца для вставленной строки является значение по умолчанию столбца, определенное при создании таблицы. Если полностью опускается список столбца, предложение VALUES или запрос должен определить значения для всех столбцов в таблице
  • VALUES — определяет строку значений, которые будут вставлены в таблицу или представление; значение должно быть определено в предложении VALUES для каждого столбца в списке столбцов
  • subquery_2 — подзапрос, который возвращает строки, вставляемые в таблицу; выборочный список этого подзапроса должен иметь такое же количество столбцов, как в списке столбцов утверждения INSERT

Утверждение INSERT с фразой VALUES добавляет одиночную строку к таблице. Эта строка содержит значения, определенные фразой VALUES.
Утверждение INSERT с подзапросом вместо фразы VALUES добавляет к таблице все строки, возвращенные подзапросом. Сервер обрабатывает подзапрос и вставляет каждую возвращенную строку в таблицу. Если подзапрос не выбирает никакие строки, сервер не вставляет никакие строки в таблицу.Подзапрос может обратиться к любой таблице или представлению, включая целевую таблицу утверждения INSERT. Сервер назначает значения полям в новых строках, основанных на внутренней позиции столбцов в таблице и порядке значений фразы VALUES или в списке выбора запроса. Если какие-либо столбцы пропущены в списке столбцов, сервер назначает им значения по умолчанию, определенные при создании таблицы. Если любой из этих столбцов имеет NOT NULL ограничение то сервер возвращает ошибку, указывающую, что ограничение было нарушено и отменяет утверждение INSERT.
При выдаче утверждения INSERT включается любой INSERT — триггер, определенный на таблице.

INSERT INTO

INSERT INTO Пример 1

INSERT INTO Пример 2
Нижеприведенная команда копирует данные сотрудников фирмы, комисионные которых превышают 25% от дохода в таблицу bonus:

INSERT INTO Пример 3
Если нужно вставить NULL-значение, необходимо указать его как обычное значение следующим образом:

INSERT INTO Пример 4
Команду INSERT можно применить для того, чтобы извлечь значения из одной таблицы и разместить их в другой, воспользовавшись для этого запросом. Для этого достаточно заменить предложение VALUES на соответствующий запрос:

Insert Into Table

To fill a table in MySQL, use the «INSERT INTO» statement.

Example

Insert a record in the «customers» table:

var mysql = require(‘mysql’);var con = mysql.createConnection({ 
host: «localhost»,  user: «yourusername»,  password: «yourpassword»,
  database: «mydb»
});con.connect(function(err) {  if (err) throw err;  console.log(«Connected!»);  var sql = «INSERT INTO customers (name, address)
VALUES (‘Company Inc’, ‘Highway 37’)»; 
con.query(sql, function (err, result) {    if (err) throw err;    console.log(«1 record inserted»);  });});

Save the code above in a file called «demo_db_insert.js», and run the file:

Run «demo_db_insert.js»

C:\Users\Your Name>node demo_db_insert.js

Which will give you this result:

Connected!1 record inserted

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.

Часто задаваемые вопросы

Вопрос: Я создал базу данных клиентов. Я знаю, что вы используете Oracle оператор INSERT для вставки информации в базу данных, но как я могу убедиться, что не ввел ту же информацию о клиенте снова?

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

Например, если у вас была таблица с названием clients с первичным ключом client_id, вы можете использовать следующий INSERT:

Oracle PL/SQL

INSERT INTO clients
(client_id, client_name, client_type)
SELECT supplier_id, supplier_name, ‘advertising’
FROM suppliers
WHERE NOT EXISTS (SELECT *
FROM clients
WHERE clients.client_id = suppliers.supplier_id);

1
2
3
4
5
6
7

INSERTINTOclients
(client_id,client_name,client_type)

SELECTsupplier_id,supplier_name,’advertising’

FROMsuppliers

WHERENOTEXISTS(SELECT*

FROMclients

WHEREclients.client_id=suppliers.supplier_id);

Это Oracle предложение INSERT вставляет несколько записей с подзапросом.

Если вы хотите вставить одну запись, вы можете использовать следующее Oracle предложение INSERT:

Oracle PL/SQL

INSERT INTO clients
(client_id, client_name, client_type)
SELECT 10345,
‘IBM’,
‘advertising’
FROM dual
WHERE NOT EXISTS (SELECT *
FROM clients
WHERE clients.client_id = 10345);

1
2
3
4
5
6
7
8
9

INSERTINTOclients
(client_id,client_name,client_type)

SELECT10345,

‘IBM’,

‘advertising’

FROMdual

WHERENOTEXISTS(SELECT*

FROMclients

WHEREclients.client_id=10345);

Использование таблицы dual позволяет ввести значения в операторе select, даже если значения не хранятся в настоящее время в таблице.

Вопрос: Как я могу вставить несколько строк явных данных в одном предложении INSERT в Oracle?

Ответ: Ниже приведен пример того, как можно вставить 3 строки в таблицу suppliers в Oracle, используя оператор INSERT:

Oracle PL/SQL

INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (1000, ‘IBM’)
INTO suppliers (supplier_id, supplier_name) VALUES (2000, ‘Microsoft’)
INTO suppliers (supplier_id, supplier_name) VALUES (3000, ‘Google’)
SELECT * FROM dual;

1
2
3
4
5

INSERTALL

INTOsuppliers(supplier_id,supplier_name)VALUES(1000,’IBM’)

INTOsuppliers(supplier_id,supplier_name)VALUES(2000,’Microsoft’)

INTOsuppliers(supplier_id,supplier_name)VALUES(3000,’Google’)

SELECT*FROMdual;

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector