Video in progress

What is a partial index and when is it better than a regular one?

A partial index stores only the rows that match its WHERE condition. If queries always hit a small part of the table (say, only active or unprocessed records), the index is much smaller and faster.

📖 Answer

Example: the task table has 50 million rows, and 2,000 of them have status = 'PENDING'. The worker always looks for exactly those.

CREATE INDEX idx_task_pending
    ON task (created_at)
    WHERE status = 'PENDING';

This index has only 2,000 entries. It fits in memory, and updating rows that are already DONE doesn't touch it at all, so writes get cheaper too.

The planner uses a partial index only if the query condition logically implies the index condition:

SELECT * FROM task WHERE status = 'PENDING' ORDER BY created_at LIMIT 100; -- works
SELECT * FROM task WHERE status = ? ...                                   -- with a parameter, it may not work in a generic plan

The second case does happen in practice: JPA binds the parameter, and in a generic plan the planner doesn't know the value. For a query like that, writing the condition as a literal is more reliable.

Another useful application is a conditional unique:

-- only one active subscription per user
CREATE UNIQUE INDEX uq_active_subscription
    ON subscription (user_id) WHERE active;

-- unique email with soft delete
CREATE UNIQUE INDEX uq_user_email ON users (email) WHERE deleted_at IS NULL;