Part 11 / Topic 1 of 7
INSERT: one, many, and from a query
The forms you know, then the one that scales. Single and multi-row, always with the column list:
INSERT INTO suppliers (name, country) VALUES ('Chai Traders', 'India');
INSERT INTO categories (name, parent_id) VALUES
('Audio', 1),
('Cables', 1);
INSERT 0 1
INSERT 0 2
(Why always the column list? INSERT INTO t VALUES (...) matches the table's column order — until someone adds a column and your values land in the wrong places, silently.)
The scaling form is INSERT ... SELECT — the rows come from a query, not a keyboard. Archive every cancelled order into an audit table:
CREATE TABLE cancelled_orders_archive (
order_id integer PRIMARY KEY,
customer_id integer NOT NULL,
order_date date NOT NULL,
archived_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO cancelled_orders_archive (order_id, customer_id, order_date)
SELECT order_id, customer_id, order_date
FROM orders
WHERE status = 'cancelled';
CREATE TABLE
INSERT 0 1
Everything a SELECT can do — joins, CTEs, window functions — can feed an INSERT. Copying between tables, seeding test data, materialising a report: all this one shape.
🧪 Quick quiz — answer from memory, then check.
- Why write the column list even though it's optional?
- What can the SELECT in
INSERT ... SELECTcontain?
Show the answers
- Without it, values bind by table column order — which breaks silently when the table changes shape.
- Anything a standalone SELECT can — joins, CTEs, windows, aggregation.
Exercise 1: The spend summary
What to do: Create customer_spend (customer_id PRIMARY KEY, orders, spend) and fill it with one INSERT ... SELECT: delivered order count and total per customer.
Sample output:
customer_id | orders | spend
-------------+--------+---------
1 | 2 | 1405.00
3 | 1 | 1310.00
2 | 2 | 949.00
5 | 1 | 399.00
(4 rows)
💡 Hint: the SELECT is Part 5's join + Part 4's aggregates; the INSERT just catches the rows.
Show the solution to Exercise 1
-- Exercise 1: The spend summary (INSERT ... SELECT with a join)
DROP TABLE IF EXISTS customer_spend;
CREATE TABLE customer_spend (
customer_id integer PRIMARY KEY,
orders integer NOT NULL,
spend numeric(12,2) NOT NULL
);
INSERT INTO customer_spend (customer_id, orders, spend)
SELECT o.customer_id, count(DISTINCT o.order_id),
sum(oi.quantity * oi.unit_price)
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY o.customer_id;
SELECT * FROM customer_spend ORDER BY spend DESC;