← Back to SQL, page 12

sql-0221 · Hard senior

What is a clustered index, and how do SQLite rowid tables and PostgreSQL heap tables relate to it?

A clustered index stores the table rows themselves in index order, so the table is the index. In SQLite, an ordinary table is a B-tree keyed by rowid (or the INTEGER PRIMARY KEY), and a WITHOUT ROWID table is clustered on its declared primary key. PostgreSQL stores rows in an unordered heap and every index, including the primary key, points into it; CLUSTER reorders the heap once but does not maintain the order.

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:

sql
CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT);
EXPLAIN QUERY PLAN SELECT v FROM t WHERE id = 5;
text
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:

sql
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;
text
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.

sql
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