Sub topic 10
Reading and writing data with SQL
This chapter covers the four statements you use most often: INSERT, SELECT, UPDATE, and DELETE. It also covers filtering, sorting, grouping, and the mistakes that cause the most damage in practice. It assumes you know what tables, primary keys, and foreign keys are, and that you can read short code snippets. Joins have their own chapter, so every query here reads from a single table.
Statements that change data and statements that read it
SQL commands fall into a few groups. Data definition statements such as CREATE TABLE change the schema. Data manipulation statements change rows: INSERT, UPDATE, and DELETE. SELECT reads rows and changes nothing.
SQL is declarative. You describe the rows you want, and the database decides how to find them. The same SELECT can run as a full table scan or an index lookup without any change to your query.
Setting up sample data
The examples use the customers and orders tables from earlier chapters. This script is complete and runs on PostgreSQL, MySQL, and SQLite. It adds an optional phone column so you can see how NULL behaves.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
order_date DATE NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0)
);
ALTER TABLE customers ADD COLUMN phone VARCHAR(30);
INSERT INTO customers (customer_id, name, email) VALUES
(1, 'Ada Lovelace', '[email protected]'),
(2, 'Grace Hopper', '[email protected]'),
(3, 'Alan Turing', '[email protected]');
INSERT INTO orders (order_id, customer_id, order_date, total_amount) VALUES
(100, 1, '2026-01-15', 59.90),
(101, 1, '2026-02-03', 20.00),
(102, 2, '2026-02-10', 150.00),
(103, 2, '2026-03-01', 15.50);Writing rows with INSERT
INSERT names the target table, the columns you are filling, and the values in the same order. A multi-row VALUES list, as above, adds several rows in one statement and is faster than separate statements.
Always list the columns explicitly. If you write INSERT INTO customers VALUES (...), the values must match the table's current column order. That statement breaks silently or loudly when someone adds a column later.
A column you leave out receives its default value, or NULL if it has no default. That is why the rows above have phone set to NULL. A NOT NULL column with no default makes the insert fail instead.
The database checks every constraint at insert time. Each of these fails and inserts nothing:
- A duplicate
emailviolatesUNIQUE. - An order with
customer_id99 violates the foreign key, because no such customer exists. - A negative
total_amountviolates theCHECK.
Reading rows with SELECT
A basic query lists columns, a table, and a condition:
SELECT name, email
FROM customers
WHERE customer_id = 1;The WHERE clause keeps only rows for which the condition is true. Common operators are:
| Need | Operator | Example |
|---|---|---|
| Compare | `=`, `<>`, `<`, `<=`, `>`, `>=` | `total_amount >= 50` |
| Combine | `AND`, `OR`, `NOT` | `customer_id = 2 AND total_amount > 100` |
| Range | `BETWEEN a AND b` (inclusive) | `order_date BETWEEN '2026-02-01' AND '2026-02-28'` |
| Set membership | `IN (...)` | `customer_id IN (1, 3)` |
| Text pattern | `LIKE` with `%` and `_` | `email LIKE '%@example.com'` |
| Missing value | `IS NULL`, `IS NOT NULL` | `phone IS NULL` |
AND binds more tightly than OR. Write a OR b AND c and the database reads it as a OR (b AND c). Use parentheses whenever you mix them.
NULL needs its own test
NULL means "unknown", so any comparison with it yields neither true nor false but unknown, and WHERE discards unknown rows. This query returns nothing, even for customers with no phone:
SELECT name FROM customers WHERE phone = NULL;The correct form is:
SELECT name FROM customers WHERE phone IS NULL;The same rule applies to <>. phone <> '555-0100' does not return rows where phone is NULL.
Sorting and limiting
Without ORDER BY, the database may return rows in any order, and that order can change between runs. Add ORDER BY whenever order matters. DESC reverses the sort, and you can list several sort keys.
SELECT order_id, order_date, total_amount
FROM orders
ORDER BY total_amount DESC, order_id
LIMIT 2;This returns orders 102 (150.00) and 100 (59.90). LIMIT works in PostgreSQL, MySQL, and SQLite. The standard form is FETCH FIRST 2 ROWS ONLY, which PostgreSQL also accepts. SQL Server uses TOP. A limit without ORDER BY gives you an arbitrary subset.
Summarizing rows with aggregates and GROUP BY
Aggregate functions collapse many rows into one value: COUNT, SUM, AVG, MIN, and MAX. With no GROUP BY, they summarize the whole filtered table.
SELECT COUNT(*) AS order_count, SUM(total_amount) AS revenue
FROM orders;This returns 4 orders and 245.40 in revenue. COUNT(*) counts rows. COUNT(column) counts only rows where that column is not NULL. The other aggregates also skip NULL values.
GROUP BY makes one group per distinct value and computes the aggregates per group. HAVING filters groups after aggregation, the way WHERE filters rows before it.
SELECT customer_id,
COUNT(*) AS order_count,
SUM(total_amount) AS total_spent
FROM orders
WHERE order_date >= '2026-01-01'
GROUP BY customer_id
HAVING SUM(total_amount) > 100
ORDER BY total_spent DESC;The result is one row: customer 2, with 2 orders and 165.50 spent. Customer 1 totals 79.90 and is filtered out by HAVING.
Every selected column must either appear in GROUP BY or be wrapped in an aggregate. Selecting order_date in this query is an error in PostgreSQL and in MySQL's default mode, because each group contains several dates and the database cannot pick one.
The order SQL evaluates a query
You write SELECT first, but the database logically processes it last. This explains most "why can't I use that here" errors.
Two consequences follow:
WHEREruns beforeSELECT, so it cannot use a column alias defined inSELECT. Repeat the expression, or wrap the query in a subquery.ORDER BYruns afterSELECT, so it can use aliases. That is whyORDER BY total_spentworked above.
The database's physical plan may differ from this order for speed, but the results always match it.
Changing rows with UPDATE and DELETE
UPDATE sets new values on every row that matches its WHERE clause. DELETE removes every matching row.
UPDATE customers
SET phone = '555-0100'
WHERE customer_id = 1;
DELETE FROM orders
WHERE order_id = 103;Both statements report how many rows they affected. Check that count. If you expected one row and got 400, something is wrong.
An update can use the row's current values, as in SET total_amount = total_amount * 1.1. The right-hand side reads the old value, and the database computes it per row.
Constraints apply to changes as well as inserts. This statement fails because orders still reference customer 1:
DELETE FROM customers WHERE customer_id = 1;The foreign key refuses to leave orders pointing at a missing customer. You must delete or reassign the orders first, or define the key with ON DELETE CASCADE so the database does it for you. Cascading is convenient, but one delete can then remove many rows, so choose it deliberately.
Common errors
| Symptom | Likely cause |
|---|---|
| Query returns no rows for `= NULL` | Use `IS NULL` instead |
| `UPDATE` changed every row | Missing or wrong `WHERE` |
| "column must appear in GROUP BY" | Selected a non-aggregated column that is not grouped |
| Rows come back in a different order | No `ORDER BY` |
| Insert fails with a constraint error | Duplicate key, missing parent row, or a rule violated by the values |
| Unknown column in `WHERE` | Used a `SELECT` alias before it exists |
| Text value rejected or misread | Used double quotes; string literals take single quotes |
In SQL, single quotes mark string values ('Ada Lovelace') and double quotes mark identifiers such as column names.
Never build SQL by joining strings
When an application inserts user input into a query, pass the values as parameters through the database driver. Do not paste them into the SQL text. Pasting lets input like '; DELETE FROM orders; -- change the meaning of the statement, which is SQL injection. With parameters, the database treats the value strictly as data.
import sqlite3
conn = sqlite3.connect("shop.db")
email = "[email protected]"
row = conn.execute(
"SELECT name FROM customers WHERE email = ?", (email,)
).fetchone()
print(row)The ? placeholder is SQLite's syntax. PostgreSQL drivers typically use %s or $1, and the idea is the same.
Exercise
Using the sample data, write one query that returns each customerid that has placed more than one order, along with the date of their most recent order, newest first. Then explain why selecting orderdate without an aggregate would fail.
Show answer
SELECT customerid, MAX(orderdate) AS lastorder FROM orders GROUP BY customerid HAVING COUNT(*) > 1 ORDER BY lastorder DESC; The result is customer 2 (2026-03-01, or 2026-02-10 if order 103 was deleted, in which case customer 2 would have only one order and drop out) and customer 1 (2026-02-03). With all four orders present, customer 2 appears first. Selecting plain orderdate fails because each group holds several dates, and the database cannot choose one for the output row. MAX collapses the group to a single value, which is valid.
Exercise
A teammate runs UPDATE orders SET total_amount = 0; by mistake in a session with no open transaction and autocommit on. What went wrong, and which habit would have prevented it?
Show answer
The statement has no WHERE clause, so it set total_amount to 0 on every row, and autocommit made the change permanent immediately. Running the condition as a SELECT first, and wrapping the change in BEGIN ... COMMIT so it can be rolled back after checking the affected row count, would have prevented the loss.