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
userstable, aCHECKconstraint permits onlyfreeandpro. A query forplan = 'Pro'scans the table by default. Settingconstraint_exclusiontoonreplaces the scan with aResultnode and aOne-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_atcut execution from about 627 ms to 187 ms, but occupied 214 MB. - For day-level lookups, an expression index can instead truncate
sold_atto the day in UTC and cast it todate. 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 NOTHINGfailed to match it, but naming it withON CONFLICT ON CONSTRAINTworked.DO UPDATEis unsupported even when the constraint is named. The article also shows aMERGEplan 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.