MSDN Documentation

INSERT Statements

The INSERT statement is used to add new rows of data to a table in a database. It's a fundamental operation for populating your tables and keeping your data up-to-date.

Syntax

There are two primary syntaxes for the INSERT statement:

1. Inserting a Single Row with Specific Values

This syntax allows you to specify the values for each column in the new row.

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

Example:

INSERT INTO Employees (EmployeeID, FirstName, LastName, Department)
VALUES (101, 'Alice', 'Smith', 'Engineering');

2. Inserting a Single Row Using Values from Another Table (Subquery)

This syntax is useful when you want to copy data from one table to another or insert data based on the results of a query.

INSERT INTO table_name (column1, column2, column3, ...)
SELECT columnA, columnB, columnC, ...
FROM another_table
WHERE condition;

Example:

INSERT INTO HighSalaryEmployees (EmployeeID, FullName)
SELECT EmployeeID, FirstName + ' ' + LastName
FROM Employees
WHERE Salary > 80000;

Inserting Multiple Rows

Most SQL dialects allow inserting multiple rows in a single statement by providing comma-separated value lists.

INSERT INTO Products (ProductID, ProductName, Price)
VALUES
    (1, 'Laptop', 1200.00),
    (2, 'Keyboard', 75.50),
    (3, 'Mouse', 25.99);
Note: The exact syntax for inserting multiple rows can vary slightly between different database systems (e.g., MySQL, PostgreSQL, SQL Server).

Important Considerations

Example with Default Value and Identity Column:

-- Assuming OrderID is an IDENTITY column and OrderDate has a DEFAULT value of GETDATE()
INSERT INTO Orders (CustomerID, ProductID)
VALUES (50, 12);
Tip: When inserting a large number of rows, consider using bulk insert utilities provided by your database system for better performance.