36. The whole guide on one page
Every statement of the guide, short and grouped, each with a one-line example and a link to the chapter that teaches it.
The order of a SELECT
Open this page when you can't remember how a statement is written. The examples in the tables use the practice shop's data, so you can type nearly all of them. For the full story, follow the chapter number in the last column.
One query can use many parts at once, but they must always be written in this order. This one finds the sales of each category, from orders that weren't cancelled, keeps the categories that sold more than 500 baht, and puts the biggest first:
SELECT c.name AS category, sum(oi.qty * oi.price) AS sales
FROM order_item AS oi
JOIN orders AS o ON o.id = oi.order_id
JOIN product AS p ON p.id = oi.product_id
JOIN category AS c ON c.id = p.category_id
WHERE o.status <> 'cancelled'
GROUP BY c.name
HAVING sum(oi.qty * oi.price) > 500
ORDER BY sales DESC
LIMIT 3;| category | sales |
|---|---|
| Stationery | 1065.0 |
| Snacks | 785.0 |
| Bakery | 750.0 |
Three categories, Stationery the best at 1,065 baht. Drinks (610 baht) passes the HAVING too, but LIMIT 3 leaves it out.
The database doesn't work in the order the parts are written, but in the order of this table. Knowing it explains why WHERE can't filter by sum() (there are no groups yet: that is HAVING's job) and why ORDER BY can use a name (alias) given in the SELECT:
| Step | Part | What it does |
|---|---|---|
| 1 | FROM / JOIN | gathers the rows from the tables |
| 2 | WHERE | filters row by row |
| 3 | GROUP BY | makes the groups |
| 4 | HAVING | filters group by group |
| 5 | SELECT | works out the columns shown (aliases are born here) |
| 6 | ORDER BY | sorts |
| 7 | LIMIT / OFFSET | keeps only some of the rows |
Reading, filtering and sorting
Reading
| To | Example | Chapter |
|---|---|---|
| choose columns | SELECT name, price FROM product; | 2 |
| every column | SELECT * FROM category; | 2 |
| drop repeated rows | SELECT DISTINCT city FROM customer; | 2 |
| work out and name a column | SELECT name, price * 1.07 AS with_vat FROM product; | 7 |
| round | SELECT round(10 / 3.0, 2); | 7 |
| change a type | SELECT CAST('42' AS INTEGER) + 1; | 7 |
Filtering
| To | Example | Chapter |
|---|---|---|
| compare | SELECT name FROM product WHERE price > 50; | 3 |
| and / or | SELECT name FROM product WHERE price < 50 AND stock > 0; | 4 |
| one of a list | SELECT name FROM customer WHERE city IN ('Bangkok', 'Phuket'); | 4 |
| in a range | SELECT name FROM product WHERE price BETWEEN 30 AND 60; | 4 |
| starts with | SELECT name FROM product WHERE name LIKE 'C%'; | 5 |
| no value | SELECT name FROM customer WHERE phone IS NULL; | 5 |
| a stand-in for NULL | SELECT name, coalesce(phone, '-') FROM customer; | 5 |
Sorting and cutting
| To | Example | Chapter |
|---|---|---|
| sort, smallest first | SELECT name, price FROM product ORDER BY price; | 6 |
| sort, biggest first | SELECT name, price FROM product ORDER BY price DESC; | 6 |
| sort by several columns | SELECT name, city FROM customer ORDER BY city, name; | 6 |
| only N rows | SELECT name, price FROM product ORDER BY price DESC LIMIT 3; | 6 |
| the next page | SELECT name FROM product ORDER BY id LIMIT 5 OFFSET 5; | 6 |
Dates and times
| To | Example | Chapter |
|---|---|---|
| today | SELECT date('now'); | 8 |
| add days | SELECT date('2026-12-01', '+7 days'); | 8 |
| year and month | SELECT strftime('%Y-%m', ordered) FROM orders; | 8 |
| days between | SELECT julianday('2026-12-01') - julianday(joined) FROM customer; | 8 |
| end of the month | SELECT date('2026-02-10', 'start of month', '+1 month', '-1 day'); | 8 |
Summing up and joining
Summing up and grouping
| To | Example | Chapter |
|---|---|---|
| count, sum, average | SELECT count(*), sum(stock), avg(price) FROM product; | 9 |
| smallest, biggest | SELECT min(price), max(price) FROM product; | 9 |
| count distinct values | SELECT count(DISTINCT city) FROM customer; | 9 |
| sum up per group | SELECT city, count(*) FROM customer GROUP BY city; | 10 |
| filter groups | SELECT city, count(*) FROM customer GROUP BY city HAVING count(*) >= 3; | 10 |
| join a group's values | SELECT city, group_concat(name, ', ') FROM customer GROUP BY city; | 10 |
JOIN
| To | Example | Chapter |
|---|---|---|
| matching rows | SELECT p.name, c.name FROM product AS p JOIN category AS c ON c.id = p.category_id; | 11 |
| keep every left row | SELECT c.name, o.id FROM customer AS c LEFT JOIN orders AS o ON o.customer_id = c.id; | 12 |
| left rows with no match | SELECT c.name FROM customer AS c LEFT JOIN orders AS o ON o.customer_id = c.id WHERE o.id IS NULL; | 12 |
Subqueries, sets and CASE
| To | Example | Chapter |
|---|---|---|
| compare with a subquery's value | SELECT name FROM product WHERE price > (SELECT avg(price) FROM product); | 13 |
| in a subquery's result | SELECT name FROM customer WHERE id IN (SELECT customer_id FROM orders); | 13 |
| is there a matching row? | SELECT name FROM customer AS c WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id); | 13 |
| two results together | SELECT name FROM category UNION ALL SELECT name FROM product; | 14 |
| in the first, not the second | SELECT id FROM customer EXCEPT SELECT customer_id FROM orders; | 14 |
| in both | SELECT customer_id FROM orders WHERE status = 'paid' INTERSECT SELECT customer_id FROM orders WHERE status = 'shipped'; | 14 |
| a value by condition | SELECT name, CASE WHEN stock = 0 THEN 'sold out' ELSE 'in stock' END FROM product; | 15 |
Changing data
Adding, changing, deleting
| To | Example | Chapter |
|---|---|---|
| add a row | INSERT INTO category (name) VALUES ('Toys'); | 16 |
| add several rows | INSERT INTO category (name) VALUES ('Fruit'), ('Pet'); | 16 |
| add from a query | INSERT INTO category (name) SELECT upper(name) FROM category WHERE id = 1; | 16 |
| change values | UPDATE product SET price = price + 5 WHERE id = 11; | 17 |
| delete rows | DELETE FROM category WHERE name = 'Pet'; | 17 |
| add, or change if there | INSERT INTO category (id, name) VALUES (5, 'Toys & Games') ON CONFLICT (id) DO UPDATE SET name = excluded.name; | 18 |
| see the rows just changed | UPDATE product SET stock = stock + 10 WHERE stock = 0 RETURNING id, name, stock; | 18 |
Transactions
| To | Example | Chapter |
|---|---|---|
| start | BEGIN; | 19 |
| keep it all | COMMIT; | 19 |
| undo it all | ROLLBACK; | 19 |
| a point to return to | SAVEPOINT before_price; | 19 |
| back to that point | ROLLBACK TO before_price; | 19 |
Designing a database
Tables and their rules
CREATE TABLE supplier (
id INTEGER PRIMARY KEY, -- the row's number
name TEXT NOT NULL UNIQUE, -- never empty, never twice
phone TEXT,
rating INTEGER DEFAULT 3 CHECK (rating BETWEEN 1 AND 5),
category_id INTEGER REFERENCES category(id) -- foreign key
);| To | Example | Chapter |
|---|---|---|
| make a table | CREATE TABLE supplier (id INTEGER PRIMARY KEY, name TEXT NOT NULL); | 20 |
| a table with strict types | CREATE TABLE note (id INTEGER PRIMARY KEY, body TEXT) STRICT; | 20 |
| a column's rules | NOT NULL, UNIQUE, DEFAULT 0, CHECK (price >= 0) | 21 |
| point to another table | category_id INTEGER REFERENCES category(id) | 22 |
| turn foreign keys on | PRAGMA foreign_keys = ON; | 22 |
| add a column | ALTER TABLE supplier ADD COLUMN phone TEXT; | 23 |
| rename a column | ALTER TABLE supplier RENAME COLUMN phone TO tel; | 23 |
| drop a column | ALTER TABLE supplier DROP COLUMN tel; | 23 |
| rename a table | ALTER TABLE supplier RENAME TO vendor; | 23 |
| drop a table | DROP TABLE vendor; | 20 |
| see a table's columns | PRAGMA table_info(product); | 20 |
Indexes and views
| To | Example | Chapter |
|---|---|---|
| make an index | CREATE INDEX customer_city ON customer(city); | 25 |
| a unique index | CREATE UNIQUE INDEX customer_phone ON customer(phone); | 25 |
| see a table's indexes | PRAGMA index_list(customer); | 25 |
| drop an index | DROP INDEX customer_phone; | 25 |
| make a view | CREATE VIEW in_stock AS SELECT id, name, stock FROM product WHERE stock > 0; | 30 |
| use a view | SELECT * FROM in_stock; | 30 |
| drop a view | DROP VIEW in_stock; | 30 |
Triggers
A trigger is a statement the database runs by itself when data changes, for example taking stock whenever a new order item comes in (chapter 31):
CREATE TRIGGER take_stock AFTER INSERT ON order_item
BEGIN
UPDATE product SET stock = stock - NEW.qty WHERE id = NEW.product_id;
END;
DROP TRIGGER take_stock;Advanced
WITH and window functions
| To | Example | Chapter |
|---|---|---|
| name a part of a query | WITH cheap AS (SELECT * FROM product WHERE price < 40) SELECT name FROM cheap; | 26 |
| a recursive query | WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 5) SELECT i FROM n; | 27 |
| number the rows | SELECT name, price, row_number() OVER (ORDER BY price DESC, id) AS n FROM product ORDER BY n; | 28 |
| rank within each group | SELECT category_id, name, rank() OVER (PARTITION BY category_id ORDER BY price DESC) AS r FROM product ORDER BY category_id, r; | 28 |
| the previous row's value | SELECT id, ordered, lag(ordered) OVER (ORDER BY id) FROM orders; | 28 |
| a running total | SELECT name, stock, sum(stock) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM product; | 29 |
JSON
| To | Example | Chapter |
|---|---|---|
| make JSON | SELECT json_object('name', name, 'price', price) FROM product; | 32 |
| read a value in JSON | SELECT json_extract('{"a": {"b": 5}}', '$.a.b'); | 32 |
| read it, the short way | SELECT '{"name": "Coffee"}' ->> '$.name'; | 32 |
| an array as rows | SELECT value FROM json_each('[10, 20, 30]'); | 32 |
| rows into an array | SELECT json_group_array(name) FROM category; | 32 |
Text
| To | Example | Chapter |
|---|---|---|
| upper and lower case | SELECT upper(name), lower(name) FROM category; | 33 |
| length | SELECT name, length(name) FROM product; | 33 |
| take a part | SELECT substr(phone, 1, 3) FROM customer; | 33 |
| replace | SELECT replace(phone, '-', '') FROM customer; | 33 |
| trim spaces | SELECT trim(' Coffee '); | 33 |
| find where | SELECT name, instr(name, ' ') FROM customer; | 33 |
| format | SELECT format('%s costs %.2f baht', name, price) FROM product; | 33 |
Text is joined with ||:
SELECT name || ' (' || city || ')' AS who FROM customer WHERE city = 'Phuket';| who |
|---|
| Pim Chaiya (Phuket) |
| Siriporn Kaewdee (Phuket) |
Thai dictionary order is COLLATE THAI, Phai SQL's own (SQLite hasn't got it). See how ไก่ (chicken) comes before ขนม (sweets): Thai words are ordered by their consonants, and ก comes before ข, whatever vowel is written first:
SELECT column1 AS word FROM (VALUES ('ขนม'), ('ไก่'), ('กาแฟ')) ORDER BY word COLLATE THAI;| word |
|---|
| กาแฟ |
| ไก่ |
| ขนม |
In real work
| To | Example | Chapter |
|---|---|---|
| is there any? (stops at the first) | SELECT EXISTS (SELECT 1 FROM orders WHERE customer_id = 1); | 34 |
| a range, not a function | SELECT id FROM orders WHERE ordered >= '2026-10-01' AND ordered < '2026-11-01'; | 34 |
| pack the file | VACUUM; | 34 |
| a parameter | SELECT name FROM product WHERE id = ?; | 35 |
| back up to a new file | VACUUM INTO 'backup.db'; | 35 |
| check the file | PRAGMA integrity_check; | 35 |
Phai SQL has no EXPLAIN QUERY PLAN yet. Phai Database Studio shows a query's plan: the Plan button on the SQL tab (or Ctrl+L) (chapter 34).
Put several things together in one query:
- Show each customer's name and how many orders they have, including those who have never ordered (as 0), most first, then by name.
- Show the 3 products sold in the largest numbers (the sum of
qty), from orders that weren't cancelled. - With
WITH, find the sales of each month (strftime('%Y-%m', ordered)), leaving out cancelled orders, then add a running total with a window function.
Show the answer
SELECT c.name, count(o.id) AS orders
FROM customer AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id
ORDER BY orders DESC, c.name;
SELECT p.name, sum(oi.qty) AS sold
FROM order_item AS oi
JOIN orders AS o ON o.id = oi.order_id
JOIN product AS p ON p.id = oi.product_id
WHERE o.status <> 'cancelled'
GROUP BY p.id
ORDER BY sold DESC, p.name
LIMIT 3;
WITH monthly AS (
SELECT strftime('%Y-%m', o.ordered) AS month, sum(oi.qty * oi.price) AS sales
FROM orders AS o
JOIN order_item AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY month
)
SELECT month, sales, sum(sales) OVER (ORDER BY month) AS running_total
FROM monthly
ORDER BY month;| name | orders |
|---|---|
| Somchai Jaidee | 3 |
| Anan Wongsa | 2 |
| Kanya Boonmee | 2 |
| Malee Srisuk | 2 |
| Pim Chaiya | 2 |
| Wichai Saelim | 2 |
| Narin Thongdee | 1 |
| Siriporn Kaewdee | 1 |
| Lalita Meesuk | 0 |
| Tawan Rungruang | 0 |
| name | sold |
|---|---|
| Pen | 35 |
| Notebook | 18 |
| Potato Chips | 11 |
| month | sales | running_total |
|---|---|---|
| 2026-09 | 820.0 | 820.0 |
| 2026-10 | 1450.0 | 2270.0 |
| 2026-11 | 940.0 | 3210.0 |
Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made