TExcelTAD
Home › MySQL › MySQL INSERT INTO

MySQL INSERT INTO

INSERT INTO adds new rows to a table. The clear, recommended form names the columns you are filling, then gives the values in the same order:

sql
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
mysql · try it yourself
INSERT INTO categories (name, description)
VALUES ('Frozen', 'Ice cream and frozen vegetables');

SELECT * FROM categories WHERE category_id >= 5;
+-------------+-----------+---------------------------------+
| category_id | name      | description                     |
+-------------+-----------+---------------------------------+
|           5 | Snacks    | Chips, nuts and chocolate       |
|           6 | Household | NULL                            |
|           7 | Frozen    | Ice cream and frozen vegetables |
+-------------+-----------+---------------------------------+

We didn't give a category_id: the column is AUTO_INCREMENT, so MySQL picked the next number (7) itself. Columns you leave out get their default value (NULL, unless the table defines another default).

Several rows at once

One statement can insert many rows. This is much faster than many single-row statements, because the server parses and commits once:

mysql · try it yourself
INSERT INTO suppliers (name, city, country)
VALUES ('Nordic Fish AB', 'Gothenburg', 'Sweden'),
       ('Masala House',   'Mumbai',     'India'),
       ('Maple Sweets',   'Montreal',   'Canada');

SELECT supplier_id, name, contact_name, country
FROM suppliers
WHERE supplier_id > 5;
+-------------+--------------------+--------------+-------------+
| supplier_id | name               | contact_name | country     |
+-------------+--------------------+--------------+-------------+
|           6 | CleanHome Supplies | NULL         | Netherlands |
|           7 | Nordic Fish AB     | NULL         | Sweden      |
|           8 | Masala House       | NULL         | India       |
|           9 | Maple Sweets       | NULL         | Canada      |
+-------------+--------------------+--------------+-------------+

Getting the new id

After inserting into a table with an AUTO_INCREMENT key, LAST_INSERT_ID() returns the id that was generated in your session. Use it to insert related rows, for example an order and then its lines:

mysql · try it yourself
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (13, 5, '2025-06-04', 'processing');

SET @new_order = LAST_INSERT_ID();

INSERT INTO order_details (order_id, product_id, quantity, unit_price)
VALUES (@new_order, 9, 2, 1.45),
       (@new_order, 6, 3, 1.60);

SELECT @new_order AS order_id;
SELECT * FROM order_details WHERE order_id = @new_order;
+----------+
| order_id |
+----------+
|       23 |
+----------+
+----------+------------+----------+------------+----------+
| order_id | product_id | quantity | unit_price | discount |
+----------+------------+----------+------------+----------+
|       23 |          6 |        3 |       1.60 |     0.00 |
|       23 |          9 |        2 |       1.45 |     0.00 |
+----------+------------+----------+------------+----------+

@new_order is a user variable: it lives for the rest of the session. discount was omitted and took its default, 0.00.

Note: With a multi-row INSERT, LAST_INSERT_ID() returns the id of the first row inserted, not the last.

Without a column list

You can omit the column list and give a value for every column, in table order. It is shorter but fragile: if the table gets a new column, the statement breaks or, worse, puts values into the wrong columns.

sql
INSERT INTO categories VALUES (NULL, 'Pet Food', 'Food for cats and dogs');

Here NULL for the AUTO_INCREMENT column also means "generate the next id".

When an insert fails

The server checks every row against the table's rules. A missing required value, a value of the wrong type or a reference to a row that doesn't exist makes the whole statement fail:

mysql · try it yourself
INSERT INTO products (name, category_id, supplier_id, unit_price)
VALUES ('Mystery Item', 99, 1, 5.00);
ERROR 1452 (23000) at line 1: Cannot add or update a child row: a foreign key constraint fails (`shop`.`products`, CONSTRAINT `products_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`category_id`))

There is no category 99, so the foreign key rejects the row. Without that rule the database would happily store a product in a category that doesn't exist.

INSERT IGNORE and upserts

Two MySQL extensions deal with rows that would break a unique key:

  • INSERT IGNORE skips such rows instead of failing.
  • INSERT ... ON DUPLICATE KEY UPDATE updates the existing row instead (an "upsert").
mysql · try it yourself
INSERT IGNORE INTO categories (category_id, name) VALUES (1, 'Drinks'), (7, 'Frozen');
SELECT category_id, name FROM categories WHERE category_id IN (1, 7);

INSERT INTO categories (category_id, name, description)
VALUES (2, 'Bakery', 'Fresh bread every morning')
ON DUPLICATE KEY UPDATE description = VALUES(description);
SELECT * FROM categories WHERE category_id = 2;
+-------------+-----------+
| category_id | name      |
+-------------+-----------+
|           1 | Beverages |
|           7 | Frozen    |
+-------------+-----------+
+-------------+--------+---------------------------+
| category_id | name   | description               |
+-------------+--------+---------------------------+
|           2 | Bakery | Fresh bread every morning |
+-------------+--------+---------------------------+

Category 1 already existed, so (1, 'Drinks') was silently skipped and Beverages kept its name; 7 was new and was inserted. The upsert then found category 2 and updated its description.

Note: MySQL 8.0.20+ prefers a row alias instead of VALUES(col): INSERT ... VALUES (...) AS new ON DUPLICATE KEY UPDATE description = new.description. MariaDB doesn't support the alias form, while both still accept VALUES(col), which is why this course uses it.

Test yourself

What happens to a column you leave out of an INSERT column list?

  1. The insert fails
  2. It gets its default value (often NULL)
  3. It copies the previous row's value
  4. It is set to 0

Which function returns the AUTO_INCREMENT id generated by your last INSERT?

  1. MAX(id)
  2. LAST_INSERT_ID()
  3. NEXT_ID()
  4. @@identity

What does INSERT ... ON DUPLICATE KEY UPDATE do when the key already exists?

  1. Fails with an error
  2. Inserts a second copy
  3. Updates the existing row
  4. Deletes the old row