Careeroza
Sargable Queries
What Does Sargable Mean?
A condition is sargable (Search ARGument ABLE) when the database can use an index to evaluate it. Wrapping the indexed column in a function or calculation usually makes it non-sargable.
| Non-sargable (scans) | Sargable (uses index) |
|---|---|
WHERE YEAR(OrderDate) = 2024 | WHERE OrderDate >= '2024-01-01' AND OrderDate < '2025-01-01' |
WHERE Price * 1.18 > 100 | WHERE Price > 100 / 1.18 |
WHERE UPPER(Email) = '[email protected]' | WHERE Email = '[email protected]' (or an index on UPPER(Email)) |
WHERE Name LIKE '%son' | WHERE Name LIKE 'Jo%' |
WHERE CAST(CustomerID AS TEXT) = '4' | WHERE CustomerID = 4 |
See It in the Plan
Function on the column: SCAN
Wrapping OrderDate in strftime() hides it from the index:
CREATE INDEX idx_orders_date ON Orders (OrderDate);
EXPLAIN QUERY PLAN
SELECT * FROM Orders WHERE strftime('%Y', OrderDate) = '2024';Result: 1 row
| id | parent | notused | detail |
|---|---|---|---|
| 2 | 0 | 216 | SCAN Orders |
Range on the column: SEARCH
The same filter written as a date range can use the index:
CREATE INDEX idx_orders_date ON Orders (OrderDate);
EXPLAIN QUERY PLAN
SELECT * FROM Orders WHERE OrderDate >= '2024-01-01' AND OrderDate < '2025-01-01';Result: 1 row
| id | parent | notused | detail |
|---|---|---|---|
| 3 | 0 | 164 | SEARCH Orders USING INDEX idx_orders_date (OrderDate>? AND OrderDate<?) |