SQLite ORDER BY and LIMIT: which index does less work?
Find a customer’s 20 newest orders. SQLite can look up that customer and sort the matches, or read orders newest first and skip other customers. Predict which path does less work for each customer.
The query and its two indexes
SELECT id, created_at FROM orders WHERE customer_id = :customer ORDER BY created_at DESC, id DESC LIMIT 20;
View schema, seed and indexes
CREATE TABLE orders ( id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL, created_at INTEGER NOT NULL ); WITH RECURSIVE ids(i) AS ( VALUES (1) UNION ALL SELECT i + 1 FROM ids WHERE i < 20000 ) INSERT INTO orders SELECT i, CASE WHEN i % 2 = 1 THEN 42 ELSE 100 + i % 1000 END, i / 4 FROM ids; CREATE INDEX orders_customer ON orders(customer_id); CREATE INDEX orders_recent ON orders(created_at DESC, id DESC);
Both customer queries use the same 20,000 orders. Jev received the same schema, seed, query and customer frequencies. Commit your pick to see its frozen prediction alongside the live SQLite plans.
Frequent customer
Customer 42 has 10,000 of the 20,000 orders.
Rare customer
Customer 102 has 20 of the 20,000 orders.
0 of 2 comparisons complete
Why the cheaper path changes
For the frequent customer, reading newest first finds 20 matches in 249 VM steps. Looking up the customer first leaves 10,000 matching orders to consider for the sort and takes 120,031 steps.
For the rare customer, looking up the 20 matches leaves only those rows to sort and takes 271 steps. Reading newest first must pass many other customers’ orders and takes 80,085 steps.
The automatic plan shows which index SQLite chose on this seed. The forced plans show the work each alternative requires. A plan that says SEARCH can cost more than one that says SCAN when LIMIT allows the scan to stop early.
Try another customer
Ask Jev for a fresh prediction, or compare the indexes directly in your browser.
Choose 42 (10,000 orders) or any even number from 100 to 1098 (20 orders each).