man sql/sqlite-group-by
How SQLite runs GROUP BY and ORDER BY ... LIMIT
A top-N query is one of the first things people write in SQL:
SELECT user_id, count(*) AS n
FROM visits
GROUP BY user_id
ORDER BY n DESC
LIMIT 3;
How does SQLite count the groups, and does it sort every group just to
return three of them? EXPLAIN QUERY PLAN answers in three lines, and two of
those lines say “B-tree”. This article reads the SQLite 3.54.0 source
(select.c and vdbesort.c) and checks each claim against the bytecode
that the sqlite3 CLI on macOS (Apple’s build of 3.54.0) generates.
The test table, in a file art.db, has 100,000 rows with 37,485 distinct
user_id values, made by a deterministic formula so the counts are uneven.
Below, SELECT ... LIMIT 3 in a command stands for the query above.
CREATE TABLE visits(user_id INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100000)
INSERT INTO visits
SELECT (i * 7919 % 100003) * (i * 104729 % 99991) % 50000 FROM n;
The plan
$ sqlite3 art.db "EXPLAIN QUERY PLAN SELECT user_id, count(*) AS n
FROM visits GROUP BY user_id ORDER BY n DESC LIMIT 3;"
QUERY PLAN
|--SCAN visits
|--USE TEMP B-TREE FOR GROUP BY
`--USE TEMP B-TREE FOR ORDER BY
SQLite’s EQP documentation says these lines
appear when “SQLite may need to use a temporary b-tree structure to sort the
output rows”. The caption is a fixed string: explainTempTable() in
select.c prints "USE TEMP B-TREE FOR %s" with DISTINCT, ORDER BY or
GROUP BY filled in. The plan doesn’t say which structure actually runs.
The bytecode does.
GROUP BY is a sort
EXPLAIN without QUERY PLAN lists the virtual machine program. Filtered to
the cursor-related opcodes:
$ sqlite3 art.db "EXPLAIN SELECT ... LIMIT 3;" | grep -E 'Sorter|Ephemeral|IfNotZero|Last|IdxLE|Delete|IdxInsert|Sort '
1 OpenEphemeral 1 4 0 k(1,-B) 0 nColumn=4
3 SorterOpen 2 1 0 k(1,-B) 0
11 SorterInsert 2 11 0 0 key=r[11]
14 SorterSort 2 48 0 0 GROUP BY sort
15 SorterData 2 10 3 0 r[10]=data
27 SorterNext 2 15 0 0
37 IfNotZero 1 41 0 0 if r[1]!=0 then r[1]--, goto 41
38 Last 1 0 0 0
39 IdxLE 1 44 12 1 0 key=r[12]
40 Delete 1 0 0 0
43 IdxInsert 1 16 12 3 0 key=r[16]
48 Sort 1 53 0 0
Cursor 2 is the GROUP BY. It is a SorterOpen cursor: every row’s
user_id goes into the sorter (SorterInsert), the sorter sorts
(SorterSort, commented “GROUP BY sort”), and the loop reads the keys back in
order. Equal keys now sit next to each other, so counting a group is a
running count that is output and reset whenever the key changes. There is
no hash table anywhere. In select.c, the GROUP BY branch of
sqlite3Select() always allocates this cursor with
sqlite3VdbeAddOp4(v, OP_SorterOpen, ...) and turns it into a no-op
(sqlite3VdbeChangeToNoop) only when the WHERE planner can deliver rows already in GROUP BY order. Only in
the other case does it print USE TEMP B-TREE FOR GROUP BY.
The sorter lives in vdbesort.c. Its header comment describes it as a
“multi-threaded external merge sort”, used “for CREATE INDEX statements or by
SELECT statements with ORDER BY clauses that cannot be satisfied using
indexes and without LIMIT clauses”. In outline:
SorterInsert -> append the record to an unsorted in-memory list
(flush the sorted list to a temp file as a "PMA"
when it grows past the threshold)
SorterSort -> merge sort the list; merge PMAs, at most 16 at a time
SorterNext -> hand out records in order
The in-memory sort, vdbeSorterSort(), is a bottom-up merge sort over a
linked list with an array of 64 slots, where slot i holds a sorted run of
2^i records. Before sorting, vdbeSorterGetCompare() picks a comparator.
If every record’s first field was an integer it uses
vdbeSorterCompareInt, which never decodes the record. SQLite stores
integers big-endian, so two integers of the same size are compared byte by
byte, like memcmp, with a fix-up for the sign.
The flush threshold is “the value returned by PRAGMA main.page_size
multiplied by that returned by PRAGMA main.cache_size, in bytes”. On this
build those are 4096 and 2000, so about 8 MB. With more than
SORTER_MAX_MERGE_COUNT (16) PMAs, the merge becomes a tree of merges.
A single-threaded sorter appends all its PMAs to one temp file. PRAGMA threads returns 0 here, so the sorter runs on one thread.
ORDER BY … LIMIT keeps three rows
Cursor 1 is the ORDER BY. It is an OpenEphemeral cursor, a real temporary
B-tree, and opcodes 37 to 43 run once per finished group:
IfNotZero r[1] fewer than 3 rows kept so far? -> just insert
Last else look at the last entry (the smallest count so far)
IdxLE new count <= that one? -> skip this group
Delete else delete the last entry
IdxInsert insert the new group
This is pushOntoSorter() in select.c. Its comment says the record is
inserted only “if either (a) there are currently less than LIMIT+OFFSET items
or (b) the new record is smaller than the largest record currently in the
sorter”, and that “there are never more than LIMIT+OFFSET items in the
sorter”. “Smaller” is in ORDER BY order, which for n DESC means a bigger
count. So the B-tree that answers LIMIT 3 never holds more than three rows,
however many groups there are. A group that doesn’t make the top three
costs one comparison with the last entry.
Why a B-tree here and the sorter elsewhere? sqlite3Select() first codes
every ORDER BY as OP_OpenEphemeral. Then, after computing the LIMIT
registers, it does this:
if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
sSort.sortFlags |= SORTFLAG_UseSorter;
}
No LIMIT, and the ORDER BY becomes a sorter like the GROUP BY. The B-tree
supports deleting its last entry, which a capped top-N needs. The sorter is
append-then-sort and can’t. The same query without LIMIT 3 confirms it:
$ sqlite3 art.db "EXPLAIN SELECT user_id, count(*) AS n FROM visits
GROUP BY user_id ORDER BY n DESC;" | grep -E 'Sorter(Open|Insert|Sort)|Ephemeral'
1 SorterOpen 1 4 0 k(1,-B) 0
2 SorterOpen 2 1 0 k(1,-B) 0
10 SorterInsert 2 10 0 0 key=r[10]
13 SorterSort 2 42 0 0 GROUP BY sort
37 SorterInsert 1 14 11 2 0 key=r[14]
43 SorterSort 1 49 0 0
The CLI can count the rows. This build has SQLITE_ENABLE_STMT_SCANSTATUS,
so .scanstats on adds loop and row counts to the plan:
$ sqlite3 art.db ".scanstats on" "SELECT ... LIMIT 3;"
10000|34
42800|32
30000|30
QUERY PLAN
|--SCAN visits 1 100K
|--USE TEMP B-TREE FOR GROUP BY 1 100K
`--USE TEMP B-TREE FOR ORDER BY 1 37.4K
All 37,485 groups are offered to the ORDER BY step, but the B-tree they are offered to stays at three rows.
The GROUP BY borrows the ORDER BY’s direction
Look again at the two k(...) descriptions in the first listing. The ORDER
BY’s key is k(1,-B): one field, descending (-), binary collation. The
GROUP BY’s key is also k(1,-B). Nobody asked for GROUP BY user_id DESC.
$ for o in "n DESC" "n" "n DESC, user_id"; do
echo "-- ORDER BY $o"
sqlite3 art.db "EXPLAIN SELECT user_id, count(*) AS n FROM visits
GROUP BY user_id ORDER BY $o LIMIT 3;" |
grep -E 'SorterOpen|OpenEphemeral' | awk '{print $2, $6}'
done
-- ORDER BY n DESC
OpenEphemeral k(1,-B)
SorterOpen k(1,-B)
-- ORDER BY n
OpenEphemeral k(1,B)
SorterOpen k(1,B)
-- ORDER BY n DESC, user_id
OpenEphemeral k(2,-B,B)
SorterOpen k(1,B)
The reason is sqlite3CopySortOrder() in select.c. If the GROUP BY and
ORDER BY lists “have the same number of terms”, it copies each ORDER BY
term’s direction onto the GROUP BY term in the same position. Then it
checks whether the two lists are the same expressions; if so, one sort can
serve both. That check fails here (user_id is not n), but the copied
direction stays. Grouping doesn’t care about direction, so the groups are
the same. Their order is different, and that decides ties.
The B-tree keeps the first of several equal counts it meets, because IdxLE
skips a new row whose count equals the last one kept. Groups arrive in GROUP
BY order. Under n DESC that is descending user_id:
$ sqlite3 art.db "SELECT user_id, count(*) AS n FROM visits GROUP BY user_id ORDER BY n DESC LIMIT 3;"
10000|34
42800|32
30000|30
$ sqlite3 art.db "SELECT user_id, count(*) AS n FROM visits GROUP BY user_id ORDER BY n DESC, user_id LIMIT 3;"
10000|34
42800|32
0|30
Users 30000 and 0 both have 30 visits. Without a tiebreaker you get 30000,
the larger ID. With user_id as a second ORDER BY term, the lists no longer
have the same length, the GROUP BY sorts ascending, and you get 0, which is
also what the tiebreaker asks for. SQL makes no promise about the first
answer. The second is the only one you can rely on.
What an index changes
An index on user_id stores the IDs already sorted, so the GROUP BY needs
no sort:
$ cp art.db art_idx.db
$ sqlite3 art_idx.db "CREATE INDEX visits_user ON visits(user_id);" \
"EXPLAIN QUERY PLAN SELECT ... LIMIT 3;" ".scanstats on" "SELECT ... LIMIT 3;"
QUERY PLAN
|--SCAN visits USING COVERING INDEX visits_user
`--USE TEMP B-TREE FOR ORDER BY
10000|34
42800|32
0|30
QUERY PLAN
|--SCAN visits USING COVERING INDEX visits_user 1 100K
`--USE TEMP B-TREE FOR ORDER BY 1 37.4K
The GROUP BY line is gone, and the tie now resolves to user 0, because the
index hands out IDs in ascending order. Adding an index changed the result
of a query. The ORDER BY still needs its three-row B-tree: no index can know
the counts in advance.
Building that index is not free. EXPLAIN CREATE INDEX shows the same
sorter: SorterOpen, SorterInsert, SorterSort. The sort moves from the
query to the index build. That pays off when many queries use the index,
and costs time for a table that will be queried once.
Curious facts
USE TEMP B-TREE FOR GROUP BYis printed for a cursor opened withOP_SorterOpen, which is a merge sorter, not a B-tree. For an ORDER BY with a LIMIT the caption is literally true.LIMIT 3caps the ORDER BY’s B-tree at LIMIT+OFFSET rows.LIMIT 3 OFFSET 1000keeps 1,003.GROUP BY x ORDER BY count(*) DESCsorts the groups byxdescending, because the ORDER BY has one term and so does the GROUP BY. Add a second ORDER BY term and the one-term GROUP BY goes back to ascending.- The sorter picks a specialized comparator when every key’s first field is
an integer (
vdbeSorterCompareInt), or every one is text (vdbeSorterCompareText). Integers mixed with floats getvdbeSorterCompareReal. One text value among numbers falls back to the general comparator. - The in-memory sort keeps 64 slots of runs, sized for powers of two. The source comment notes that the 64 slots can never all be used “with only a 64-bit address space”.
History
- The
vdbesort.cfile header is dated 2011-07-09. - 3.8.7 (2014-10-17): “The sorter can use auxiliary helper threads”, off by
default and enabled with
PRAGMA threads. - 3.21.0 (2017-10-24): the planner prefers co-routines for FROM-clause subqueries with an ORDER BY, so expensive work can be moved after the sort and the LIMIT (optoverview, section 12.1).
- 3.25.0 (2018-09-15): window functions, whose
OVER (ORDER BY ...)is another place a full sort appears.
Sources
src/select.cat version-3.54.0 (GitHub mirror): pushOntoSorter, the LIMIT branch, explainTempTable, ORDER BY caption, sqlite3CopySortOrder, OpenEphemeral becomes SorterOpen without a LIMIT, GROUP BY and ORDER BY share a direction, GROUP BY sorter and its Noop, GROUP BY captionsrc/vdbesort.cat version-3.54.0: header and algorithm, SORTER_MAX_MERGE_COUNT, threshold from page_size and cache_size, vdbeSorterCompareInt, vdbeSorterGetCompare and vdbeSorterSort, typeMask in sqlite3VdbeSorterWrite- EXPLAIN QUERY PLAN, section 1.2
- The SQLite query optimizer overview, section 12
- Release history: 3.8.7, 3.21.0, 3.25.0
grep -rl /lib/sql/sqlite-group-by/
ls sql/
- draft Multiplying rows in SQL: SQLite has no PRODUCT()SQLite can sum a column but not multiply one. Why the exp(sum(ln(x))) trick got 15% of products of three numbers under 100,000 wrong, how a recursive CTE folds rows exactly, and what SQLite 3.54 does when the integers overflow.