Sub topic 15
Casts and Index Usage
Assume you know SELECT, WHERE, CREATE TABLE, and basic PostgreSQL data types. This chapter focuses on how casts affect a B-tree index, the usual index type for equality and range searches.
An index stores values in an order that PostgreSQL can search efficiently. A predicate is index-friendly when PostgreSQL can compare the indexed column directly with a compatible value or range. Casting the column inside the predicate can hide that ordering from the planner.
The problem with casting an indexed column
Suppose an events table stores timestamps and has an index on created_at:
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY,
created_at timestamptz NOT NULL,
payload jsonb
);
CREATE INDEX events_created_at_idx
ON events (created_at);This query casts every created_at value to a date before comparing it:
SELECT *
FROM events
WHERE created_at::date = DATE '2026-11-27';The plain B-tree index stores timestamptz values, not their converted date values. PostgreSQL may need to calculate created_at::date for many rows and then filter them. On a large table, this can result in a sequential scan.
Rewrite the condition as a half-open range:
SELECT *
FROM events
WHERE created_at >= TIMESTAMPTZ '2026-11-27 00:00:00+00'
AND created_at < TIMESTAMPTZ '2026-11-28 00:00:00+00';The column remains bare. PostgreSQL can use the index to find values from the start of the day up to, but not including, the next day.
Check the planner
Use EXPLAIN to inspect the chosen plan:
EXPLAIN
SELECT *
FROM events
WHERE created_at >= TIMESTAMPTZ '2026-11-27 00:00:00+00'
AND created_at < TIMESTAMPTZ '2026-11-28 00:00:00+00';Look for an Index Scan or Bitmap Index Scan. A sequential scan is not automatically wrong. If the table is small or most rows match, reading the whole table may be cheaper.
A range is also safer than BETWEEN for time periods. BETWEEN includes both endpoints, which can overlap adjacent periods. The >= and < form gives each timestamp one unambiguous interval.
When an expression index is appropriate
Sometimes the cast or expression is the required search rule. You can index that expression instead:
CREATE INDEX events_created_date_idx
ON events ((created_at::date));Then the original predicate may use the expression index:
SELECT *
FROM events
WHERE created_at::date = DATE '2026-11-27';Expression indexes add storage and maintenance cost. Use one when the expression appears frequently and rewriting the predicate as a range is unsuitable.
Exercise
Rewrite WHERE created_at::date = DATE '2026-11-27' so a plain index on created_at can be used.
Show answer
Use WHERE created_at >= TIMESTAMPTZ '2026-11-27 00:00:00+00' AND created_at < TIMESTAMPTZ '2026-11-28 00:00:00+00'.