What a partial index is, the queries it speeds up, how partial unique indexes enforce rules like one active subscription per customer, and why prepared statements sometimes ignore them.

A partial index is a Postgres index with a WHERE clause, so it covers only the rows you query, such as the few thousand pending jobs in a table of forty million finished ones.
It is one of the cheapest performance fixes available on a large table, and its unique variant enforces business rules that a plain unique constraint cannot express.
The partial index documentation describes the main case as a column with a skewed distribution, where queries only look at the rare values. Three shapes cover most backends:
WHERE status = 'pending' on a jobs or outbox table, where finished rows are the vast majority and never queried by status again.WHERE deleted_at IS NULL on tables where deleted rows are kept for audit but excluded from every read.WHERE external_id IS NOT NULL when only some rows have the value and lookups always filter on it.CREATE INDEX jobs_pending_run_at_idx
ON jobs (run_at)
WHERE status = 'pending';
-- Uses the index: the WHERE clause matches the predicate exactly.
SELECT id FROM jobs
WHERE status = 'pending' AND run_at <= now()
ORDER BY run_at
LIMIT 50;
Indexing run_at instead of status is deliberate, since every row in the index already has the status, and the index can then serve the ORDER BY run_at as well.
A plain unique constraint on (customer_id) would allow only one subscription per customer ever. A partial unique index enforces "one active subscription per customer" while keeping the full history of cancelled ones:
CREATE UNIQUE INDEX subscriptions_one_active_idx
ON subscriptions (customer_id)
WHERE status = 'active';
The database rejects the second active row even when two requests race, which an application-level "check, then insert" cannot guarantee. The same shape works for one default address per user, one primary email per account or one open shift per driver.
The planner uses a partial index only when it can show that the query's WHERE clause implies the index predicate, and the docs are explicit that this matching happens at planning time and that parameterized clauses do not work with a partial index. Two consequences catch people out:
WHERE status = $1 cannot prove status = 'pending' for every possible value, so a generic plan for a prepared statement skips the index. Write the predicate value as a literal in the query, and keep only the values that vary as parameters.x < 1 implies x < 2, but it will not rewrite NOT (status <> 'pending') or a function call into the form you indexed.Run EXPLAIN on the exact query your code sends, with the same literals and parameters, to confirm the index appears in the plan.
An upsert can target a partial unique index, but the conflict target has to repeat the predicate: ON CONFLICT (customer_id) WHERE status = 'active' DO NOTHING. The INSERT documentation calls this the index_predicate, and without it Postgres reports that no matching constraint exists.
Best fit: large tables where queries only touch a small, well-defined subset, and rules that apply to one state of a row.
Encore is a backend framework with built-in infrastructure, so the index lives in the same service as the code that depends on it: a migration in the service's migrations directory, applied by encore run to the local Postgres it starts and by each deploy to RDS or Cloud SQL in your account. This subscriptions service relies on the partial unique index to stop a second active subscription:
Run in your terminal to get started locally.
-- subscriptions/migrations/1_create_subscriptions.up.sql
CREATE TABLE subscriptions (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id text NOT NULL,
plan text NOT NULL,
status text NOT NULL DEFAULT 'active',
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX subscriptions_one_active_idx
ON subscriptions (customer_id)
WHERE status = 'active';
// subscriptions/subscriptions.go
package subscriptions
import (
"context"
"encore.dev/beta/errs"
"encore.dev/storage/sqldb"
"encore.dev/storage/sqldb/sqlerr"
)
var db = sqldb.NewDatabase("subscriptions", sqldb.DatabaseConfig{Migrations: "./migrations"})
type StartParams struct {
CustomerID string `json:"customer_id"`
Plan string `json:"plan"`
}
type Subscription struct {
ID int64 `json:"id"`
}
//encore:api public method=POST path=/subscriptions
func Start(ctx context.Context, p *StartParams) (*Subscription, error) {
var id int64
err := db.QueryRow(ctx, `
INSERT INTO subscriptions (customer_id, plan)
VALUES ($1, $2)
RETURNING id
`, p.CustomerID, p.Plan).Scan(&id)
if sqldb.ErrCode(err) == sqlerr.UniqueViolation {
return nil, &errs.Error{Code: errs.AlreadyExists, Message: "customer already has an active subscription"}
}
if err != nil {
return nil, err
}
return &Subscription{ID: id}, nil
}
// CountActive uses the partial index: the predicate is written as a literal.
//
//encore:api public method=GET path=/customers/:customerID/active
func CountActive(ctx context.Context, customerID string) (*Count, error) {
var n int
err := db.QueryRow(ctx, `
SELECT count(*) FROM subscriptions
WHERE customer_id = $1 AND status = 'active'
`, customerID).Scan(&n)
if err != nil {
return nil, err
}
return &Count{Active: n}, nil
}
type Count struct {
Active int `json:"active"`
}
sqldb.ErrCode maps the Postgres error to a typed code, and returning errs.AlreadyExists gives the caller a 409 instead of a generic 500, as listed in the API errors docs. The databases docs cover migrations and the query API, and adding an index to an existing table is the same flow described in changing the database schema. A test that starts two subscriptions for the same customer and expects the second to fail keeps the rule from being dropped in a later migration.
When an AI coding agent is asked to "make sure a customer can only have one active plan", the useful change is a migration with the partial unique index plus the error mapping in the endpoint, and with both in the service's own directory the agent can make that one change and test the race locally before it ships.
Best fit: services that need database-enforced rules on one state of a row and fast reads on a small, hot subset.
CREATE INDEX CONCURRENTLY so writes are not blocked, keeping in mind that the CREATE INDEX documentation says it cannot run inside a transaction block.pg_stat_user_indexes, and drop it if idx_scan stays at zero.A partial index is an index built with a WHERE clause, so it only contains the rows that match that predicate. It is smaller and cheaper to maintain than a full index, and Postgres uses it for queries whose WHERE clause implies the index predicate.
The planner only uses a partial index when it can prove at planning time that the query's WHERE clause implies the index predicate. A predicate written differently, or a parameter in place of the literal value, such as status = $1 instead of status = 'pending', usually prevents that match.
Yes. CREATE UNIQUE INDEX ... WHERE enforces uniqueness only among rows that match the predicate, for example one active subscription per customer while any number of cancelled ones are allowed.
Add CREATE UNIQUE INDEX ... WHERE to a migration file in the service's migrations directory, then check sqldb.ErrCode(err) == sqlerr.UniqueViolation in the endpoint to return a clear error. encore run applies the migration to the local Postgres it starts.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.