BitmapOr Combines Two Index Scans
An OR over two single-column indexes cannot share one composite btree, so the planner may merge both index bitmaps with a BitmapOr node instead.
Page 5 of 7
An OR over two single-column indexes cannot share one composite btree, so the planner may merge both index bitmaps with a BitmapOr node instead.
Roll up boolean flags per group with bool_and and bool_or, which ignore NULL inputs and return NULL when no non-null input exists.
Sort tickets by urgency: a CASE expression returns the numeric priority used as the leading ORDER BY key, and ELSE catches unlisted statuses.
Bind optional filters as NULL so (param IS NULL OR col = param) collapses to always true, letting one statement serve every filter combination.
Make a column conditionally required with a CHECK: status = 'closed' must carry closed_at, while other statuses leave it free; NOT NULL cannot express this.
CHECK constraints cannot contain subqueries or reference other rows, so cross-row rules need a deferrable constraint trigger that validates at commit time.
A CHECK constraint can compare several columns of the same row, rejecting bookings whose end time is not strictly after the start time at the database boundary.
Enforce exactly-one-of-two columns with a CHECK constraint over num_nonnulls, rejecting rows that assign both or neither target.
Enforce text hygiene with CHECK constraints: btrim equality rejects padded strings, char_length bounds the size, status accepts known values only.
Assign each user to the month of first activity, join follow-up months back, and render retention as conditional counts per months-since bucket.
Control string comparison per column, per query, and per index with COLLATE, so the same names sort differently per language and indexes stay usable.
UNIQUE (user_id, project_id) allows one user on many projects and one project on many users, while two single-column uniques would forbid both.
Enforce a whole-set rule like two-leads-per-team with a DEFERRABLE INITIALLY DEFERRED constraint trigger, validated at COMMIT instead of per row.
Load CSV in one atomic statement with COPY, choosing server-side file reads or the client-side \copy equivalent and skipping row-by-row inserts.
CORR measures the Pearson correlation of two columns per group, also works as a window aggregate, and returns NULL when a variance is zero.
COUNT(DISTINCT x) OVER fails in PostgreSQL with 'DISTINCT is not implemented for window functions'; deduplicate first, then window-count.
Build a full combination matrix with CROSS JOIN, then LEFT JOIN real facts onto the skeleton so empty combinations show as zero instead of disappearing.
Keep large result sets on the server and pull them batch by batch with DECLARE CURSOR, FETCH n, and CLOSE, or let WITH HOLD survive the transaction commit.
Subtracting dates returns integer days while subtracting timestamps returns an interval, so mixing the two types changes the result's shape.
Truncate timestamps to calendar boundaries with date_trunc, then group on the result so counts align to real months, weeks, and hours.
Keep the top row of every group with DISTINCT ON, where the leading ORDER BY columns decide which row survives and wrapping re-sorts the output.
ALTER TABLE DROP COLUMN finishes instantly regardless of table size because only catalog metadata flips; old bytes stay in the heap until a rewrite.
Set enable_seqscan = off so the planner prefers index paths, compare the plans, then RESET; it is session-level debugging, not a production setting.
Build dynamic statements server-side with EXECUTE format: %I quotes identifiers and %L escapes literals, so stray apostrophes cannot break or inject the SQL.
BUFFERS output splits page access into shared hit for pages already cached and shared read for disk or OS fetches; two runs expose the cache effect.
Create expression indexes only from IMMUTABLE functions: upper() qualifies, while STABLE helpers like age(timestamp) are rejected outright.
FETCH FIRST n ROWS WITH TIES extends the result to every row tied with the cutoff, so leaderboards stop truncating equal scores that bare LIMIT silently drops.
Add a foreign key online with NOT VALID to skip scanning existing rows, then validate it later under a light lock that never blocks reads or writes.
FOR UPDATE NOWAIT fails immediately with lock_not_available when another transaction holds the row, choosing a loud failure over unbounded queue waiting.
Join ledgers from both sides, keep only rows with NULL on either side or mismatched amounts, and label each difference with a CASE.
Give tables random UUID primary keys with the built-in gen_random_uuid default, and validate external identifiers with ::uuid casts.
Explain the GIN fastupdate pending list: bulk writes batch there, queries pay a periodic merge cost, and fastupdate off trades write speed for smooth reads.
Accelerate overlap queries on range columns with a GiST index, because B-tree indexes cannot serve the && operator that range types rely on.
Give a reporting role read-only access with GRANT SELECT and ALTER DEFAULT PRIVILEGES so future tables inherit the same narrow scope.
One query yields detail rows, region subtotals, and a grand total via GROUPING SETS, with GROUPING() flagging which output columns are aggregated placeholders.
Filter month and day windows with >= start AND < end because BETWEEN reads the upper bound as midnight and drops the remainder of that day.
Create a hash index for equality-only lookups on long token columns, leaving range predicates, ordering, and uniqueness to a btree companion index.
Hash partitions route rows by modulus and remainder over the partition key, with equality predicates pruning the scan to a single partition.
Compare the two aggregation paths with EXPLAIN: hash builds first, group aggregates over sorted input, and enable_hashagg flips the plan for comparison.
CREATE INDEX IF NOT EXISTS and DROP CONSTRAINT IF EXISTS keep migrations re-runnable; ADD CONSTRAINT has none, so a DO block queries pg_constraint first.
Index Cond pushes equality and range predicates into the index scan; non-indexed columns surface as a post-scan Filter with rows-removed cost.
Index foreign key child columns because PostgreSQL does not create them automatically, so parent deletes avoid scanning the child table.
A btree index serves ORDER BY with LIMIT: the scan stops after n rows in either direction, and only a mismatched sort column falls back to a full sort.
Discover table structure through INFORMATION_SCHEMA columns and table_constraints instead of hardcoding column names into migrations.
Summing a parent through a one-to-many join counts each parent once per child; pre-aggregate the child side in a CTE to keep totals honest.
PostgreSQL 17 JSON_TABLE expands a JSON document into relational rows, declaring each column with name, type, and path, and NESTED PATH flattens inner arrays.
Lock the JSONB contract at write time: jsonb_typeof pins the top-level type and required keys, and nested values get their own type checks.
Match literal underscores and percent signs in LIKE patterns by escaping them, or the wildcards silently match characters you did not intend.
Split a tickets table by region with PARTITION BY LIST: equality and IN predicates prune to the matching child tables and skip the rest.
Deliver session-to-session signals with NOTIFY, which queues messages only at commit and drops them silently when nobody is listening.
PostgreSQL 17 MERGE adds WHEN NOT MATCHED BY SOURCE, so one statement updates changed rows, inserts missing ones, and deletes stale target rows in a sync.
A plain min or max becomes an index-endpoint InitPlan in EXPLAIN, independent of table size; ORDER BY plus LIMIT 1 fetches the whole oldest row the same way.
Return the most frequent non-null value per group with mode() WITHIN GROUP, and narrow the vote with FILTER when only qualifying rows count.
Chain INSERT RETURNING output into an UPDATE within one data-modifying CTE statement so order creation and stock deduction commit atomically together.
Every UPDATE writes a new row version: ctid moves to fresh storage and xmin records the writing transaction, which is the bloat VACUUM later reclaims.
A few indexed rows make nested loop cheapest, while a full aggregate over both tables amortizes into one hash join build; EXPLAIN shows which wins.
Use NOT EXISTS for anti joins because a single NULL in a NOT IN subquery makes the predicate UNKNOWN and silently returns an empty result.
now() freezes at transaction start so every call in one transaction agrees, while clock_timestamp() keeps moving with the wall clock.
Pick the second row of a window frame with nth_value; the default frame gives a moving answer while an unbounded full frame pins one constant runner-up.
PostgreSQL treats NULL as largest, so DESC defaults to NULLS FIRST; ORDER BY DESC NULLS LAST matches only an index created with the same explicit NULLS LAST.
Store money in NUMERIC and analytics in double precision: binary floats cannot represent 0.1 exactly, so repeated sums drift away from decimal results.
Inserting two rows that hit the same conflict target fails with cannot affect row a second time; aggregate the source by key first so each target appears once.
Right-table filters belong in ON, not WHERE: a WHERE on the right side of a LEFT JOIN discards unmatched rows and silently turns it into an inner join.
A unique index on a partitioned table must include every partition key column, because per-partition enforcement alone cannot guarantee global uniqueness.
Ordered-set aggregates cannot be window functions, so compute PERCENTILE_CONT per group in a CTE and join it back to attach the median to every detail row.
List the sessions waiting on locks with pg_blocking_pids joined against pg_stat_activity, then inspect pg_locks for the exact lock modes they are stuck on.
Promote a unique index built with CREATE INDEX CONCURRENTLY to a primary key with ADD CONSTRAINT USING INDEX, without rebuilding the table.
Declare range partitions so inserts route to the right child and queries with the partition key prune every other partition in the plan.
SEARCH DEPTH FIRST BY sets the sequence column to each row key path, emitting parents before children so trees unfold in pre-order without hand-managed state.
Split a delimited string with a recursive CTE that peels one token per iteration, and prefer the built-in string_to_table on PostgreSQL 14 and later.
Clean text with regexp_replace masking, substring FROM pattern extraction, and the ~ operator for regex membership tests inside SELECT lists.
Compare each reading against a trailing frame mean and stddev_samp that exclude the current row, flagging |z| beyond 3 with NULL-safe division.
Assign queue rows to worker slots by taking ROW_NUMBER modulo the worker count, with a partitioned variant that balances within each region.
ROW_NUMBER assigns arbitrary order among rows tied on the sort key; add a unique tiebreaker to make numbering, paging, and deduplication reproducible.
Track a cumulative high-water mark with MAX() OVER ordered frames, handling the empty first-row frame whose MAX evaluates to NULL.
Keep a plain index usable by moving interval math to the constant side: a function wrapped around the indexed column blocks the index scan.
Mark a point inside a transaction with SAVEPOINT so a failed statement can be undone with ROLLBACK TO SAVEPOINT while earlier work stays intact.
Unqualified table and function names resolve through search_path left to right, so switching schemas re-points the same queries.
Increment counters inside a single self-referencing UPDATE so concurrent transactions serialize on the row lock; the read-then-write pattern loses increments.
Identity and nextval never recycle numbers: rolled-back inserts leave permanent gaps, so count rows with count(*) instead of max(id).
Split event streams into sessions: LAG measures the gap since the previous click, a flag marks 30-minute gaps, and a running SUM assigns session numbers.
ALTER COLUMN SET DEFAULT shapes only future inserts: existing rows keep their values, and DROP DEFAULT just removes the expression without rewriting data.
SET LOCAL statement_timeout caps every statement inside the current transaction only, so pooled connections return to their default limit after COMMIT.
Adding a NOT VALID check and validating it first lets SET NOT NULL skip the table scan on PostgreSQL 12+, turning a long lock into metadata work.
Seed random() with setseed to replay the exact same sequence in a session, which makes generated fixtures and sampled comparisons reproducible.
Bulk imports with explicit ids leave the IDENTITY sequence behind; setval to max(id) via pg_get_serial_sequence makes the next insert safe again.
Create a partitioned-tree index with USING spgist (url text_ops) so constant-prefix LIKE queries hit the index, while infix patterns still need trigram support.
Build running event trails with string_agg as a window aggregate: ROWS frames accumulate from the partition start or a trailing window of recent steps.
Sample rows cheaply with TABLESAMPLE SYSTEM for block-level speed or BERNOULLI for row-level evenness, pinning the draw with REPEATABLE.
Session-private temp tables either survive commits (the default) or vanish with ON COMMIT DROP, which requires an enclosing transaction.
Plain boolean predicates drop NULL rows silently; IS TRUE and IS NOT TRUE make the treatment of unknown three-valued states explicit.
Map timestamps and numbers to display strings with format patterns — quoted literals, FM trimming, and currency via the locale setting.
A BEFORE UPDATE trigger rewrites NEW.updated_at inside the database, so every UPDATE gets a fresh timestamp even when the application forgets to set one.
Answer scheduling questions with tstzrange operators: && tests overlap, @> tests containment, and lower, upper, and upper_inc expose exact boundaries.
Combine a stored tsvector generated column with a GIN index so websearch_to_tsquery queries rank matching articles without scanning every row.
Add UNIQUE to the referencing column so a foreign key allows at most one child per parent, turning a one-to-many relationship into a true one-to-one.
Trade WAL writes for speed with CREATE UNLOGGED: faster inserts for rebuildable staging data, with the table truncated after a crash and never replicated.
Expand arrays with unnest WITH ORDINALITY so each element keeps its original 1-based position through a LATERAL join instead of losing order.
Window functions cannot appear in an UPDATE's WHERE clause, so rank rows in a CTE with ROW_NUMBER and flip status through UPDATE FROM past the newest order.
Sort batch upsert input by conflict key so concurrent transactions acquire row locks in the same order instead of failing with deadlock detected.