Skip to content
Raisalon

Software Engineering

SQLite ORDER BY and “USE TEMP B-TREE” explained

Read a SQLite query plan, match a composite index to a filtered sort, and return the newest five records without building a temporary sorting tree.

Author
3 min read

SQLite can use an index to find the right customer’s invoices and still build a temporary B-tree to sort them. The clue in EXPLAIN QUERY PLAN is USE TEMP B-TREE FOR ORDER BY. Read the filter and the ordering together. For a query that asks for the newest five invoices of one customer, an index beginning with customer and continuing with the sort keys can do both jobs.

Build a small invoice archive

Run these SQL blocks in order in a fresh SQLite database. The data is synthetic, so you can repeat the experiment without inspecting anyone’s invoices. The timestamp is an integer measured in seconds. Several invoices share a timestamp so that tie-breaking affects which five IDs you get back.

CREATE TABLE invoice (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL,
  issued_at INTEGER NOT NULL,
  amount_cents INTEGER NOT NULL
);

WITH RECURSIVE seq(n) AS (
  VALUES (1)
  UNION ALL SELECT n + 1 FROM seq WHERE n < 1000
)
INSERT INTO invoice
SELECT n, n % 10, 1700000000 + CAST(n / 50 AS INTEGER), n * 10
FROM seq;

CREATE INDEX invoice_customer ON invoice(customer_id);

The query below looks up customer 7 and asks for the last five invoices, newest first. The secondary ordering by ID gives an unambiguous result within a timestamp. Without a tie-breaker the database is free to return tied rows in any order, which becomes especially awkward when a tie overlaps the fifth row.

EXPLAIN QUERY PLAN
SELECT id, issued_at
FROM invoice
WHERE customer_id = 7
ORDER BY issued_at DESC, id DESC
LIMIT 5;

Look for two details. The search step uses the customer index to find matching invoices. The temporary sorting step indicates that the chosen access path cannot supply those invoices in the requested order. SQLite’s plan output is a debugging aid whose exact wording can change across versions. SQLite guide to EXPLAIN QUERY PLAN

Put the equality key before the ordering keys

Imagine the index entries as a sorted list. In a list ordered by customer first, all entries for customer 7 sit together. Inside that range, descending issue time puts the newest invoice at the front. Descending ID settles any ties. The engine can begin at the matching range and stop after five entries.

CREATE INDEX invoice_customer_newest
ON invoice(customer_id, issued_at DESC, id DESC);

EXPLAIN QUERY PLAN
SELECT id, issued_at
FROM invoice
WHERE customer_id = 7
ORDER BY issued_at DESC, id DESC
LIMIT 5;

SELECT id, issued_at
FROM invoice WHERE customer_id = 7
ORDER BY issued_at DESC, id DESC LIMIT 5;

The five IDs are 997, 987, 977, 967 and 957. With the composite index, the plan can show a covering index search and omit the temporary sort. A covering index supplies every value this query needs. Add amount_cents to the result and SQLite may have to visit the table for that value, even while the index still supplies the order. Sorting and covering are two separate benefits. SQLite query planner guide

Follow the request when it changes

Now suppose the product team wants the newest five invoices across all customers. The same index groups by customer before time. The newest invoice for customer 8 might precede every invoice for customer 7 in a global feed, but their records live in different index ranges. Rerun the plan without the customer equality condition. A new sort is a reasonable outcome for a genuinely different question.

Another small change is ORDER BY issued_at DESC, id ASC. Scanning an index backward reverses the direction of the entire sequence. It cannot selectively reverse the tie-breaker inside each timestamp group. If the mixed direction is a requirement, test an index matching that order, and check whether SQLite sorts only the unsatisfied part. Think about the ordering within a group before creating a new index for every query spelling.

Decide whether the extra index earns its keep

An index consumes space and has to be maintained on writes. Try realistic customer sizes, including the account with a long history. A development database with three invoices per customer gives the sorter very little work. On the other hand, a report that returns almost the entire table might be quite happy with a scan and sort. Record the chosen plan alongside elapsed time using the same data and database settings.

Check result correctness before timing. For example, a change from numeric timestamps to inconsistently formatted date strings can silently alter chronological ordering. A fast index will faithfully produce the order of its stored keys. If the stored values are epoch timestamps, confirm the unit on a known invoice using the Unix timestamp converter.

Next steps

Copy the exact production-shaped query into a scratch database, including its filters, tie-breakers and limit. Keep a before-and-after plan and the returned IDs. If the sorting step disappears and both result lists agree, you have evidence that the new access path preserves the report’s meaning. Use representative timings to decide whether that improvement justifies another index.

Share

Written by