// dialect comparison

Column-prefix indexes in every SQL dialect

A prefix index stores just the first N characters of a varchar, cutting index size dramatically on long text columns.

Filed under Indizes

The verdict

Only MySQL has real prefix indexes. An expression index or computed column on LEFT/SUBSTR substitutes in the other four, but the indexed value is not the column, so a plain WHERE name = 'x' or a range on name will not use it (SQL Server's computed-column matching is the exception for the exact expression).

Where they differ

MySQL has native prefix syntax with (col(N)). Everyone else approximates it with an expression on the first N characters, which works as long as the query repeats the expression or the prefix is selective enough.

How each engine writes it

SQL Server

ALTER TABLE products ADD name_prefix AS LEFT(name, 20);
CREATE INDEX idx_products_name_prefix ON products (name_prefix);

No prefix indexes. Index a computed column holding LEFT(name, 20), as here, or index the whole column if it fits the 1,700-byte nonclustered key limit.

PostgreSQL

CREATE INDEX idx_products_name ON products (LEFT(name, 20));

No prefix syntax; an expression index on LEFT(name, 20) is the closest. Queries must repeat LEFT(name, 20) = ? to use it, and verify the prefix is selective.

MySQL

CREATE INDEX idx_products_name ON products (name(20));

Native prefix syntax, required for BLOB and TEXT and optional for CHAR and VARCHAR. WHERE name = 'x' uses it directly. A prefix index can never cover a query, because the full value is not stored in it.

SQLite

CREATE INDEX idx_products_name ON products (SUBSTR(name, 1, 20));

No prefix syntax; index the SUBSTR expression. The query must filter on SUBSTR(name, 1, 20) to hit the index.

Oracle

CREATE INDEX idx_products_name ON products (SUBSTR(name, 1, 20));

No prefix syntax; a function-based index on SUBSTR does it. The query must repeat the same SUBSTR expression.

Questions that come up

How do I pick the prefix length?

Compare COUNT(DISTINCT col) with COUNT(DISTINCT LEFT(col, N)) for growing N; pick the smallest N that keeps selectivity close to the full column.

Does a prefix index work for ORDER BY?

No, in MySQL and in the expression-based variants. Sorting on the full column still needs the data or a full index on it.

Why does my query ignore the expression index?

Because WHERE name = 'x' does not mention SUBSTR(name, 1, 20). Only queries written against the expression use the index.

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.