SQL from Scratch: SELECT, JOIN, GROUP BY, and Window Functions on One Small Bookshop Dataset
SQL is the language for talking to a relational database. This guide works through SELECT, WHERE, GROUP BY, JOIN, LEFT JOIN, subqueries, window functions, the NULL trap, parameter binding against injection, and transaction rollback on a fictional bookshop's two tables, ending with a daily revenue report. Standard-library sqlite3 only, Python 3.12.3.

Within days of launching, a vibe project hits the same problem: the data lives in a database, but answering "which category sells best" or "which book never sold once" needs SQL, and nobody knows how to write it. SQL (Structured Query Language) is the language for talking to a relational database: you describe the data you want, and the database finds it. This guide teaches SQL from scratch on a fictional small bookshop (titles, prices, and orders are all demo data): selecting, filtering, sorting, grouping, joining tables, ranking, and transactions, all practised on one dataset. Everything is measured with Python's standard-library sqlite3 in an in-memory database on Python 3.12.3 — nothing written to disk, no external database service; every SQL statement and every line of output is a real measured result. SQLite syntax is broadly the same as PostgreSQL and MySQL, so learning this set means switching databases later is mostly a matter of checking dialect differences, not relearning the language.
First, the two tables. books holds books: id, title, category, price, stock. orders holds orders: order id, which book was bought, how many copies, and the order date. The tables link through book_id matching books.id — "one table per kind of thing, joined when needed" is the basic idea of a relational database:
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
category TEXT NOT NULL,
price REAL NOT NULL,
stock INTEGER NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
book_id INTEGER NOT NULL,
qty INTEGER NOT NULL,
ordered_on TEXT NOT NULL
);
The demo data is 7 books and 6 orders: "Python Basics" at 59 with 12 in stock, "Algorithms Illustrated" at 79 with 5, "Computer Systems Deep Dive" at 139 with 3, "Dream of the Red Chamber" at 89 with 0 in stock, "Three-Body" at 69 with 20, "A Brief History of Time" at 49 with 8, and "One Hundred Years of Solitude" at 59 with 4. The orders run from 20 to 23 November, six of them. Every query result below can be checked by hand against this little table — the best habit when learning SQL is to work out the answer in your head first, then see whether the database gives the same number.
The column types are worth a look, too: INTEGER for whole numbers, REAL for prices with decimals, TEXT for titles, categories, and dates. id INTEGER PRIMARY KEY is the primary key — the unique number that identifies a row, and the number book_id in the orders table points at. A primary key is never duplicated and never empty, so if an order is written with a book id that does not exist, the join finds no match and the order silently drops out of an inner-join result — when data looks wrong, checking whether the foreign keys line up is often faster than re-reading the SQL. Money should not really be stored as REAL in a production project, because binary floating point has precision issues (a computation like 59.0 × 3 can grow a tiny tail); the demo uses REAL only because the amounts are whole yuan and the dataset is small. In production, store money as an integer number of cents or fen in a fixed-point type.
Reading data: SELECT, WHERE, ORDER BY, LIMIT
The basic SQL sentence is SELECT what you want FROM which table WHERE filter out rows ORDER BY sort by what LIMIT how many. The three most expensive books:
SELECT title, price FROM books ORDER BY price DESC LIMIT 3;
Output:
('Computer Systems Deep Dive', 139.0)
('Dream of the Red Chamber', 89.0)
('Algorithms Illustrated', 79.0)
A few details are worth pausing on: SELECT title, price means "just these two columns" — SELECT * takes everything, which is fine for demos but in project code it is better to name the columns, so adding a column to the table later does not drag extra data back. ORDER BY price DESC sorts from high to low; without DESC the default is low to high. LIMIT 3 takes only the first three rows, and paging is LIMIT 10 OFFSET 20 (skip 20, take 10). WHERE filters rows — WHERE stock > 0 keeps only books in stock, WHERE category = 'Programming' keeps only programming books — and conditions combine: WHERE category = 'Programming' AND price < 100 means "programming books under 100".
One mistake beginners make often: assuming that without ORDER BY, rows come back in insertion order. They do not. The database guarantees no default order — the order you get today may change tomorrow. If you want a definite order, write ORDER BY explicitly. Paged queries especially need this, or the same row can show up once on each of two pages.
Grouping: GROUP BY and aggregate functions
To answer "how many books are in each category, and what is the average price", looking row by row is not enough — group the rows by category and compute a number per group:
SELECT category, COUNT(*) AS n, ROUND(AVG(price), 1) AS avg_price
FROM books GROUP BY category ORDER BY category;
Output:
('Literature', 2, 74.0)
('Popular Science', 1, 49.0)
('Programming', 3, 92.3)
('Sci-Fi', 1, 69.0)
COUNT(*) counts rows, AVG(price) averages the price, and SUM, MAX, and MIN work the same way — these are aggregate functions, which squash many rows into one number. GROUP BY category means "split the rows into piles by category and compute one set of numbers per pile". AS n gives the result column a name — optional, but it reads better and is easier to refer to in code. ROUND(..., 1) keeps one decimal place: the programming average of 92.3 is (59 + 79 + 139) ÷ 3 = 92.333…, rounded — check it by hand and it lines up.
To filter groups after grouping, use HAVING, not WHERE. The split of labour is: WHERE filters rows before grouping, HAVING filters groups after grouping. "Only books with 2 or more orders" means grouping orders by book first, then dropping the groups under 2:
SELECT books.title, COUNT(*) AS n, SUM(orders.qty) AS total_qty
FROM orders JOIN books ON orders.book_id = books.id
GROUP BY books.title HAVING COUNT(*) >= 2;
Output:
('Python Basics', 2, 3)
('Three-Body', 2, 5)
"Python Basics" sold in 2 orders totalling 3 copies, "Three-Body" in 2 orders totalling 5 copies; "Algorithms Illustrated" and "Computer Systems Deep Dive", with one order each, were filtered out by HAVING. Writing HAVING COUNT(*) >= 2 as WHERE COUNT(*) >= 2 errors out directly — when WHERE runs, grouping has not happened yet, so COUNT(*) does not exist yet.
Joining tables: JOIN stitches two tables together
The orders table holds only book_id — no title, no unit price. To answer "which book did each order sell, and for how much", join the two tables. JOIN … ON means "pair up rows from the two tables by this condition":
SELECT orders.id, books.title, orders.qty, books.price * orders.qty AS amount
FROM orders JOIN books ON orders.book_id = books.id ORDER BY orders.id;
Output:
(101, 'Python Basics', 2, 118.0)
(102, 'Python Basics', 1, 59.0)
(103, 'Algorithms Illustrated', 3, 237.0)
(104, 'Three-Body', 4, 276.0)
(105, 'Three-Body', 1, 69.0)
(106, 'Computer Systems Deep Dive', 1, 139.0)
All six orders matched a book, and the amount is unit price times quantity: order 101, two copies of "Python Basics", is 118; order 104, four copies of "Three-Body", is 276. Note that arithmetic between columns, like books.price * orders.qty, can go straight into the SELECT — let the database compute it instead of pulling the whole table back into the program. It is much faster and moves far less data.
An inner join (JOIN, i.e. INNER JOIN) keeps only rows that match on both sides. Books with no orders and orders with no book never appear in the result. That is exactly how it differs from LEFT JOIN below, and the easiest thing for beginners to mix up: use an inner join when you wanted a full list, and the rows with missing data quietly disappear — without any error.
LEFT JOIN: books that never sold still show up
For a list of "how many orders each book sold", including books that never sold once, an inner join fails: "Dream of the Red Chamber", "A Brief History of Time", and "One Hundred Years of Solitude" have no orders, and an inner join drops them. Use a left join:
SELECT books.title, COUNT(orders.id) AS sold_orders
FROM books LEFT JOIN orders ON orders.book_id = books.id
GROUP BY books.id ORDER BY books.id;
Output:
('Python Basics', 2)
('Algorithms Illustrated', 1)
('Computer Systems Deep Dive', 1)
('Dream of the Red Chamber', 0)
('Three-Body', 2)
('A Brief History of Time', 0)
('One Hundred Years of Solitude', 0)
LEFT JOIN means "keep every row of the left table (books); match rows from the right table (orders) where possible, and fill NULL where there is no match". All seven books are there, and the three that never sold show 0 orders. One detail: the count uses COUNT(orders.id), not COUNT(*) — for unmatched rows orders.id is NULL, and COUNT(column) skips NULLs, so the answer is 0; COUNT(*) would count the unmatched row itself and give 1, which is wrong. The NULL trap gets its own section below.
The same idea works in reverse: WHERE orders.id IS NULL selects exactly the "books that never sold". This is a very common SQL move: left join plus a NULL check means "find rows with no matching record". Admin lists like "unprocessed orders" or "unlinked accounts" are almost always built this way.
Subqueries: compute a small result, then use it as a condition
Sometimes a query's condition is itself the result of another query — nest one query inside another, and it is called a subquery. "Only books that sold":
SELECT title FROM books WHERE id IN (SELECT book_id FROM orders) ORDER BY id;
Output:
('Python Basics',)
('Algorithms Illustrated',)
('Computer Systems Deep Dive',)
('Three-Body',)
The subquery in brackets first computes "the ids of books with orders" — 1, 2, 3, 5 — and the outer query then uses IN to keep those four books. Subqueries and JOINs can often be rewritten into each other: this example could also be written with a JOIN plus DISTINCT. As a rule of thumb, when the condition is "is it in this set", a subquery reads more directly; when you need columns from both tables at once, use a JOIN. Performance is usually about the same — look at the execution plan when optimisation is actually needed, not before.

Window functions: ranking without writing the query twice
To answer "each book's sales, and its rank inside its own category", without window functions you would write two queries and stitch them together; with a window function, one SQL statement is enough:
SELECT books.category, books.title,
SUM(books.price * orders.qty) AS sales,
RANK() OVER (PARTITION BY books.category ORDER BY SUM(books.price * orders.qty) DESC) AS rank_in_cat
FROM orders JOIN books ON orders.book_id = books.id
GROUP BY books.category, books.title ORDER BY books.category, rank_in_cat;
Output:
('Programming', 'Algorithms Illustrated', 237.0, 1)
('Programming', 'Python Basics', 177.0, 2)
('Programming', 'Computer Systems Deep Dive', 139.0, 3)
('Sci-Fi', 'Three-Body', 345.0, 1)
RANK() OVER (PARTITION BY ... ORDER BY ...) means: first cut the rows into windows by category (PARTITION BY books.category), then rank inside each window by sales. Sci-Fi has only "Three-Body", ranked 1; in Programming, "Algorithms Illustrated" at 237 is 1st, "Python Basics" at 177 is 2nd, "Computer Systems Deep Dive" at 139 is 3rd. Sales themselves come from SUM(unit price × quantity): "Three-Body" sold 5 copies for 345, "Algorithms Illustrated" 3 copies for 237 — and those numbers match the order details above (276 + 69 = 345, and 237).
The biggest difference from GROUP BY is that grouping squashes many rows into one, while a window function does not squash anything — every row stays, with one extra computed column beside it. For "top 3 per category", "sales as a percentage of the category total", or "the difference from the previous row", window functions are almost the only comfortable way to write it. RANK skips numbers on ties (two 1st places are followed by 3rd); for no skipping use DENSE_RANK, and for plain row numbers use ROW_NUMBER — the three differ only on ties, so remembering RANK first is enough.
The NULL trap: unknown is not the same as nothing
NULL in SQL means "unknown, not filled in yet" — it is not 0, and it is not an empty string. The three easiest traps: first, comparing NULL with anything gives "unknown", including comparing it with itself — NULL = NULL is not true, it is NULL, so WHERE stock = NULL never matches a row; write WHERE stock IS NULL instead. Second, aggregate functions skip NULLs:
SELECT COUNT(*) AS all_rows, COUNT(stock) AS stock_rows FROM
(SELECT 12 AS stock UNION ALL SELECT NULL UNION ALL SELECT 5);
Output:
(3, 2)
Of three rows, one has a NULL stock: COUNT(*) counts 3 rows, COUNT(stock) counts only 2 non-empty values — which is exactly why the left join above counts orders with COUNT(orders.id). Third, NULL in arithmetic turns the whole result NULL: if the unit price is NULL, unit price × quantity is NULL too, and the row quietly vanishes from a total; convert NULL to 0 first with COALESCE(unit price, 0). Marking columns that must never be empty with NOT NULL at table-creation time prevents a large share of these problems at the source.
Parameter binding: never build SQL from user input
This is the most important safety section in the guide. Suppose a book search takes a title, and someone types ' OR '1'='1 as the title. Building the SQL by concatenating the input:
cur.execute("SELECT title FROM books WHERE title = '" + evil + "';")
produces WHERE title = '' OR '1'='1' — '1'='1' is always true, so the condition holds for every row. A search meant for one book returned all 7. Measured: the string-building version returned 7 rows. With parameter binding:
cur.execute("SELECT title FROM books WHERE title = ?;", (evil,))
Measured: parameter binding returned 0 rows. The ? placeholder makes the database treat the input purely as a literal value to compare — the quotes inside it can no longer change the structure of the SQL. This is SQL injection: an attacker rewrites your query using input. The demo only returned extra rows, but in a real project the same trick bypasses logins and dumps whole user tables. The rule is a single one with no exceptions: wherever user input goes into SQL, use parameter binding, never string building. Python's sqlite3 uses ? as the placeholder; PostgreSQL's psycopg uses %s — different spelling, same idea.
Transactions: all of it happens, or none of it does
Placing an order does two things at once: add a row to the orders table and reduce the stock. If adding the order succeeds but reducing the stock fails, the order stays and the stock never moves — the books no longer add up. A transaction wraps several steps into one unit: either everything commits, or one failure rolls everything back:
cur.execute("BEGIN")
cur.execute("UPDATE books SET stock = stock - 100 WHERE id = 5;")
cur.execute("INSERT INTO orders VALUES (107, 5, 100, '2026-11-23');")
# Check the stock: if it goes negative, raise an error and roll back
if stock < 0:
raise ValueError("Not enough stock, order failed")
con.commit()
Output:
Stock of Three-Body before ordering: 20
Rollback reason: Not enough stock, order failed
Stock of Three-Body after rollback: 20
Total orders after rollback: 6
"Three-Body" has only 20 copies in stock, so ordering 100 at once fails the check and rolls back: the stock is still 20, the order total is still 6, and order 107 was never left behind — as if the order never happened. After a rollback the database is in exactly the state it was in before the order, which is the atomicity of a transaction. For order placement, transfers, and points deductions — anything where "two steps must succeed together" — transactions are not optional, they are required. Checking in memory that the stock is enough without wrapping the steps in a transaction still breaks under concurrent orders: two buyers can both see "enough stock" at the same time and both push the stock below zero — the scenario covered in the already-published concurrency and transactions guide. This guide covers only the SQL-side mechanics.
Putting it together: a daily report for the bookshop
Combining the pieces above answers real business questions — for example, daily revenue over the last four days. This one query uses a join, grouping, aggregation, and sorting together:
SELECT orders.ordered_on AS day, SUM(books.price * orders.qty) AS revenue
FROM orders JOIN books ON orders.book_id = books.id
GROUP BY orders.ordered_on ORDER BY day;
Output:
('2026-11-20', 118.0)
('2026-11-21', 296.0)
('2026-11-22', 276.0)
('2026-11-23', 208.0)
Check it by hand: 20 November has only order 101 at 118; 21 November is order 102 at 59 plus order 103 at 237, totalling 296; 22 November is order 104 at 276; 23 November is order 105 at 69 plus order 106 at 139, totalling 208. The four days add up to 898, exactly the sum of the six order amounts from the details above — 118 + 59 + 237 + 276 + 69 + 139 = 898. Grouped totals that match the detail rows mean nothing was missed and nothing double-counted. The habit of checking a grouped sum against the detail total catches many mistakes the moment they happen.
The report can keep growing from here: to see "the best-selling book each day", wrap the report query in another layer with a window function and take rank 1 per day; to see "which category contributed the most revenue", change the GROUP BY column from the date to the category. The building blocks are all ones this guide already covered, recombined — no new syntax needed. Most real project reports are arrangements of these same blocks. Learn each block well first, then combine them; it is much faster than memorising complex queries up front.
The five traps beginners hit most
Trap one: comparing with = NULL in a WHERE clause, which never matches a row; test for emptiness with IS NULL or IS NOT NULL. Trap two: using WHERE to filter groups after grouping, which errors out; filter rows before grouping with WHERE, filter groups after grouping with HAVING — the two jobs must not be mixed. Trap three: COUNT(*) and COUNT(column) count different things, because the second skips NULLs; after a left join, count the right table's rows with COUNT(right_table.id). Trap four: paging without ORDER BY — order is not guaranteed, and the same row can appear once on each of two pages. Trap five: building SQL by concatenating user input, which leaves the door open to injection; parameter binding has no exceptions.
Wrap-up and checklist
In one sentence: SQL is a language for describing "the data I want" — filter rows with WHERE, group with GROUP BY and filter groups with HAVING, join tables with JOIN (and LEFT JOIN when rows with missing data must stay), rank with window functions, bind all user input as parameters, and wrap multi-step writes in a transaction. After this guide, check yourself against this list: can you write "the average price of books in each category" and "how many orders each book sold"? Can you say how an inner join differs from a left join? Can you explain why COUNT(*) and COUNT(column) give different answers? Can you write one window function that ranks books inside their category? Can you say which steps must go inside a transaction? If all of those are yes, this SQL foundation is solid. The best next exercise is to take a real table from your own vibe project and ask it three questions with the sentence patterns from this guide — if the answers line up, SQL is genuinely in your hands. The full demo code lives in the draft folder as demo242_zh.py, and the English rerun script is rerun_en_demo242_g2.py; the two runs agree on the numbers.
Boundaries with already-published guides: this guide covers basic SQL queries (SELECT, JOIN, GROUP BY, window functions, transactions, parameter binding). It does not cover slow-query and index optimisation (a separate slow-query and indexing guide covers that), it does not cover schema migrations (a separate database migration guide covers that), and it does not cover transaction isolation and overselling under concurrency (a separate concurrency and transactions guide covers the ordering scenario with Prisma and Drizzle). The four guides each cover their own stretch, with no overlap.
Comments (0)
Sources
Related articles
Author 137's books, 20000 rows: SCAN takes 0.177 s for 200 runs, one index makes it 0.012 s, 14.9x faster, same 100 rows. JOIN and subquery both return 2000 rows in about 0.020 s, and a covering index drops the temp B-tree sort. SQLite 3.45.1, stdlib only.
tmux 3.4, zero packages: 1 session, 2 windows, 3 panes; the logs window prints 1 to 5, editor panes report ready. Detach with Ctrl-b d, reattach with tmux attach — the session outlives the connection. Mouse, prefix key and history limit in ~/.tmux.conf included.
GCC 13.3.0, C17, zero packages: a first C program, sizeof results 1/2/4/8/8/4/8/8, sum 1..100 is 5050, 10! is 3628800, 8 numbers sorted, 3 books total 1088 pages, 3 file lines and 70 chars read back. Preprocessing alone expands 3 lines to 815.