Insert into command in SQL

The INSERT INTO statement in SQL is used to insert new rows of data into a table. There are several ways to use this statement depending on the amount and type of data you are inserting. Here are some examples and syntaxes: Basic Syntax The basic syntax for inserting data into a table is as follows:

SQL Syntax

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

Note: If we change the order of column names, then their corresponding values must also be in the order matching the column names.

Example: Consider a table employees with columns id, name, and department. Basic Insert:

SQL Syntax

INSERT INTO employees (id, name, department)
VALUES (1, 'John Doe', 'Sales');

Insert Another record:

SQL Syntax

INSERT INTO employees (id, name, department)
VALUES (5, ‘Ashish', 'Inventory');

Inserting Multiple Rows We can insert multiple rows in a single INSERT INTO statement by separating each row with a comma. Example:

SQL

INSERT INTO employees (id, name, department)
VALUES
(2, 'Jane Smith', 'Marketing'),
(3, 'Michael Johnson', 'IT'),
(4, 'Emily Davis', 'HR');

Inserting Data Without Specifying Column Names If we are inserting values into all columns of the table, we can omit the column names in the INSERT INTO statement. The values must be in the same order as the columns in the table.

SQL Syntax

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

Example:

SQL

INSERT INTO employees
VALUES (5, 'Laura Wilson', 'Finance');

Inserting Data from Another Table We can also insert data into a table by selecting data from another table.

SQL Syntax

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

Example:

SQL Syntax

INSERT INTO employees (id, name, department)
SELECT id, name, department
FROM temp_employees
WHERE status = 'active';