Everything so far only read data. Four statements change it. INSERT adds rows, UPDATE changes them, DELETE removes them, and SELECT shows the result. In the practice every run starts from a fresh copy of the database, so you can't break anything; at work, these are the statements to slow down for.
INSERT INTO products (id, name, category, price)
VALUES (9, 'Duck whistle', 'Outdoors', 6.50);
SELECT id, name, price FROM products WHERE category = 'Outdoors';
Returns
id | name | price
---+--------------+------
8 | Binoculars | 120
9 | Duck whistle | 6.5
(2 rows)
Name the columns in an INSERT; then it still works if someone adds a column later. UPDATE sets new values on every row the WHERE matches:
UPDATE products SET price = ROUND(price * 1.10, 2) WHERE category = 'Books';
SELECT name, price FROM products WHERE category = 'Books';
Returns
name | price
------------+------
Field guide | 19.8
Sketchbook | 10.73
(2 rows)
An UPDATE or DELETE without a WHERE changes every row. Before running one, write it as a SELECT with the same WHERE and check the rows it finds. Then change SELECT to UPDATE or DELETE.
A transaction groups statements so they all happen or none do. BEGIN starts one, COMMIT keeps the changes, and ROLLBACK throws them all away, as if they'd never run. Moving money between accounts is the classic case: you never want the take-away to happen without the add.
BEGIN;
DELETE FROM order_items;
ROLLBACK;
SELECT COUNT(*) AS after_rollback FROM order_items;
Returns
after_rollback
--------------
14
(1 row)
Loading data often needs "insert this, or update it if it's already there", called an upsert. SQLite and PostgreSQL write INSERT … ON CONFLICT (key) DO UPDATE SET …, where excluded means the row you tried to insert. MySQL has ON DUPLICATE KEY UPDATE; SQL Server, Oracle and the warehouses use MERGE.
INSERT INTO products (id, name, category, price)
VALUES (5, 'Pond net', 'Garden', 14.00), (10, 'Lily pad float', 'Garden', 22.00)
ON CONFLICT (id) DO UPDATE SET price = excluded.price;
SELECT id, name, price FROM products WHERE category = 'Garden' ORDER BY id;
Returns
id | name | price
---+----------------+------
1 | Duck feeder | 24
2 | Bird bath | 45.5
5 | Pond net | 14
10 | Lily pad float | 22
(4 rows)
Product 5 already existed, so its price was updated; 10 was new, so it was inserted. RETURNING (SQLite, PostgreSQL) makes an INSERT, UPDATE or DELETE hand back the rows it changed.
Practice
Add a customer: id 9, name Ivo, city Austin, joined 2024-10-20. Then select the name of every customer in Austin.