A query against a ten-million row audit or ledger table suddenly crawls, spiking database CPU to 100 percent. You check your composite index on (tenant_id, created_at, status), verify the columns are there, and wonder why the optimizer chose a sequential table scan or burned through 400,000 buffer reads anyway.

The Broken Execution Plan

Here is the offending pattern. You need all pending records for a specific tenant created on a given date:

sql
SELECT id, payload, created_at, status
FROM audit_events
WHERE tenant_id = 42
  AND DATE(created_at) = '2025-02-15'
  AND status = 'PENDING';

The table has an index covering these columns:

sql
CREATE INDEX idx_audit_events_lookup 
ON audit_events (tenant_id, created_at, status);

When you inspect the plan in PostgreSQL with EXPLAIN (ANALYZE, BUFFERS) or in SQL Server with SET STATISTICS IO ON, the index is either ignored completely or used as a loose range scan that reads far more disk pages than necessary.

text
Bitmap Heap Scan on audit_events  (cost=1240.50..84920.10 rows=450 width=84) (actual time=18.412..412.301 rows=12 loops=1)
  Recheck Cond: (tenant_id = 42)
  Filter: ((status = 'PENDING'::text) AND (date(created_at) = '2025-02-15'::date))
  Rows Removed by Filter: 320140
  Buffers: shared hit=4210 read=18920
  ->  Bitmap Index Scan on idx_audit_events_lookup  (cost=0.00..1240.39 rows=62000 width=0) (actual time=14.210..14.210 rows=320152 loops=1)
        Index Cond: (tenant_id = 42)
Planning Time: 0.184 ms
Execution Time: 412.385 ms

The database hit the index solely for tenant_id = 42. It pulled 320,152 index entries off the disk, hopped out to the heap pages to read each row, and then threw away 320,140 rows using runtime filters.

Non-SARGable Predicates and B-Trees

A query predicate is SARGable (Search Argument Able) when the database engine can use the B-tree structure to jump directly to the first matching leaf node and walk sequentially until the condition terminates.

Wrapping a column in a function like DATE(created_at) breaks SARGability. The B-tree stores raw timestamptz values. It does not store the output of the DATE() scalar function. Because the function converts dynamic values at row evaluation time, the optimizer cannot compute a deterministic search boundary. The B-tree index stops being a search tree at that column and degrades into an unindexed filter.

The second issue is composite index column ordering. In a multi-column B-tree, keys are sorted strictly from left to right: first by column 1, then by column 2 within ties of column 1, and so on. If column 1 is an equality match, column 2 can be searched as a range. But once an index column encounters an open range or a non-SARGable function, the engine cannot use subsequent columns in the index for direct traversal.

In idx_audit_events_lookup (tenant_id, created_at, status), matching status = 'PENDING' requires the index to jump through different slices of created_at. If created_at is evaluated as an open date range or crippled by a function, the engine cannot seek on status. It has to scan all rows for that tenant_id within that date range.

Writing SARGable Range Queries

Never pass indexed columns into transformation functions in your WHERE clause. Transform the literal comparison value on the right side instead.

Rewrite the date comparison using an explicit, half-open range [start, end):

sql
SELECT id, payload, created_at, status
FROM audit_events
WHERE tenant_id = 42
  AND created_at >= '2025-02-15 00:00:00Z'
  AND created_at < '2025-02-16 00:00:00Z'
  AND status = 'PENDING';

This makes created_at SARGable. The engine can now execute a binary search on the created_at boundary. But the composite index column order is still suboptimal.

Fixing Composite Index Column Order

Rule of thumb for composite indexes: Equality columns first, then Range columns, then Projection/Include columns (Equality, Equality, …, Range).

In your application, queries filter by exact tenant_id and exact status, but select a window across created_at. If created_at sits between tenant_id and status, the range scan on created_at prevents the B-tree from seeking down to status = 'PENDING'.

Drop the old index and define it with equality columns preceding range columns:

sql
DROP INDEX idx_audit_events_lookup;

CREATE INDEX idx_audit_events_tenant_status_created 
ON audit_events (tenant_id, status, created_at);

If you frequently fetch payload or id and want to avoid heap fetches entirely, consider index-only scans by covering those columns with an INCLUDE clause:

sql
CREATE INDEX idx_audit_events_covering
ON audit_events (tenant_id, status, created_at)
INCLUDE (payload);

Verifying the Execution Plan

Run the updated query with EXPLAIN (ANALYZE, BUFFERS):

sql
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, payload, created_at, status
FROM audit_events
WHERE tenant_id = 42
  AND status = 'PENDING'
  AND created_at >= '2025-02-15 00:00:00Z'
  AND created_at < '2025-02-16 00:00:00Z';

Inspect the output:

text
Index Scan using idx_audit_events_tenant_status_created on audit_events  (cost=0.43..8.45 rows=12 width=84) (actual time=0.038..0.046 rows=12 loops=1)
  Index Cond: ((tenant_id = 42) AND (status = 'PENDING'::text) AND (created_at >= '2025-02-15 00:00:00+00'::timestamp with time zone) AND (created_at < '2025-02-16 00:00:00+00'::timestamp with time zone))
  Buffers: shared hit=4
Planning Time: 0.122 ms
Execution Time: 0.063 ms

The difference is clear. Instead of 23,130 buffer reads and 412 milliseconds, the database completes the operation with 4 buffer hits in 0.063 milliseconds. All three predicates appear directly under Index Cond, confirming a pure index seek with zero heap filtering.

Real-World Edge Cases

Implicit Type Coercion Disabling Seeks

One of the quietest ways to kill SARGability occurs without any explicit function call. If your data types mismatch between the application parameter and the database schema, the database will add an implicit cast function around the table column.

Suppose account_number in a customer table is a VARCHAR(32):

sql
-- Application sends an unquoted integer literal or untyped parameter
SELECT id, balance 
FROM accounts 
WHERE account_number = 10048291;

In engines like SQL Server and Oracle, data type precedence dictacts that strings convert to integers, not integers to strings. The engine secretly rewrites your query to:

sql
SELECT id, balance 
FROM accounts 
WHERE CAST(account_number AS INT) = 10048291;

An index on account_number is instantly invalidated. The plan falls back to an index scan or table scan over millions of rows. Keep your parameter types aligned with column definitions in code:

sql
-- Fix: enforce the string type at the application or query layer
SELECT id, balance 
FROM accounts 
WHERE account_number = '10048291';

Leading Wildcards in Pattern Matching

Text searches using LIKE can be SARGable, but only if the match anchor starts at the beginning of the string:

sql
-- SARGable: acts as a range scan (starts with 'ORD-99' and stops before 'ORD-9:')
SELECT id FROM orders WHERE order_code LIKE 'ORD-99%';

-- Non-SARGable: forces full index or table scan
SELECT id FROM orders WHERE order_code LIKE '%9981';

If you must match suffixes or substrings without full-text search infrastructure, you have two options depending on your database engine.

For pure suffix searches ('%something'), create a generated column that stores the reversed string and index that column:

sql
ALTER TABLE orders 
ADD COLUMN order_code_reversed VARCHAR(64) 
GENERATED ALWAYS AS (REVERSE(order_code)) STORED;

CREATE INDEX idx_orders_code_rev ON orders (order_code_reversed);

-- Query using the reversed prefix
SELECT id FROM orders 
WHERE order_code_reversed LIKE REVERSE('%9981');
-- Which parses to: LIKE '1899%'

For arbitrary substring queries ('%value%') in PostgreSQL, drop standard B-trees entirely and build a trigram index with the pg_trgm extension:

sql
CREATE EXTENSION IF NOT EXISTS pg_trgm;

CREATE INDEX idx_orders_code_trgm 
ON orders USING gin (order_code gin_trgm_ops);

-- This now executes an indexed bitmap search
SELECT id FROM orders WHERE order_code LIKE '%9981%';

More in SQL