The INSERT statement is used to add one or more rows to a table in a SQL Server database.
It can be used to insert a single row, multiple rows, or the results of a query into a table.
The most common syntax for the INSERT statement is:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Or, if you are providing values for all columns in their defined order:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
You can insert the results of a SELECT query into another table:
INSERT INTO table_name (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM source_table
WHERE condition;
For inserting data from a JSON string:
INSERT INTO table_name (column1, column2)
SELECT JSON_VALUE(value, '$.property1'), JSON_VALUE(value, '$.property2')
FROM OPENJSON(@json_string);
SELECT statement that retrieves data from one or more tables to be inserted into the target table.Insert a new record into the Customers table.
INSERT INTO Customers (CustomerID, CompanyName, ContactName, Country)
VALUES (101, 'New Corp', 'Jane Doe', 'USA');
Insert several new records into the Products table.
INSERT INTO Products (ProductID, ProductName, Price)
VALUES
(78, 'Chai', 18.00),
(79, 'Chang', 19.00),
(80, 'Aniseed Syrup', 10.00);
Copy data from an old customer table to a new one.
INSERT INTO NewCustomers (CustomerID, CustomerName)
SELECT OldID, Name
FROM OldCustomers
WHERE City = 'London';
If you provide values for all columns in the correct order.
-- Assuming 'Orders' table has columns: OrderID, CustomerID, OrderDate
INSERT INTO Orders
VALUES (10001, 5, '2023-10-27');
INSERT operations are subject to table constraints such as PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and NOT NULL. Violations will result in an error.IDENTITY column, you do not typically provide a value for it; SQL Server automatically generates it. You can use SET IDENTITY_INSERT table_name ON; to manually insert values into an identity column, but this should be done with caution.NULL values into columns that allow them.INSERT statement, the default value will be used.