Browse topics

Partial and expression indexes

Version
19
Review
Draft

Summary#

An expression index stores the result of an expression. A partial index covers only rows that match its predicate. A unique index can combine both to enforce a rule on a subset of rows.

Syntax#

sql
CREATE UNIQUE INDEX index_name
ON table_name (lower(column_name))
WHERE predicate;

INSERT INTO table_name VALUES (value_list)
ON CONFLICT (lower(column_name)) WHERE predicate DO NOTHING;

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind. EXPLAIN (COSTS OFF) shows the chosen plan without estimates that vary. Plans depend on data and settings.

sql
BEGIN;
SET LOCAL default_statistics_target = 1000;

CREATE TEMPORARY TABLE users (
    user_id    integer PRIMARY KEY,
    email      text NOT NULL,
    deleted_on date
);

INSERT INTO users
SELECT n,
       'User' || n || '@example.com',
       CASE WHEN n % 10 = 0 THEN date '2026-01-01' END
FROM generate_series(1, 20000) AS g(n);

-- Unique, ignoring letter case, among rows that are not deleted.
CREATE UNIQUE INDEX users_live_email_idx
    ON users (lower(email))
    WHERE deleted_on IS NULL;
ANALYZE users;

-- The query repeats both the expression and the predicate.
EXPLAIN (COSTS OFF)
SELECT user_id FROM users
WHERE lower(email) = 'user7@example.com' AND deleted_on IS NULL;

-- Without the predicate, the partial index cannot answer the query.
EXPLAIN (COSTS OFF)
SELECT user_id FROM users
WHERE lower(email) = 'user7@example.com';

-- A live duplicate is skipped.
INSERT INTO users VALUES (20001, 'USER7@example.com', NULL)
ON CONFLICT (lower(email)) WHERE deleted_on IS NULL DO NOTHING
RETURNING user_id;

-- The address of a deleted user can be used again.
INSERT INTO users VALUES (20002, 'user10@EXAMPLE.com', NULL)
ON CONFLICT (lower(email)) WHERE deleted_on IS NULL DO NOTHING
RETURNING user_id;

ROLLBACK;

Expected output#

Text
QUERY PLAN
Index Scan using users_live_email_idx on users
  Index Cond: (lower(email) = 'user7@example.com'::text)
(2 rows)
QUERY PLAN
Seq Scan on users
  Filter: (lower(email) = 'user7@example.com'::text)
(2 rows)
user_id
(0 rows)
user_id
20002
(1 row)

Common mistakes#

Repeat deleted_on IS NULL in the query so the planner can prove it only needs live rows. Use lower(email) to look up an index key. For ON CONFLICT inference, specify the indexed expression and a predicate that implies the index predicate. A non-partial unique index on the same expression can also qualify.

Version applicability#

These index forms work in PostgreSQL 19. The ON CONFLICT statements require PostgreSQL 9.5 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0