Insert into statement in SQL Server
The INSERT INTO statement in SQL Server is used to insert new records into a table. It allows you to specify the table name and the values to be inserted into the corresponding columns.
The basic syntax for the INSERT INTO statement is as follows:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Let's say we have a table called "Employees" with columns "EmployeeID," "FirstName," and "LastName." Here's an example of how to use the INSERT INTO statement to insert a new employee into the table:
INSERT INTO Employees (EmployeeID, FirstName, LastName)
VALUES (1, 'John', 'Doe');
In this example, we are inserting a new employee with an EmployeeID of 1, FirstName of 'John,' and LastName of 'Doe' into the "Employees" table.
If you want to insert multiple records in a single INSERT INTO statement, you can separate each set of values with commas:
INSERT INTO Employees (EmployeeID, FirstName, LastName)
VALUES (2, 'Jane', 'Smith'),
(3, 'Michael', 'Johnson'),
(4, 'Emily', 'Davis');
In this case, we are inserting three new employees into the "Employees" table in a single statement.
You can also insert data into a subset of columns by explicitly specifying the column names:
INSERT INTO Employees (FirstName, LastName)
VALUES ('Sarah', 'Williams');
Here, we are inserting a new employee with a FirstName of 'Sarah' and LastName of 'Williams,' while omitting the EmployeeID column. If the omitted columns allow NULL values or have default values defined, the statement will execute successfully.
It's important to ensure that the values being inserted match the data types and constraints defined for the respective columns in the table. Otherwise, the INSERT INTO statement may result in errors or unexpected behavior.
The INSERT INTO statement is a fundamental SQL operation that allows you to add new records to a table, providing the foundation for data insertion in SQL Server.