Index sorting
Overview
An ordered B-tree can satisfy compatible ORDER BY clauses without a separate sort. A backward scan reverses all key directions, not arbitrary individual directions. Mixed directions, collation, NULL ordering and tie-breaking affect compatibility.
First example
EXPLAIN QUERY PLAN SELECT tenant,day,id FROM ai_event ORDER BY tenant ASC,day DESC,id ASC LIMIT 3;Observed SQLite result (rows in JSON):
[ [ 4, 0, 0, "SCAN ai_event USING COVERING INDEX ai_tenant_day" ]]How it works
The fixture index begins tenant ASC, day DESC, id ASC. The first query matches this ordering; the second requests tenant ASC, day ASC, id ASC, and SQLite uses a temporary B-tree for the last two terms. LIMIT can benefit when compatible index order avoids sorting all qualifying rows. Here the index is scanned, not searched, which is appropriate without a WHERE restriction. PostgreSQL B-tree can scan backward, but mixed directions may require an explicit index design. An index does not guarantee output ordering without ORDER BY. Include a stable tie-breaker for deterministic pagination; concurrent changes can still shift offset pages.
Practical example
EXPLAIN QUERY PLAN SELECT tenant,day,id FROM ai_event ORDER BY tenant ASC,day ASC,id ASC LIMIT 3;Observed SQLite result (rows in JSON):
[ [ 4, 0, 0, "SCAN ai_event USING COVERING INDEX ai_tenant_day" ], [ 25, 0, 0, "USE TEMP B-TREE FOR LAST 2 TERMS OF ORDER BY" ]]Practice and mistakes
Practice: run the first query without EXPLAIN. Hint 1: LIMIT 3. Hint 2: tenant 1, days 991,981,971. Then reverse all three directions and inspect the plan; do not infer timing from plan alone.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TEMP TABLE ai_demo(id integer PRIMARY KEY, tenant integer, day integer, amount integer, tags text[], span int4range, loc point);INSERT INTO ai_demo VALUES (42,2,42,420,ARRAY['sql'],int4range(1,5),point(1,2)),(52,2,52,520,ARRAY['sql','index'],int4range(5,8),point(3,4)),(62,2,62,620,ARRAY['index'],int4range(8,10),point(5,6));CREATE INDEX ai_demo_order ON ai_demo(tenant ASC,day DESC,id ASC);SELECT id FROM ai_demo ORDER BY tenant ASC,day DESC,id ASC LIMIT 2;ROLLBACK;Expected result, not executed: [[62], [52]]