Set operations and pagination
Overview
Combine result relations, decide whether to retain duplicates, and paginate only after defining a deterministic order. Explain the difference between offset and keyset pagination.
First example
SELECT customer_id FROM lq_order WHERE status='paid' UNION SELECT customer_id FROM lq_order WHERE status='pending' ORDER BY customer_id LIMIT 2 OFFSET 1;Observed SQLite result (rows in JSON):
[ [ 2 ], [ 4 ]]How it works
Each SELECT arm is a query block; UNION removes duplicates, UNION ALL preserves multiplicity. INTERSECT finds shared rows and EXCEPT returns left-only rows under their default distinct semantics. PostgreSQL gives INTERSECT higher precedence than UNION/EXCEPT; SQLite evaluates compound operators left to right. Use explicit query blocks via CTEs to avoid ambiguity. Global ORDER BY and LIMIT/OFFSET apply to the compound result. Example one merges paid and pending customer IDs, orders the three distinct IDs (1,2,4), and skips the first ID: 2,4. Example two sorts orders by amount DESC,id ASC; page 1 ends at (150,2), so page 2 uses amount<150 OR (amount=150 AND id>2). The expected IDs are 6 and 1. Include the unique tie-breaker in both order and cursor. Offset pagination can skip or repeat rows if data changes between requests; keyset pagination reduces positional drift but does not guarantee a consistent snapshot if rows change. Use a stable snapshot when the use case requires it.
Practical example
SELECT id,amount FROM lq_order WHERE amount<150 OR (amount=150 AND id>2) ORDER BY amount DESC,id LIMIT 2;Observed SQLite result (rows in JSON):
[ [ 6, 150 ], [ 1, 100 ]]Practice and mistakes
Practice: replace UNION with UNION ALL and predict the result after OFFSET 1 LIMIT 2. Hint 1: sorted IDs are 1,1,1,2,2,4. Hint 2: keep duplicates. Expected IDs: 1,1. For the second example remove id from the cursor and explain why an equal-price row can be lost.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TEMP TABLE lq_customer(id INTEGER PRIMARY KEY, name TEXT NOT NULL);CREATE TEMP TABLE lq_order(id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES lq_customer(id), amount INTEGER NOT NULL CHECK(amount>=0), status TEXT NOT NULL CHECK(status IN ('paid','pending')));INSERT INTO lq_customer VALUES(1,'Ada'),(2,'Reza'),(3,'Sara'),(4,'Mina');INSERT INTO lq_order VALUES(1,1,100,'paid'),(2,1,150,'paid'),(3,2,250,'paid'),(4,2,50,'pending'),(5,4,80,'pending'),(6,1,150,'pending');CREATE INDEX lq_order_amount ON lq_order(amount,id);CREATE INDEX lq_order_customer ON lq_order(customer_id);
SELECT id,amount FROM lq_order WHERE amount<150 OR (amount=150 AND id>2) ORDER BY amount DESC,id LIMIT 2;ROLLBACK;Expected result, not executed: [[6, 150], [1, 100]]