In MySQL, The "INSERT INTO" statement is used to add single or multiple records or rows to the table.
We can insert data into the table in two ways.
Declare column names while Inserting.
By omitting the column names while Inserting.
INSERT INTO tableName (columnName1, columnName2, columnN) VALUES (value1, value2, valueN);
tableName: The name of the table to which we want to insert data.
columnName1, columnName2, columnN: The columns into which we want to insert data.
VALUES: The keyword used to specify the values to be inserted.
value1, value2, valueN: The values to be inserted into the corresponding columns.
In the below query, we are inserting a new row into the "users" table with values for the "firstName", and "lastName" columns.
INSERT INTO users (first_name, last_name) VALUES ('Alice', 'Collin');
In the below query, we are inserting a new row into the "users" table with values for the "userId", "firstName", and "lastName" columns.
INSERT INTO users (userId, firstName, lastName) VALUES (U1001, 'Alice', 'Collin');
In the below query, we are inserting multiple rows into the "products" table with values for the "product_name", "product_code", "category" and "product_price" columns.
INSERT INTO products (product_name, product_code, category, product_price) VALUES ('iPhone XR', 'I101', 'ELECTRONICS', 1200), ('onePlus 9x', 'O101', 'ELECTRONICS', 800), ('Samsung Flip', 'S101', 'ELECTRONICS', 600);
In the below query, we are inserting multiple rows into the "products" table with values for the "product_name", "product_code", "category" and "product_price" columns using the `SELECT` Command
INSERT INTO products (product_name, product_code, category, product_price) SELECT product_name, product_code, category, product_price FROM old_products;
We can use the INSERT INTO ... SELECT statement to insert data into a table based on the results of a SELECT query.
INSERT INTO products (product_name, product_code, category, product_price, created_at) SELECT product_name, product_code, category, product_price, created_at FROM old_products WHERE created_at < '2023-12-31' AND created_at > '2023-01-01';
In the above query, we are inserting rows into the "products" table based on the result set of the SELECT query where products created_at date less than '2023-12-31' and created_at date greater than '2023-01-01'.
In the below query, we are inserting a new row into the "users" table with values for the "userId", "firstName", and "lastName" columns but omitted from Query.
INSERT INTO users VALUES ("Alice", 'Collin', 'U101');