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;
categorysales
Stationery1065.0
Snacks785.0
Bakery750.0
3 rows

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:

StepPartWhat it does
1FROM / JOINgathers the rows from the tables
2WHEREfilters row by row
3GROUP BYmakes the groups
4HAVINGfilters group by group
5SELECTworks out the columns shown (aliases are born here)
6ORDER BYsorts
7LIMIT / OFFSETkeeps only some of the rows

Reading, filtering and sorting

Reading

ToExampleChapter
choose columnsSELECT name, price FROM product;2
every columnSELECT * FROM category;2
drop repeated rowsSELECT DISTINCT city FROM customer;2
work out and name a columnSELECT name, price * 1.07 AS with_vat FROM product;7
roundSELECT round(10 / 3.0, 2);7
change a typeSELECT CAST('42' AS INTEGER) + 1;7

Filtering

ToExampleChapter
compareSELECT name FROM product WHERE price > 50;3
and / orSELECT name FROM product WHERE price < 50 AND stock > 0;4
one of a listSELECT name FROM customer WHERE city IN ('Bangkok', 'Phuket');4
in a rangeSELECT name FROM product WHERE price BETWEEN 30 AND 60;4
starts withSELECT name FROM product WHERE name LIKE 'C%';5
no valueSELECT name FROM customer WHERE phone IS NULL;5
a stand-in for NULLSELECT name, coalesce(phone, '-') FROM customer;5

Sorting and cutting

ToExampleChapter
sort, smallest firstSELECT name, price FROM product ORDER BY price;6
sort, biggest firstSELECT name, price FROM product ORDER BY price DESC;6
sort by several columnsSELECT name, city FROM customer ORDER BY city, name;6
only N rowsSELECT name, price FROM product ORDER BY price DESC LIMIT 3;6
the next pageSELECT name FROM product ORDER BY id LIMIT 5 OFFSET 5;6

Dates and times

ToExampleChapter
todaySELECT date('now');8
add daysSELECT date('2026-12-01', '+7 days');8
year and monthSELECT strftime('%Y-%m', ordered) FROM orders;8
days betweenSELECT julianday('2026-12-01') - julianday(joined) FROM customer;8
end of the monthSELECT date('2026-02-10', 'start of month', '+1 month', '-1 day');8

Summing up and joining

Summing up and grouping

ToExampleChapter
count, sum, averageSELECT count(*), sum(stock), avg(price) FROM product;9
smallest, biggestSELECT min(price), max(price) FROM product;9
count distinct valuesSELECT count(DISTINCT city) FROM customer;9
sum up per groupSELECT city, count(*) FROM customer GROUP BY city;10
filter groupsSELECT city, count(*) FROM customer GROUP BY city HAVING count(*) >= 3;10
join a group's valuesSELECT city, group_concat(name, ', ') FROM customer GROUP BY city;10

JOIN

ToExampleChapter
matching rowsSELECT p.name, c.name FROM product AS p JOIN category AS c ON c.id = p.category_id;11
keep every left rowSELECT c.name, o.id FROM customer AS c LEFT JOIN orders AS o ON o.customer_id = c.id;12
left rows with no matchSELECT 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

ToExampleChapter
compare with a subquery's valueSELECT name FROM product WHERE price > (SELECT avg(price) FROM product);13
in a subquery's resultSELECT 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 togetherSELECT name FROM category UNION ALL SELECT name FROM product;14
in the first, not the secondSELECT id FROM customer EXCEPT SELECT customer_id FROM orders;14
in bothSELECT customer_id FROM orders WHERE status = 'paid' INTERSECT SELECT customer_id FROM orders WHERE status = 'shipped';14
a value by conditionSELECT name, CASE WHEN stock = 0 THEN 'sold out' ELSE 'in stock' END FROM product;15

Changing data

Adding, changing, deleting

ToExampleChapter
add a rowINSERT INTO category (name) VALUES ('Toys');16
add several rowsINSERT INTO category (name) VALUES ('Fruit'), ('Pet');16
add from a queryINSERT INTO category (name) SELECT upper(name) FROM category WHERE id = 1;16
change valuesUPDATE product SET price = price + 5 WHERE id = 11;17
delete rowsDELETE FROM category WHERE name = 'Pet';17
add, or change if thereINSERT INTO category (id, name) VALUES (5, 'Toys & Games') ON CONFLICT (id) DO UPDATE SET name = excluded.name;18
see the rows just changedUPDATE product SET stock = stock + 10 WHERE stock = 0 RETURNING id, name, stock;18

Transactions

ToExampleChapter
startBEGIN;19
keep it allCOMMIT;19
undo it allROLLBACK;19
a point to return toSAVEPOINT before_price;19
back to that pointROLLBACK 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
);
ToExampleChapter
make a tableCREATE TABLE supplier (id INTEGER PRIMARY KEY, name TEXT NOT NULL);20
a table with strict typesCREATE TABLE note (id INTEGER PRIMARY KEY, body TEXT) STRICT;20
a column's rulesNOT NULL, UNIQUE, DEFAULT 0, CHECK (price >= 0)21
point to another tablecategory_id INTEGER REFERENCES category(id)22
turn foreign keys onPRAGMA foreign_keys = ON;22
add a columnALTER TABLE supplier ADD COLUMN phone TEXT;23
rename a columnALTER TABLE supplier RENAME COLUMN phone TO tel;23
drop a columnALTER TABLE supplier DROP COLUMN tel;23
rename a tableALTER TABLE supplier RENAME TO vendor;23
drop a tableDROP TABLE vendor;20
see a table's columnsPRAGMA table_info(product);20

Indexes and views

ToExampleChapter
make an indexCREATE INDEX customer_city ON customer(city);25
a unique indexCREATE UNIQUE INDEX customer_phone ON customer(phone);25
see a table's indexesPRAGMA index_list(customer);25
drop an indexDROP INDEX customer_phone;25
make a viewCREATE VIEW in_stock AS SELECT id, name, stock FROM product WHERE stock > 0;30
use a viewSELECT * FROM in_stock;30
drop a viewDROP 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

ToExampleChapter
name a part of a queryWITH cheap AS (SELECT * FROM product WHERE price < 40) SELECT name FROM cheap;26
a recursive queryWITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 5) SELECT i FROM n;27
number the rowsSELECT name, price, row_number() OVER (ORDER BY price DESC, id) AS n FROM product ORDER BY n;28
rank within each groupSELECT 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 valueSELECT id, ordered, lag(ordered) OVER (ORDER BY id) FROM orders;28
a running totalSELECT name, stock, sum(stock) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM product;29

JSON

ToExampleChapter
make JSONSELECT json_object('name', name, 'price', price) FROM product;32
read a value in JSONSELECT json_extract('{"a": {"b": 5}}', '$.a.b');32
read it, the short waySELECT '{"name": "Coffee"}' ->> '$.name';32
an array as rowsSELECT value FROM json_each('[10, 20, 30]');32
rows into an arraySELECT json_group_array(name) FROM category;32

Text

ToExampleChapter
upper and lower caseSELECT upper(name), lower(name) FROM category;33
lengthSELECT name, length(name) FROM product;33
take a partSELECT substr(phone, 1, 3) FROM customer;33
replaceSELECT replace(phone, '-', '') FROM customer;33
trim spacesSELECT trim(' Coffee ');33
find whereSELECT name, instr(name, ' ') FROM customer;33
formatSELECT 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)
2 rows

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:

Phai SQL
SELECT column1 AS word FROM (VALUES ('ขนม'), ('ไก่'), ('กาแฟ')) ORDER BY word COLLATE THAI;
word
กาแฟ
ไก่
ขนม
3 rows

In real work

ToExampleChapter
is there any? (stops at the first)SELECT EXISTS (SELECT 1 FROM orders WHERE customer_id = 1);34
a range, not a functionSELECT id FROM orders WHERE ordered >= '2026-10-01' AND ordered < '2026-11-01';34
pack the fileVACUUM;34
a parameterSELECT name FROM product WHERE id = ?;35
back up to a new fileVACUUM INTO 'backup.db';35
check the filePRAGMA 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:

  1. Show each customer's name and how many orders they have, including those who have never ordered (as 0), most first, then by name.
  2. Show the 3 products sold in the largest numbers (the sum of qty), from orders that weren't cancelled.
  3. 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;
nameorders
Somchai Jaidee3
Anan Wongsa2
Kanya Boonmee2
Malee Srisuk2
Pim Chaiya2
Wichai Saelim2
Narin Thongdee1
Siriporn Kaewdee1
Lalita Meesuk0
Tawan Rungruang0
10 rows
namesold
Pen35
Notebook18
Potato Chips11
3 rows
monthsalesrunning_total
2026-09820.0820.0
2026-101450.02270.0
2026-11940.03210.0
3 rows

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