Full answer
SQL Server and MySQL InnoDB cluster tables on the primary key, so range scans on the key read neighbouring rows, and secondary indexes store the primary key to find rows.
SQLite works similarly. A rowid table is a B-tree on rowid; an INTEGER PRIMARY KEY is an alias for rowid, so lookups by it go straight to the row:
CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT);
EXPLAIN QUERY PLAN SELECT v FROM t WHERE id = 5;QUERY PLAN
SEARCH t USING INTEGER PRIMARY KEY (rowid=?)A WITHOUT ROWID table is organized by its primary key, which suits composite keys, as in a junction table:
CREATE TABLE enrol (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id)) WITHOUT ROWID;
EXPLAIN QUERY PLAN SELECT course_id FROM enrol WHERE student_id = 1;QUERY PLAN
SEARCH enrol USING PRIMARY KEY (student_id=?)PostgreSQL's heap means the primary key index is just another index. CLUSTER table USING index sorts the heap once, and later inserts are not kept in order.
Why it matters: a random UUID as a clustered key scatters inserts across the whole B-tree, while an increasing key appends at the end.
CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT);
EXPLAIN QUERY PLAN SELECT v FROM t WHERE id = 5;
CREATE TABLE enrol (student_id INTEGER, course_id INTEGER, PRIMARY KEY (student_id, course_id)) WITHOUT ROWID;
EXPLAIN QUERY PLAN SELECT course_id FROM enrol WHERE student_id = 1;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- A clustered index stores rows in key order
- SQLite tables are B-trees on rowid; INTEGER PRIMARY KEY aliases it
- WITHOUT ROWID tables cluster on the primary key
- PostgreSQL uses an unordered heap; CLUSTER is one-off
Common mistakes
- Assuming PostgreSQL keeps rows in primary key order
- Choosing random clustered keys for insert-heavy tables
Follow-ups
- When would WITHOUT ROWID be a good fit?
- How do secondary indexes find rows in a clustered table?
Tips
- Contrast heap and clustered storage