Skip to content
Haki Benita Blog·

Unconventional PostgreSQL Optimizations

Unconventional PostgreSQL Optimizations

Key Takeaway

Haki Benita explores unconventional PostgreSQL techniques: using CHECK constraints to skip full table scans, using function-based indexes to lower cardinality, and enforcing uniqueness with a hash index.

Why It Matters

For long text that only needs equality lookups and is not referenced by foreign keys, a hash-backed exclusion constraint can save index space but cannot support ON CONFLICT DO UPDATE.

Technical Breakdown · Distilled from the original source

Skip scans using CHECK constraints

  • On the 100,000-row users table, a CHECK constraint permits only free and pro. A query for plan = 'Pro' scans the table by default. Setting constraint_exclusion to on replaces the scan with a Result node and a One-Time Filter: false.
  • The default, partition, does not apply this check to all ordinary tables. Execution fell from 7.436 ms to 0.008 ms in the example, while planning rose from 4.564 ms to 5.760 ms. Weigh that trade-off for hand-written reporting queries.

Index at the reporting granularity

  • On the 10-million-row sales table, a monthly query groups sales by day. A B-tree on sold_at cut execution from about 627 ms to 187 ms, but occupied 214 MB.
  • For day-level lookups, an expression index can instead truncate sold_at to the day in UTC and cast it to date. This lowers key cardinality rather than retaining timestamp precision that daily reports do not need.

Reject duplicate URLs with a hash-backed exclusion constraint

  • An equality-based exclusion constraint backed by a hash index rejects duplicate URLs and supports equality lookups. In the example, it occupied 32 MB versus 154 MB for the unique B-tree.
  • The constraint cannot serve as a foreign-key target. ON CONFLICT (url) DO NOTHING failed to match it, but naming it with ON CONFLICT ON CONSTRAINT worked. DO UPDATE is unsupported even when the constraint is named. The article also shows a MERGE plan that uses the hash index.
Source: Haki Benita Blog· hakibenita.com

PG Radar summarizes verified changes and impact. Read the original post for full technical details and code samples.

Read Official Source

Related PostgreSQL Reference