MySQL - Insert Query - Add New Record

An INSERT query is used in SQL (Structured Query Language) to add new data to a table. The INSERT statement specifies the name of the table, the columns where data will be added, and the values that will be added to the table.

Inserting a single row into a table

INSERT INTO users (name, email, age) VALUES ('John Smith', '[email protected]', 30);

In this example, we are inserting a single row into the "users" table. The values 'John Smith', '[email protected]', and 30 are being inserted into the "name", "email", and "age" columns, respectively.

Inserting multiple rows into a table

INSERT INTO users (name, email, age) VALUES ('Jane Doe', '[email protected]', 25), ('Bob Johnson', '[email protected]', 40), ('Alice Lee', '[email protected]', 35);

In this example, we are inserting multiple rows into the "users" table. We are specifying the columns we want to insert data into, and then using the VALUES keyword to specify the values for each row. Note that we are using parentheses to group the values for each row.

Inserting data into a table using a subquery

INSERT INTO sales (product_id, sales_date, quantity) SELECT id, '2022-02-01', 10 FROM products WHERE category = 'Electronics';

In this example, we are inserting data into the "sales" table using a subquery. We are selecting the "id" column from the "products" table, and then specifying a constant value for the "sales_date" column and the "quantity" column. We are only inserting data for products in the "Electronics" category.