The INSERT INTO statement in MySQL is used to insert new rows into a table. The basic syntax of the INSERT INTO statement is as follows:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
Here, table_name
is the name of the table where we want to insert the new rows. column1
, column2
, column3
, etc. are the names of the columns in the table where we want to insert data. value1
, value2
, value3
, etc. are the actual values that we want to insert into the columns.
For example, let’s say we have a table named employees
with columns id
, name
, age
, and salary
. To insert a new row into the table with the following values:
- id = 1
- name = “John Doe”
- age = 30
- salary = 50000
We can use the following SQL query:
INSERT INTO employees (id, name, age, salary) VALUES (1, 'John Doe', 30, 50000);
If we want to insert multiple rows into the table in a single query, we can use a comma-separated list of values in the VALUES clause. For example, to insert two new rows into the table with the following values:
- id = 2, name = “Jane Smith”, age = 25, salary = 45000
- id = 3, name = “Bob Johnson”, age = 40, salary = 60000
We can use the following SQL query:
INSERT INTO employees (id, name, age, salary) VALUES (2, 'Jane Smith', 25, 45000), (3, 'Bob Johnson', 40, 60000);
Note that the values must be in the same order as the columns in the INSERT INTO statement. If we omit a column in the column list, we must specify a default value or NULL for that column, or MySQL will generate an error. If we omit the column list entirely, we must provide a value for every column in the table, in the order they appear in the table.