Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Learn how to use PostgreSQL partial indexes with WHERE clauses to reduce index size, speed up queries on filtered data, and enforce unique subsets.
Quick answer
A PostgreSQL partial index is an index built over a subset of rows defined by a conditional WHERE clause. It reduces disk usage and write overhead by indexing only the rows that match the predicate, allowing queries with matching filters to execute rapid index scans without indexing irrelevant data.
FAQs
What is the main benefit of a partial index in PostgreSQL?
A partial index reduces index file size and write overhead by storing pointers only for rows satisfying a specific WHERE clause. This saves RAM and keeps critical query indexes cached in memory.
Can a PostgreSQL partial index have multiple columns?
Yes. A partial index supports composite column definitions just like a regular B-tree index, combined with a single WHERE condition.
Why does my query ignore a partial index despite having the same condition?
The planner ignores partial indexes if the query WHERE clause is broader than the index predicate, or if parameterized queries hide the literal values required to prove the condition holds true.
Can I create a partial index concurrently in production?
Yes. You can run CREATE INDEX CONCURRENTLY with a WHERE clause to build the partial index without locking writes on the parent table.
Build fast text search directly in PostgreSQL without external search engines. Master to_tsvector, to_tsquery, relevance ranking with ts_rank, and GIN indexes.
PostgreSQL partial indexes let you attach a WHERE clause directly to an index definition. Standard indexes index every row in a table. In contrast, a partial index stores pointers only for rows satisfying your filter condition. When ninety-five percent of your table contains archived or completed records that queries rarely touch, indexing the entire table wastes RAM, slows down writes, and inflates backup files.
By indexing only the active five percent of rows, your index fits entirely in memory. Queries searching for active records execute rapid index scans, while insert and update operations on completed records skip index maintenance completely. Understanding how the query planner matches queries to partial indexes ensures your queries take advantage of these savings.
Why partial indexes outperform full table indexes
Every index on a table imposes a direct cost on write operations. Whenever you run an INSERT, UPDATE, or DELETE, PostgreSQL must update every relevant B-tree index on that table. On high-throughput transactional tables, secondary indexes frequently cause write bottlenecks and disk bloat. Read our analysis on database indexing principles for how B-tree maintenance impacts page splits.
A partial index eliminates index maintenance for any row that fails the index predicate. If you insert a row where status = 'archived', an index defined with WHERE status != 'archived' ignores the new row entirely. The database writes the row to the heap page and updates only the primary key and unrelated indexes.
The second major advantage is cache efficiency. Operating systems and PostgreSQL buffer pools cache frequently accessed 8KB pages. A full index on a 100-million-row table might consume 8 gigabytes of memory. A partial index covering only the 200,000 active records might occupy only 16 megabytes. That tiny index remains permanently pinned in RAM, avoiding random disk reads and lowering query latency.
Syntax and basic partial index creation
You define a partial index by appending a standard WHERE clause to the end of the CREATE INDEX command. The expression can use comparison operators, boolean flags, null checks, and function calls that are immutable.
Creating a basic partial index
-- Index only active accountsCREATE INDEX idx_users_active_emailON users (email)WHERE is_active = true;-- Index only pending queue jobsCREATE INDEX idx_jobs_pendingON background_jobs (priority DESC, created_at ASC)WHERE status = 'pending';
According to the PostgreSQL partial index documentation, the predicate in the index definition must contain only immutable functions. Volatile functions like now() or random() are disallowed because the condition must evaluate consistently regardless of transaction execution timing.
Matching rules: how the planner uses partial indexes
The PostgreSQL query planner uses a partial index only when it can mathematically prove that the query filter implies the index predicate. If your query condition is broader than the index predicate, the planner cannot use the index.
Query planner matching comparison
-- Planner uses idx_users_active_email:SELECT id, email, created_atFROM usersWHERE email = 'alex@example.com' AND is_active = true;-- Planner CANNOT use idx_users_active_email (scans full table or standard index):SELECT id, email, created_atFROM usersWHERE email = 'alex@example.com';
The query WHERE clause must either match the index predicate exactly or be mathematically stricter. For instance, if your index condition is WHERE score > 100, a query with WHERE score > 500 can use the index because every score over 500 is guaranteed to be over 100. However, a query with WHERE score > 50 cannot use the index because rows between 51 and 100 are missing from the index structure.
Conditional uniqueness with partial unique indexes
Standard unique constraints prevent duplicate values across all rows in a table. In many production systems, you want to enforce uniqueness only among active records while allowing historical duplicates. Soft deletion is the most common example. Read our guide on SQL soft delete patterns for schema trade-offs.
Consider a tenancy model where users can deactivate accounts. You want each organization to have only one active billing contact, but historical billing contacts can exist in the table with active = false. A partial unique index enforces this rule cleanly at the database level.
Partial unique index implementation
-- Allow multiple inactive records, but guarantee only one active billing contact per orgCREATE UNIQUE INDEX uq_org_active_billing_contactON organization_contacts (organization_id)WHERE is_billing_contact = true AND is_active = true;-- Insert first contact (succeeds)INSERT INTO organization_contacts (organization_id, contact_name, is_billing_contact, is_active)VALUES (101, 'Finance Lead', true, true);-- Insert second active contact for same org (fails with unique violation)-- ERROR: duplicate key value violates unique constraint "uq_org_active_billing_contact"
Excluding NULL values from sparse column indexes
Many relational tables have sparse columns where ninety-nine percent of rows contain NULL. For example, an orders table might have an optional refund_transaction_id or an escalation_reason column. Indexing a column where almost all values are NULL fills B-tree leaf pages with pointers to empty values.
Sparse column partial index
-- Traditional full index: stores millions of NULL entries-- CREATE INDEX idx_orders_refund ON orders (refund_transaction_id);-- Partial index: stores only actual refunded ordersCREATE INDEX idx_orders_refund_partialON orders (refund_transaction_id)WHERE refund_transaction_id IS NOT NULL;-- Query that hits the partial indexSELECT id, customer_id, total_amountFROM ordersWHERE refund_transaction_id = 'ref_987654321';
As detailed in the PostgreSQL index expressions reference, indexing only non-null values reduces the B-tree depth by several levels, speeding up lookups and slashing maintenance costs during bulk imports.
Common pitfalls with prepared statements and ORMs
A frequent issue occurs when applications use parameterized queries through database drivers or ORMs. When an application passes a parameter like WHERE status = $1, PostgreSQL initially prepares a generic plan. If $1 is a variable rather than a literal constant, the planner cannot be certain that $1 will match the partial index condition.
In PostgreSQL, the query engine evaluates custom plans for the first five executions. If the generic plan is chosen afterward, queries that previously hit the partial index might fall back to sequential scans. To guarantee partial index usage, keep the literal condition directly in your SQL string, such as WHERE status = 'pending' AND user_id = $1.
Measuring index size and memory reduction in practice
You can measure the exact storage savings of partial indexes using PostgreSQL internal administration functions. Running pg_relation_size() against both a standard index and a partial index demonstrates why partial indexes stay resident in memory.
Checking partial index storage savings
-- Compare size of full index vs partial indexSELECT relname AS index_name, pg_size_pretty(pg_relation_size(c.oid)) AS index_sizeFROM pg_class cJOIN pg_namespace n ON n.oid = c.relnamespaceWHERE c.relname IN ('idx_orders_full_status', 'idx_orders_pending_partial') AND n.nspname = 'public';
Actionable checklist for partial indexes
Verify row distribution: check that the filtered subset represents less than twenty percent of the table.
Keep predicates static: use literal constants in the WHERE clause rather than variable parameters.
Run EXPLAIN ANALYZE: inspect the query plan to confirm the planner chooses an Index Scan or Bitmap Index Scan rather than a Seq Scan.
Monitor index size: compare pg_relation_size of the partial index against a standard index to verify disk savings.
Validate query alignment: confirm all application queries accessing the subset include the exact index predicate.
Review vacuum impact: remember that dead tuples in the indexed subset still require vacuum cleanup.
Wrapping up
PostgreSQL partial indexes are one of the most effective ways to optimize read performance and trim unnecessary storage on high-volume tables. By indexing only active, non-null, or unprocessed rows, you keep B-trees compact, fast, and cached in RAM. Before pushing new index migrations to production, format your SQL queries and schema scripts with sqlfmt to maintain consistent code style across your engineering team.