// conditional reference

SQL COALESCE index usage

Why COALESCE(col, default) in a WHERE clause turns index seeks into scans, and the fixes.

カテゴリ
条件付き
Returns
rows
In this category
37 of 43

構文

WHERE COALESCE(col, 'new') = 'new' | WHERE col = 'new' OR col IS NULL

エンジンサポート

エンジンSupportメモ
SQL Server はい Supported under this name.
PostgreSQL はい Supported under this name.
MySQL はい Supported under this name.
SQLite はい Supported under this name.
Oracle はい Supported under this name.

例

PostgreSQL

CREATE INDEX ON users (COALESCE(email, ''));

Any engine

SELECT * FROM users WHERE email = '[email protected]' OR email IS NULL;

知っておくと便利なこと

  • A function on the column makes the predicate non-sargable: the engine must evaluate COALESCE per row unless an expression index matches it exactly.
  • PostgreSQL fix: CREATE INDEX ON t (COALESCE(col, '')) makes the wrapped form seekable.
  • SQL Server fix: add a computed column AS COALESCE(col, '') and index it. MySQL 8.0.13+ supports functional indexes, written with doubled parentheses: INDEX ((COALESCE(col, ''))). SQLite and Oracle accept expression indexes directly.
  • The common intent behind COALESCE(col, 'new') = 'new' is col = 'new' OR col IS NULL, and a plain index on col can answer that form directly. Oracle is the exception: its B-tree indexes do not store all-NULL keys, so the IS NULL half needs a composite index such as (col, 0).

Questions about COALESCE

Why does COALESCE(col, '') = @x ignore my index?

The index is on col, not on COALESCE(col, ''); the engine must compute the expression for every row unless an expression index exists.

What is the sargable rewrite?

Spell out what the COALESCE means. COALESCE(col, @d) = @x is col = @x when @x differs from @d, and col = @x OR col IS NULL when they are equal. Or keep the COALESCE and build an expression index that matches it exactly.

Does this apply to other functions?

Yes: UPPER(col), CAST(col AS ...) and friends all break index use the same way.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.