Sargable WHERE — Index-Seekable Filters in SQL
Bare column vs value seeks; functions force scans
Sargable predicates let the engine seek: bare column compared to a value (col = ?, col > ?, col BETWEEN). Non-sargable forms — functions on columns (YEAR(hired)), leading-% LIKE, arithmetic wrapping, implicit type conversions — force full scans. Write filters index-first, match types, keep columns bare; fix legacy shapes with expression indexes.
Seekable shape
Bare column vs value: col = ?, col > ?, BETWEEN — index seeks O(log n).
Scan-forcing shapes
Functions, leading-%, arithmetic wrapping, type mismatches — full scans O(n).
Rewrite, don’t decorate
YEAR(hired)=2024 → hired range. salary*12>x → salary>x/12.
Fix legacy with indexes
Expression/computed indexes make functional predicates seekable when rewrite is impossible.
1-- slow: WHERE YEAR(hired) = 2024;2-- fast: WHERE hired >= DATE '2024-01-01' AND hired < DATE '2025-01-01';
| form | plan |
|---|---|
| slow | function on column → scan |
| fast | bare column range → seek |
Both ask for 2024 hires. The range seeks the hired index to January then scans forward; the function evaluates YEAR per row across the whole table.
YEAR() → range (same logic, seek)
Identical answers, different plans.
1-- slow: WHERE YEAR(hired) = 2024 (scan)2-- fast: WHERE hired >= DATE '2024-01-01' AND hired < DATE '2025-01-01' (seek)
| form | plan |
|---|---|
| slow | per-row function → scan |
| fast | bare range → seek |
LIKE prefix vs leading-%
Left-anchored serves B-trees; leading-% needs trigrams.
1-- fast: WHERE name LIKE 'A%' (prefix seek)2-- slow: WHERE name LIKE '%son' (scan; use trigram/full-text)
| pattern | plan |
|---|---|
| A% | prefix seek |
| %son | scan without trigram |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.