The INSERT INTO
statement in SQL is used to insert new records (rows) into a table. It allows you to specify the values to be inserted into specific columns or to insert data from a SELECT
query.
Here's the basic syntax of the INSERT INTO
statement:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
table_name
: The name of the table into which you want to insert data.(column1, column2, ...)
: Optional list of columns in the table. If provided, you need to specify values for each listed column. If omitted, values for all columns must be provided in the same order as they are defined in the table.VALUES (value1, value2, ...)
: The values to be inserted into the corresponding columns. The number of values provided must match the number of columns specified or the number of columns in the table if no columns are specified.Example:
Let's say we have a table named employees
with columns employee_id
, first_name
, last_name
, and salary
, and we want to insert a new employee record:
INSERT INTO employees (employee_id, first_name, last_name, salary)
VALUES (101, 'John', 'Doe', 50000);
This will insert a new record into the employees
table with the specified values for employee_id
, first_name
, last_name
, and salary
.
If you want to insert data into all columns of the table without specifying column names, you can omit the column list:
INSERT INTO employees
VALUES (102, 'Jane', 'Smith', 60000);
This assumes that the values provided are in the same order as the columns are defined in the table.
You can also use a SELECT
query to insert data into a table from another table or query result:
INSERT INTO employees (employee_id, first_name, last_name, salary)
SELECT employee_id, first_name, last_name, salary
FROM temporary_employees;
This will insert records into the employees
table by selecting data from the temporary_employees
table.
Remember to ensure that the data types of the values being inserted match the data types of the columns in the table.