SQL Server Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

SQL INSERT Query

Back to: SQL Server Tutorial

In Microsoft SQL Server (MS SQL), the INSERT statement is used to add new rows to a table. Here’s a detailed explanation of how to use the INSERT statement in MS SQL:

Basic Syntax

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

Example

Assume you have a table named employees with columns id, name, and position. To insert a new employee into this table, use the following query:

INSERT INTO employees (id, name, position) VALUES (1, 'John Doe', 'Software Engineer');

Inserting Multiple Rows

You can insert multiple rows in a single INSERT statement by separating each set of values with a comma:

INSERT INTO employees (id, name, position) VALUES (2, 'Jane Smith', 'Project Manager'), (3, 'Emily Johnson', 'Analyst');

Inserting Default Values

If a column has a default value specified and you want to use that default, you can omit the column from the INSERT statement:

INSERT INTO employees (name, position) VALUES ('Alice Brown', 'Designer');

Alternatively, you can use the DEFAULT keyword if you want to explicitly state that a column should use its default value:

INSERT INTO employees (id, name, position) VALUES (DEFAULT, 'Alice Brown', 'Designer');

Inserting Data from Another Table

You can insert data into a table from another table using a SELECT statement. For example, if you have an old_employees table and want to insert rows into new_employees where the start_date is after a certain date, you could use:

INSERT INTO new_employees (name, position) SELECT name, position FROM old_employees WHERE start_date > '2023-01-01';

Inserting Data with Identity Columns

If your table has an IDENTITY column (an auto-incrementing column), you don’t need to insert a value into this column; SQL Server will automatically generate it. For example:

CREATE TABLE employees ( id INT IDENTITY PRIMARY KEY, name NVARCHAR(100), position NVARCHAR(100) );

Inserting data without specifying the id column:

INSERT INTO employees (name, position) VALUES ('Michael Scott', 'Regional Manager');

Using OUTPUT Clause

SQL Server allows you to use the OUTPUT clause to return information about the rows affected by the INSERT statement. For example:

INSERT INTO employees (name, position) OUTPUT inserted.id, inserted.name VALUES ('Pam Beesly', 'Sales Representative');

This will return the id and name of the newly inserted row.

Handling Errors

To handle potential errors during an INSERT, you might use TRY...CATCH blocks:

BEGIN
TRY INSERT INTO employees (name, position) VALUES ('Jim Halpert', 'Sales Representative');
END TRY
BEGIN CATCH
-- Handle the error
SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH

This allows you to capture and handle errors that might occur during the insert operation.

Scroll to Top