Skip to content

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.

Which index will use fewer SQLite VM steps?

Rare customer

Customer 102 has 20 of the 20,000 orders.

Which index will use fewer SQLite VM steps?

0 of 2 comparisons complete

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).

The plans and returned rows run in your browser. VM steps count executed SQLite virtual machine instructions, measured in advance on this fixture using SQLite 3.49.1. Jev’s two published predictions were recorded with jev-1.14.0 on 2026-11-23. These comparisons apply to this SQLite workload.

Start the free SQL module