// troubleshooting guide

Non-sargable predicates

The column is indexed, but the filter wraps it in a function, a calculation or a leading wildcard, so the index cannot be searched. How each engine's plan shows that, how to rewrite the filter as a range, and when to index the expression instead.

Covers PostgreSQL MySQL SQL Server Oracle SQLite

The symptom

An index is sorted by the values of its columns. The engine can search it for order_date >= '2024-03-01' because it knows where that value sits in the order. It cannot search it for date(order_date) = '2024-03-01', because the index is not sorted by the result of the function. It has to compute the function for every row and compare afterwards. A filter the index can search is called sargable; one it cannot is non-sargable.

In the plan the condition moves from the place where the index is searched to the place where rows are filtered: Filter 代わりに Index Cond in PostgreSQL, Predicate 代わりに Seek Predicate in SQL Server, filter 代わりに access in Oracle, a full scan in MySQL and SQLite. The query plan viewer points at the predicate. The examples use a shop schema with 400,000 orders, 480 per day, and an index on the order date.

Diagnose it

A function around the column

All five examples ask for the orders of one day by converting the timestamp to a date.

CREATE INDEX orders_date_idx ON orders (order_date);

EXPLAIN (ANALYZE, BUFFERS)
SELECT order_id, total FROM orders WHERE order_date::date = DATE '2024-03-01';
->  Parallel Seq Scan on orders  (cost=0.00..6982.00 rows=833 width=10) (actual time=1.270..6.103 rows=160.00 loops=3)
      Filter: ((order_date)::date = '2024-03-01'::date)
      Rows Removed by Filter: 133173
CREATE INDEX orders_date_idx ON orders (order_date);

EXPLAIN FORMAT=TREE
SELECT order_id, total FROM orders WHERE DATE(order_date) = '2024-03-01';
-> Filter: (cast(orders.order_date as date) = '2024-03-01')  (cost=40184 rows=398228)
    -> Table scan on orders  (cost=40184 rows=398228)
CREATE INDEX IX_Orders_OrderDate ON dbo.Orders (OrderDate) INCLUDE (Total);
GO
SET STATISTICS IO ON;
SET STATISTICS XML ON;
GO
SELECT OrderId, Total FROM dbo.Orders WHERE CONVERT(char(10), OrderDate, 120) = '2024-03-01';
Table 'Orders'. Scan count 1, logical reads 1250, physical reads 0

The SQL Server plan is an Index Scan: it reads all 400,000 entries of the index and tests the expression, which appears under Predicate, on each one.

CREATE INDEX orders_date_idx ON orders (order_date);

EXPLAIN PLAN FOR
SELECT order_id, total FROM orders WHERE TRUNC(order_date) = DATE '2024-03-01';

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id  | Operation         | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT  |        |  4000 | 72000 |   655   (2)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| ORDERS |  4000 | 72000 |   655   (2)| 00:00:01 |
CREATE INDEX orders_date_idx ON orders (order_date);

EXPLAIN QUERY PLAN
SELECT order_id, total FROM orders WHERE date(order_date) = '2024-03-01';
`--SCAN orders

A calculation on the column

Arithmetic has the same effect as a function. The engine does not solve the equation for you:

CREATE INDEX orders_total_idx ON orders (total);

EXPLAIN SELECT order_id FROM orders WHERE total * 2 > 1998;

EXPLAIN SELECT order_id FROM orders WHERE total > 999;
Seq Scan on orders  (cost=0.00..10482.00 rows=133333 width=4)
  Filter: ((total * '2'::numeric) > '1998'::numeric)
Index Scan using orders_total_idx on orders  (cost=0.42..8.44 rows=1 width=4)
  Index Cond: (total > '999'::numeric)

A pattern that starts with a wildcard

LIKE 'R4242%' is a range in the index: everything from R4242 up to R4243. LIKE '%4242' has no starting point, so every value is tested.

CREATE INDEX orders_reference_idx ON orders (reference);

EXPLAIN SELECT order_id FROM orders WHERE reference LIKE 'R4242%'\G

EXPLAIN SELECT order_id FROM orders WHERE reference LIKE '%4242'\G
 type: range
  key: orders_reference_idx
 rows: 11
Extra: Using where; Using index
 type: index
  key: orders_reference_idx
 rows: 398228
Extra: Using where; Using index
CREATE INDEX IX_Orders_Reference ON dbo.Orders (Reference);
GO
SELECT OrderId FROM dbo.Orders WHERE Reference LIKE 'R4242%';
SELECT OrderId FROM dbo.Orders WHERE Reference LIKE '%4242';
Table 'Orders'. Scan count 1, logical reads 3, physical reads 0
Table 'Orders'. Scan count 1, logical reads 1039, physical reads 0

The first query is an Index Seek that reads 3 pages, the second an Index Scan of the same index that reads all of it.

In PostgreSQL an ordinary index serves a prefix pattern only when the column uses the C collation. With any other collation, declare the index with text_pattern_ops (varchar_pattern_ops 次の varchar column):

CREATE INDEX orders_reference_idx ON orders (reference);
EXPLAIN SELECT order_id FROM orders WHERE reference LIKE 'R4242%';

CREATE INDEX orders_reference_pattern_idx ON orders (reference varchar_pattern_ops);
EXPLAIN SELECT order_id FROM orders WHERE reference LIKE 'R4242%';
  ->  Parallel Seq Scan on orders  (cost=0.00..6565.33 rows=17 width=4)
        Filter: ((reference)::text ~~ 'R4242%'::text)
Index Scan using orders_reference_pattern_idx on orders  (cost=0.42..8.44 rows=40 width=4)
  Index Cond: (((reference)::text ~>=~ 'R4242'::text) AND ((reference)::text ~<~ 'R4243'::text))
  Filter: ((reference)::text ~~ 'R4242%'::text)

Fix it

Rewrite the filter as a range on the bare column

Leave the column alone and move the work to the other side of the comparison. One day is everything from midnight up to, but not including, the next midnight:

EXPLAIN (ANALYZE, BUFFERS)
SELECT order_id, total FROM orders
WHERE order_date >= '2024-03-01' AND order_date < '2024-03-02';
Index Scan using orders_date_idx on orders  (cost=0.42..1269.04 rows=469 width=10) (actual time=0.017..0.074 rows=480.00 loops=1)
  Index Cond: ((order_date >= '2024-03-01 00:00:00'::timestamp without time zone) AND (order_date < '2024-03-02 00:00:00'::timestamp without time zone))
  Buffers: shared hit=322 read=4
EXPLAIN FORMAT=TREE
SELECT order_id, total FROM orders
WHERE order_date >= '2024-03-01' AND order_date < '2024-03-02';
-> Index range scan on orders using orders_date_idx over ('2024-03-01 00:00:00' <= order_date < '2024-03-02 00:00:00'), with index condition: ((orders.order_date >= TIMESTAMP'2024-03-01 00:00:00') and (orders.order_date < TIMESTAMP'2024-03-02 00:00:00'))  (cost=216 rows=480)
SELECT OrderId, Total FROM dbo.Orders
WHERE OrderDate >= '2024-03-01' AND OrderDate < '2024-03-02';
Table 'Orders'. Scan count 1, logical reads 5, physical reads 0
EXPLAIN PLAN FOR
SELECT order_id, total FROM orders
WHERE order_date >= DATE '2024-03-01' AND order_date < DATE '2024-03-02';

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id  | Operation                           | Name            | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT                    |                 |   481 |  8658 |     7   (0)| 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS          |   481 |  8658 |     7   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN                  | ORDERS_DATE_IDX |   481 |       |     4   (0)| 00:00:01 |
EXPLAIN QUERY PLAN
SELECT order_id, total FROM orders
WHERE order_date >= '2024-03-01' AND order_date < '2024-03-02';
`--SEARCH orders USING INDEX orders_date_idx (order_date>? AND order_date<?)

Use a half-open range (>= そして <), not BETWEEN を伴う 23:59:59, which misses rows in the last second on columns with fractional seconds. The timestamp range filter page has the pattern for every engine, and sargable date parts covers year and month filters.

SQL Server: a cast to date is the exception

SQL Server can seek an index through CAST(column AS date) on a date-and-time column. It converts the cast into a range itself:

SELECT OrderId, Total FROM dbo.Orders WHERE CAST(OrderDate AS date) = '2024-03-01';
Table 'Orders'. Scan count 1, logical reads 7, physical reads 0

Do not rely on it for other functions. YEAR(), CONVERT to a string, DATEADD または DATEDIFF around the column all scan.

Index the expression when you cannot change the query

If the query comes from a tool or an ORM, build an index on the expression. The query text must use the same expression as the index.

CREATE INDEX orders_date_day_idx ON orders ((order_date::date));
ANALYZE orders;

EXPLAIN SELECT order_id, total FROM orders WHERE order_date::date = DATE '2024-03-01';
Index Scan using orders_date_day_idx on orders  (cost=0.42..1290.96 rows=476 width=10)
  Index Cond: ((order_date)::date = '2024-03-01'::date)
CREATE INDEX orders_date_day_idx ON orders ((DATE(order_date)));

EXPLAIN FORMAT=TREE
SELECT order_id, total FROM orders WHERE DATE(order_date) = '2024-03-01';
-> Index lookup on orders using orders_date_day_idx (cast(order_date as date)='2024-03-01')  (cost=168 rows=480)
CREATE INDEX orders_date_day_idx ON orders (TRUNC(order_date));

EXPLAIN PLAN FOR
SELECT order_id, total FROM orders WHERE TRUNC(order_date) = DATE '2024-03-01';

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);
| Id  | Operation                           | Name                | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT                    |                     |   480 |  9120 |     8   (0)| 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS              |   480 |  9120 |     8   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN                  | ORDERS_DATE_DAY_IDX |   480 |       |     4   (0)| 00:00:01 |
CREATE INDEX orders_date_day_idx ON orders (date(order_date));

EXPLAIN QUERY PLAN
SELECT order_id, total FROM orders WHERE date(order_date) = '2024-03-01';
`--SEARCH orders USING INDEX orders_date_day_idx (<expr>=?)

SQL Server has no expression indexes. Add a computed column and index that; the optimizer matches the expression in the query to the computed column:

ALTER TABLE dbo.Orders ADD OrderDay AS CONVERT(char(10), OrderDate, 120);
GO
CREATE INDEX IX_Orders_OrderDay ON dbo.Orders (OrderDay) INCLUDE (Total);
GO
SELECT OrderId, Total FROM dbo.Orders WHERE CONVERT(char(10), OrderDate, 120) = '2024-03-01';
Table 'Orders'. Scan count 1, logical reads 6, physical reads 0

その expression index page lists the syntax and limits per engine.

PostgreSQL: a trigram index for patterns that start with a wildcard

No rewrite turns LIKE '%4242' into a range. PostgreSQL's pg_trgm extension indexes every three-character fragment of the text, which lets it search for a pattern anywhere in the value:

CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX orders_reference_trgm_idx ON orders USING gin (reference gin_trgm_ops);

EXPLAIN (ANALYZE)
SELECT order_id FROM orders WHERE reference LIKE '%4242';
Bitmap Heap Scan on orders  (cost=34.51..183.67 rows=40 width=4) (actual time=0.068..0.108 rows=40.00 loops=1)
  Recheck Cond: ((reference)::text ~~ '%4242'::text)
  Rows Removed by Index Recheck: 1
  Heap Blocks: exact=41
  ->  Bitmap Index Scan on orders_reference_trgm_idx  (cost=0.00..34.50 rows=40 width=0) (actual time=0.060..0.060 rows=41.00 loops=1)
        Index Cond: ((reference)::text ~~ '%4242'::text)

On the other engines, a search inside a string needs a full-text index or a different design, such as storing the part you search for in its own column.

When to leave it alone

Leave it when the table is small, when another condition in the same query already narrows the rows through an index, or when the predicate keeps most of the table anyway. A function on the constant side of the comparison is never a problem: order_date >= CURRENT_DATE - 7 is computed once, not per row.

The checklist

Work through it in order. Each step gives you the evidence for the next one.

  1. Find the condition in the plan: is it searched (Index Cond, Seek Predicate, access) or filtered (Filter, Predicate, filter)?
  2. Look for a function, cast, calculation or leading wildcard around the column.
  3. Rewrite it as a comparison or half-open range on the bare column.
  4. If the query cannot change, index the expression (computed column on SQL Server).
  5. For patterns starting with %, use a trigram index in PostgreSQL or a full-text index.
  6. Re-capture the plan and confirm the condition is now part of the index search.

Questions that come up

What does sargable mean?

It is short for search argument able: a condition the engine can answer by searching an index instead of testing every row. column = value, column > value and column LIKE 'prefix%' are sargable. A function or calculation around the column usually is not.

Does a function on the value side hurt?

No. order_date >= CURRENT_DATE - 7 applies the function to a constant, which is computed once before the index is searched. Only an expression around the column forces the engine to evaluate it for every row.

Is BETWEEN sargable?

Yes. BETWEEN on a bare column is a range the index can search. For timestamps a half-open range with >= and < is safer, because BETWEEN includes the upper bound and an end value like 23:59:59 misses fractional seconds.

Why does LIKE 'abc%' not use my index in PostgreSQL?

A default btree index supports prefix patterns only under the C collation. For other collations create the index with text_pattern_ops or varchar_pattern_ops, which sorts the values in a way that matches LIKE.

Is WHERE CAST(col AS date) = ... always a scan?

On most engines it is unless you index the expression. SQL Server is the exception for a cast from a date-and-time type to date: it rewrites the cast into a range and seeks the index.

// fix it where the query lives

Run these queries in SQLly

SQLly is a native SQL workbench for macOS, Windows and Linux. The query plan viewer and formatter these guides link to are built into its editor.