Changing Data Lesson 17 of 21
SQL INSERT INTO — Adding Data
Add new rows to a table with INSERT INTO ... VALUES, insert several rows at once, let the database fill in ids and defaults, and copy rows with INSERT ... SELECT.
Up to now, you've only read data. Real apps also add data: a new customer signs up, a new product arrives, a sale is recorded. Adding rows is done with INSERT INTO.
Syntax
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Adding one row
INSERT INTO products (name, category, price, stock)
VALUES ('Vinegar', 'Cooking', 16, 25);
SELECT * FROM products;
The new product is at the bottom with id 16. We didn't give an id, so the database assigned the next number automatically. That's because id is an INTEGER PRIMARY KEY (in MySQL you'd mark it AUTO_INCREMENT).
The columns and values must line up
The first value goes into the first column listed, the second into the second, and so on. The number of values must match the number of columns:
INSERT INTO customers (name, barangay)
VALUES ('Rosa Lim');
Leaving out columns
Columns you don't list get NULL (or their default value, if one was set):
INSERT INTO customers (name, barangay)
VALUES ('Rosa Lim', 'Mabini');
SELECT * FROM customers WHERE name = 'Rosa Lim';
Adding several rows at once
INSERT INTO students (first_name, last_name, grade, section, birthday)
VALUES
('Diego', 'Silang', 8, 'Luna', '2013-12-16'),
('Josefa', 'Llanes', 8, 'Luna', '2013-09-11'),
('Marcelo', 'del Pilar', 7, 'Silang', '2014-08-30');
SELECT * FROM students WHERE grade <= 8 ORDER BY grade, last_name;
One INSERT with many rows is much faster than many separate INSERTs.
Recording a sale
A new order involves two tables: the order itself, and its items. We need the new order's id for the items:
INSERT INTO orders (customer_id, order_date, status)
VALUES (2, '2026-11-28', 'paid');
INSERT INTO order_items (order_id, product_id, qty)
VALUES (last_insert_rowid(), 2, 2),
(last_insert_rowid(), 3, 1);
SELECT o.id, o.order_date, p.name, oi.qty
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE o.id = 11;
last_insert_rowid() gives the id that was just created. In MySQL, it's called LAST_INSERT_ID().
Text with an apostrophe
Since text uses single quotes, write an apostrophe as two single quotes:
INSERT INTO products (name, category, price, stock)
VALUES ('Lola''s Polvoron', 'Snacks', 30, 15);
SELECT name FROM products WHERE category = 'Snacks';
INSERT ... SELECT
You can insert rows that come from a query. For example, copy all Rizal-section students into a new table for a field trip list:
CREATE TABLE field_trip (name TEXT, section TEXT);
INSERT INTO field_trip (name, section)
SELECT first_name || ' ' || last_name, section
FROM students
WHERE section = 'Rizal';
SELECT * FROM field_trip;
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04