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.
Related on SQLly
- Replacing NULL in output: COALESCE, ISNULL, NVL, IFNULL Dialect comparison
- Sorting with COALESCE in ORDER BY Dialect comparison
- Find duplicate index candidates Snippet
- Fill gaps with a calendar spine Snippet
- Full outer compare of two result sets Snippet
- Find tables without a primary key Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.