Sub topic 15
Casts and Index Usage
This chapter assumes you can read EXPLAIN output and know what a B-tree index is. It also assumes you are comfortable with CAST, :: and the implicit, assignment and explicit cast contexts from earlier chapters. The goal is to find casts that stop PostgreSQL from using an index, and to fix them.
Why a cast can hide an index
A B-tree index on created_at stores the values of that column, sorted. The planner can use it only when a condition has the form indexed_expression operator constant, and the operator belongs to the operator family of the index.
If you wrap the column in a cast, the left side becomes created_at::date, which is a different expression from created_at. The index has no entries for it. The planner then reads the whole table and evaluates the cast on every row.
CREATE TABLE events (
id bigserial PRIMARY KEY,
created_at timestamp NOT NULL,
payload text
);
INSERT INTO events (created_at, payload)
SELECT TIMESTAMP '2026-01-01' + n * interval '10 minutes', 'e' || n
FROM generate_series(1, 50000) AS n;
CREATE INDEX events_created_at_idx ON events (created_at);
ANALYZE events;
EXPLAIN SELECT * FROM events
WHERE created_at::date = DATE '2026-11-27';
EXPLAIN SELECT * FROM events
WHERE created_at >= TIMESTAMP '2026-11-27'
AND created_at < TIMESTAMP '2026-11-28';The first plan shows a Seq Scan with a Filter that contains (created_at)::date. The second normally shows an Index Scan or Bitmap Index Scan on events_created_at_idx. The exact plan depends on table size and statistics, but the cast form cannot use that index at all.
Cast the constant, not the column
The general rule is to leave the indexed column bare and convert the other side of the comparison. PostgreSQL evaluates constant expressions once during planning, so a cast on a literal or parameter costs nothing per row.
The same rule applies when a cast is implied by the types involved. If the operator chosen by type resolution needs the column converted, the column is cast even though you wrote no cast.
CREATE TABLE accounts (
id integer PRIMARY KEY,
code text
);
CREATE INDEX accounts_code_idx ON accounts (code);
-- Column is cast to numeric; the primary key index cannot be used:
EXPLAIN SELECT * FROM accounts WHERE id = 42::numeric;
-- Constant becomes integer; the index can be used:
EXPLAIN SELECT * FROM accounts WHERE id = 42;
-- Column is cast to integer; accounts_code_idx cannot be used:
EXPLAIN SELECT * FROM accounts WHERE code::integer = 42;
-- Compare as text instead:
EXPLAIN SELECT * FROM accounts WHERE code = '42';In id = 42::numeric, no integer = numeric operator exists. Resolution picks numeric = numeric and converts the column. This usually happens when an application sends decimal parameters for an integer key.
In code = 42 on a text column, you get operator does not exist: text = integer. Do not fix that by casting the column. Write the constant as text.
Cross-type operators are not casts
Some mixed-type comparisons keep the index usable even though the types differ. The B-tree operator families include cross-type operators for related types. The integer_ops family has integer = bigint, and the datetime_ops family has timestamp = timestamptz and date = timestamp. For these, the planner does not convert the column. It compares the column value directly with the other type.
Binary-coercible casts, such as varchar to text, convert nothing at run time. The planner treats them as a relabeling, so an index on a varchar column still works when you compare it to text.
| Condition | Index on the column usable? | Better form |
|---|---|---|
| `created_at::date = DATE '2026-11-27'` | No | Half-open range on `created_at` |
| `int_col = 42::numeric` | No, the column is cast | `int_col = 42` |
| `int_col = 42::bigint` | Yes, cross-type operator | Fine as written |
| `varchar_col = 'x'::text` | Yes, binary-coercible | Fine as written |
| `text_col::integer = 42` | No | `text_col = '42'` |
| `lower(email) = '[email protected]'` | No, unless an expression index exists | `CREATE INDEX ON users (lower(email))` |
Deciding what to do
Range rewrites for dates and times
Filtering on a day is the most common case. Use a half-open range, with >= the start and < the start of the next day, so that no row is missed or counted twice.
SELECT count(*) FROM events
WHERE created_at >= DATE '2026-11-27'
AND created_at < DATE '2026-11-27' + 1;Here the date constants are compared with a timestamp column. This uses a cross-type operator, so the index still applies. Avoid BETWEEN with '2026-11-27 23:59:59'. It misses fractional seconds.
Expression indexes
Sometimes you cannot rewrite the query, for example when a reporting tool always generates created_at::date. In that case, index the expression itself.
CREATE INDEX events_created_date_idx ON events ((created_at::date));
ANALYZE events;
EXPLAIN SELECT * FROM events
WHERE created_at::date = DATE '2026-11-27';The planner matches the query expression to the index expression after parsing. created_at::date and CAST(created_at AS date) are the same expression. date(created_at) is a different syntax for the same cast and also matches. A different expression, such as date_trunc('day', created_at), does not match.
Expression indexes have a cost. Every insert and update computes the expression. Each one adds an index to maintain. The index helps only the queries that use that exact expression.
The immutability requirement
An index expression must be IMMUTABLE, meaning its result depends only on its arguments. The cast from timestamp to date meets this requirement. The cast from timestamptz to date does not, because the result depends on the session TimeZone setting.
CREATE TABLE audit (at timestamptz NOT NULL);
-- Fails: functions in index expression must be marked IMMUTABLE
CREATE INDEX audit_day_bad ON audit ((at::date));
-- Works: the time zone is fixed in the expression
CREATE INDEX audit_day_utc ON audit (((at AT TIME ZONE 'UTC')::date));Queries must then use the same expression, (at AT TIME ZONE 'UTC')::date = DATE '2026-11-27'. For timestamptz columns, the range rewrite is usually simpler. It also uses the session time zone consistently.
Checking your work
Verify with EXPLAIN, not by reading the query. Check these points:
- On a small table, the planner may choose a sequential scan even when an index is usable. Test with realistic data volumes, or run
SET enable_seqscan = off;in a test session only to see whether an index plan is possible. - Look at the
FilterandIndex Condlines. A cast such as(created_at)::datein aFilterline shows that the column was converted per row. - Run
ANALYZEafter loading data. Without statistics, plan choices can mislead you. - Test with the parameter types your application driver sends. The same SQL text can plan differently when a driver binds a
numericwhere you expected aninteger.
Exercise
A table orders has an index on order_no integer. An application sends the query SELECT * FROM orders WHERE order_no = $1 and the driver binds the parameter as numeric. EXPLAIN shows a sequential scan with Filter: ((order_no)::numeric = '42'::numeric). Why is the index not used, and what are two ways to fix it?
Show answer
No integer = numeric operator exists, so type resolution picks numeric = numeric and casts the column order_no on every row. The index is on order_no itself, not on order_no::numeric. Fix it by making the parameter an integer, either by changing the driver binding or by writing WHERE order_no = $1::integer. Alternatively, create an expression index on ((order_no::numeric)), which is a worse choice because it adds index maintenance for a problem that the query can avoid.
Exercise
You need all events rows from a single day, and created_at is timestamptz. Why does CREATE INDEX ON events ((created_at::date)) fail, and what query form avoids needing that index?
Show answer
The timestamptz to date cast depends on the session TimeZone, so it is stable but not immutable, and index expressions must be immutable. Use a half-open range on the bare column instead: created_at >= TIMESTAMPTZ '2026-11-27 00:00:00+00' AND created_at < TIMESTAMPTZ '2026-11-28 00:00:00+00', which can use an ordinary index on created_at.