In SQL, the INSERT statement is used to insert new records into a newly created table. It allows you to add data to specific columns in a table or insert data based on a query’s results. Here’s an overview of how to use the INSERT statement to insert data into tables.
Table of Contents
ToggleBasic Syntax
The basic syntax of the INSERT statement is:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
- table_name: Specifies the name of the table where data will be inserted.
- column1, column2, …: Specifies the columns in the table where data will be inserted.
- value1, value2, …: Specifies the corresponding values to be inserted into listed columns.
Inserting Values into Specific Columns
To insert data into specific columns, you need to provide the column names in the INSERT statement.
For example, to insert a new records into the “employees” table, the query should specify the values for the “employee_name”, “salary”, and “department_id” columns.
INSERT INTO employees (employee_name, salary, department_id)
VALUES ('John Doe', 50000, 1);
Inserting Data from a Query
You can insert data into a table based on the results of a query. The query should select the columns and values to be inserted.
INSERT INTO employees (employee_name, salary, department_id)
SELECT name, salary, department_id
FROM new_employees;
This query inserts records into the “employees” table by selecting the “name”, “salary”, and “department_id” columns from the “new_employees” table.
Inserting Multiple Rows at Once
The INSERT statement can also insert multiple rows at once. To do this, you can specify multiple sets of values in the VALUES clause.
INSERT INTO employees (employee_name, salary, department_id)
VALUES ('John Doe', 50000, 1),
('Jane Smith', 60000, 2),
('Mike Johnson', 55000, 1);
The query inserts three records into the “employees” table with the specified values for the “employee_name”, “salary”, and “department_id” columns.
By using the INSERT statement, you can add new records to a table in your database. Whether you’re inserting values directly into columns or based on the results of a query, the INSERT statement allows you to efficiently insert data into tables and maintain your database’s integrity and consistency.