// dialect comparison

Covering indexes and INCLUDE columns in every SQL dialect

A covering index answers a query without touching the table. SQL Server and PostgreSQL have an INCLUDE clause that keeps extra columns out of the key; the rest use composite indexes.

Filed under Index

The verdict

SQL Server and PostgreSQL get a true INCLUDE clause; MySQL, SQLite and Oracle express the same idea with composite indexes. Functionally you can cover a query everywhere, but with INCLUDE the extra columns stay out of uniqueness and sort order.

Where they differ

INCLUDE columns are stored in the index leaf pages but are not part of the key, so they do not affect ordering or uniqueness. If the engine has no INCLUDE, a composite index covers the same query, at the cost of making those columns part of the key.

How each engine writes it

SQL Server

CREATE INDEX idx_orders_customer ON orders (customer_id) INCLUDE (total, status);

INCLUDE has existed since SQL Server 2005. A query that touches only customer_id, total and status is answered by an index seek with no key lookup.

PostgreSQL

CREATE INDEX idx_orders_customer ON orders (customer_id) INCLUDE (total, status);

INCLUDE supported since PostgreSQL 11. Index-only scans additionally need the visibility map warmed by VACUUM.

MySQL

CREATE INDEX idx_orders_customer ON orders (customer_id, total, status);

No INCLUDE clause. Put the extra columns into a composite index; they become part of the key (and of uniqueness, if the index is UNIQUE). InnoDB secondary indexes also carry the primary key, so id is covered for free.

SQLite

CREATE INDEX idx_orders_customer ON orders (customer_id, total, status);

No INCLUDE clause. A composite index covers the query when EXPLAIN QUERY PLAN shows the table access disappearing.

Oracle

CREATE INDEX idx_orders_customer ON orders (customer_id, total, status);

No INCLUDE clause; a composite index serves the same purpose. A B-tree index holds at most 32 columns.

Questions that come up

How do I confirm an index covers a query?

Check the plan: SQL Server shows a seek with no Key Lookup, PostgreSQL says Index Only Scan, MySQL says Using index in Extra, SQLite EXPLAIN QUERY PLAN drops the table step, Oracle shows INDEX range scan with no TABLE ACCESS.

Why not just put everything in one index?

Key columns cost more on every write and widen the index. INCLUDE keeps a narrow key for seeking while still carrying payload columns.

Does a covering index stay covering forever?

No. Add a new column to the query and it stops being covered; re-check the plan after query changes.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.