For Update Of Targets One Table
FOR UPDATE OF o locks only the listed table rows in a join; without OF every participating table gets row locks, including pure filter-side tables.
Page 3 of 7
FOR UPDATE OF o locks only the listed table rows in a join; without OF every participating table gets row locks, including pure filter-side tables.
generate_subscripts emits the valid subscript range of one array dimension, and reverse walks it backwards; a missing dimension yields zero rows.
rank(8.00) WITHIN GROUP inserts a would-be value into each ordering and reports its rank directly — the same semantics as a window rank without a frame.
Normalize messy contact strings with INITCAP for word-initial capitalization and TRANSLATE for per-character masking or deletion via an empty replacement set.
Set join_collapse_limit to 1 and the planner stops reordering explicit JOINs, so the written sequence becomes the join sequence whenever you know a better one.
Show one player's standing plus adjacent ranks by computing RANK() for the whole board once and filtering a narrow rank window around the target.
A nested-loop join whose outer keys repeat earns a Memoize node: parameterized inner scans skip work on cache hits, reported in EXPLAIN ANALYZE.
Read EXPLAIN on a partitioned ORDER BY query: Merge Append merges each partition pre-sorted index stream, so LIMIT can stop early without a global sort.
Query the leading column of a two-column btree index and it serves you; filter on the second column alone and the planner cannot enter the leftmost prefix.
Upsert against a partial unique index: ON CONFLICT (email) WHERE deleted_at IS NULL selects the arbiter, and the bare column list fails outright.
Replace a slice in place with overlay(string PLACING string FROM n [FOR len]); omitting FOR uses the inserted string own length as the replaced length.
Take per-group Q1 and Q3 with percentile_cont in a CTE, derive the 1.5x IQR fences, flag rows outside them, and count outliers per group.
PL/pgSQL cannot run a bare SELECT, so PERFORM executes and discards the rows; FOUND then tells you whether the discarded query matched anything.
pg_backend_pid returns the process ID of the server process attached to the current session, matching the pid column in pg_stat_activity and lock diagnostics.
pg_get_constraintdef decompiles a pg_constraint row back into its CONSTRAINT clause, so audits show real definitions rather than hand-copied text.
pg_get_indexdef decompiles a catalog entry back into its CREATE INDEX statement, so migrations and docs can show real DDL instead of hand-copied definitions.
Inspect dead tuples and reusable free space with pgstattuple before and after VACUUM: deletes raise dead_tuple_percent, VACUUM converts them into free_percent.
Require two words adjacent and in order with to_tsquery's <-> (FOLLOWED BY) operator, so 'btree <-> index' misses documents where the pair is swapped.
Compute an exponential moving average with a recursive CTE joining each row to the previous smoothed value; window functions cannot reference their output.
Accumulate edge cost and visited path in a recursive CTE; a strpos guard stops cycles and the outer query keeps each node's cheapest route.
Explode free-form tag lists into rows with regexp_split_to_table behind a LATERAL join; a [,;\s]+ delimiter absorbs the mixed separators split_part preserves.
RETURN NEXT and RETURN QUERY append rows to the result set without leaving the function, so a PL/pgSQL function can mix hand-built rows with whole queries.
Deduplicate uploads by content: a generated sha256 column plus a unique expression index rejects the second identical payload at insert time.
Count real status changes per ticket with LAG plus IS DISTINCT FROM, so repeated heartbeats in the same state never inflate the transition total.
Tokenize a delimited column with string_to_array, filter with = ANY, and rebuild text with array_to_string, where a null string turns empty fields into NULL.
Locate a delimiter with strpos, slice from either end with left and right, and guard the not-found case because left(x, -1) silently trims the tail.
Keep every tie inside the top three per region with RANK() <= 3 over a PARTITION BY window, and contrast the truncating ROW_NUMBER version.
Match word stems still being typed with to_tsquery's :* prefix suffix, so data:* finds data and databases for autocomplete-style search.
Expression indexes reject non-immutable functions, so wrap unaccent in an immutable wrapper pinned to its dictionary and index names for accent-free search.
A NULL team_id means the global default; a unique index on COALESCE(team_id, 0), feature makes two NULL-team rows collide exactly like two rows for team 7.
Read EXPLAIN for window queries: the Sort node feeding WindowAgg, how a matching index removes the Sort, and why distinct windows stack separate nodes.
Compare each month to the same month a year ago: LAG(revenue, 12) assumes a dense series, while a calendar self-join on month - interval stays sparse-safe.
Compute year/month/day gaps with age(), which borrows calendar days across month ends instead of assuming fixed-length months.
Raise per-column sampling with SET STATISTICS so ANALYZE keeps a longer most_common_vals list and finer histograms for skewed or long-tail columns.
CHAR(n) pads stored values with spaces and ignores trailing spaces in comparisons and length(), while VARCHAR(n) keeps every byte.
One out-of-range row fails the entire INSERT statement: CHECK constraints evaluate every row and the whole batch rolls back, so pre-validate imports.
CHECK evaluates each row in isolation — it cannot query other rows — so cross-row invariants need UNIQUE or exclusion constraints instead.
CREATE INDEX IF NOT EXISTS compares names only: an existing index with different columns silently wins, so migrations can run on the wrong shape forever.
Run a data-modifying CTE chain that archives the current row and inserts its replacement, sharing one snapshot and one commit.
Prepare the candidate set once in a CTE, then reference it twice in a self-join with a shift_id guard so each overlapping pair is reported exactly once.
Chain INSERT ON CONFLICT with RETURNING inside a CTE so the guaranteed row keys feed a follow-up join in the same statement.
Chain two CTEs so one statement ranks submitted items and joins reviewer assignments, producing the review queue in a single snapshot.
Layer a CTE and window functions: CORR measures ad-spend to revenue correlation inside each region partition instead of one pooled number.
EXTRACT(DOW) numbers Sunday as 0 through Saturday 6, while ISODOW follows ISO 8601 with Monday 1 through Sunday 7.
Self-join pg_index metadata to find indexes whose key column lists are identical on the same table, so redundant write amplification can be dropped.
ON DELETE CASCADE walks the whole reference chain: grandchild rows vanish with the root, and one RESTRICT deeper down blocks the entire delete.
ON DELETE SET DEFAULT rewrites child keys to the column default, and the delete fails outright when that default does not satisfy the foreign key.
Renaming a referenced natural key ripples into child rows under ON UPDATE CASCADE, while the NO ACTION default and RESTRICT reject the update instead.
Count consecutive funnel conversions with LAG(event, n) over user-ordered events: a step only counts when its predecessor steps happened.
GiST indexes answer nearest-neighbor queries directly: ORDER BY location <-> point returns rows from nearest to farthest without a sort step.
A partial index only helps queries whose WHERE clause implies the index predicate, so the planning output decides whether it gets used.
A failed CREATE INDEX CONCURRENTLY leaves an INVALID index that still taxes writes; find it in pg_index, drop it, and rebuild.
Interval literals accept both verbose strings and ISO 8601 durations like P1DT2H, and the two forms compare equal for the same span.
JOIN USING coalesces the shared column into one output column while ON keeps both sides, and NATURAL joins implicitly on every shared name.
GIN indexes serve containment on jsonb, but scalar equality on payload->>'key' needs a btree expression index built on that exact expression.
Emulate the unimplemented IGNORE NULLS by pre-filtering NULLs in a subquery, then streaming last_value over a narrowed frame per ticker.
Data-modifying CTEs and the outer query share one snapshot: the outer SELECT still counts rows a WITH DELETE removed; only later statements see them gone.
Partial index predicates must be IMMUTABLE, so now() inside the WHERE is rejected; gate the index on a stable status column and leave time filters to queries.
A DEFAULT partition absorbs rows no other partition accepts, and blocks CREATE TABLE ... PARTITION OF until conflicting rows are moved out.
Updating a partition key value triggers row movement: the row vanishes from the old partition and appears in the new one automatically.
Create a partitioned index and per-partition partial indexes, then confirm each child carries its own index entry in pg_indexes.
One WITH list may hold several RECURSIVE items: walk the manager chain upward and fan out to all reports in the same query, then union the labeled halves.
Cycle-tainted hierarchy walks terminate when the recursive CTE uses UNION: duplicate rows are discarded, so a repeated node produces nothing new.
Aggregate the strictly previous rows with ROWS BETWEEN n PRECEDING AND 1 PRECEDING: the current row never influences its own look-back statistic.
var_pop divides by n while var_samp divides by n-1, so one-row samples return NULL under samp but 0 under pop, and the same split applies to stddev.
Cross-row CHECK is implementation-dependent; the portable guard is a trigger that counts rows itself and must lock the zone first or inserts race past the cap.
NOT VALID only applies to foreign-key, CHECK, and not-null constraints, so a UNIQUE addition must scan and dedupe the whole table in the same statement.
Turn a small hand-written tuple list into an inline WITH ... AS (VALUES ...) CTE and LEFT JOIN against it, so unmatched parameters return zero rows.
security_invoker views execute with the caller's privileges, so row level security follows the caller instead of being bypassed by the view owner.
Measure the elapsed days between consecutive visits with LAG and a date difference, converting row order into per-user inter-event gaps.
Window calls cannot nest inside one SELECT level: compute the inner ranking in a CTE, then rank that output in the outer query.
COUNT, MAX, and AVG OVER (PARTITION BY) stamp every row with its group's aggregates, so detail rows survive alongside group totals.
Compute each group median with PERCENTILE_CONT WITHIN GROUP, including interpolated even-count values, then join the aggregate back per row.
Compare RANK and DENSE_RANK on tied totals: RANK leaves gaps after ties while DENSE_RANK numbers every distinct value consecutively.
rank, row_number, lag, and ntile ignore the frame clause entirely, while aggregates and first_value honor it — same frames, different results.
Restart running totals per month with PARTITION BY date_trunc expression keys, so each bucket starts its own cumulative sum beside the all-time total.
SELECT-list aliases are visible to ORDER BY but not to WHERE or HAVING; PostgreSQL additionally lets GROUP BY refer to output column names.
Backfill large tables in chunks with UPDATE over a bounded id subquery, keeping each transaction short so locks and replication lag stay small.
A BEFORE row trigger that returns NULL silently cancels the write: the row never lands, no error is raised, and the statement simply affects fewer rows.
A CHECK expression passes whenever it evaluates to NULL, so constraints that look strict still allow missing values unless the predicate is written NULL-aware.
Pin numeric columns to valid domains with CHECK constraints: BETWEEN bounds, positive amounts, and cross-column date order — mind that NULL passes.
Enforce code formats at the database boundary with a CHECK constraint on a POSIX regex pattern, so malformed tracking codes are rejected on write.
Constrain a status column to an explicit whitelist with CHECK ... IN so invalid states are rejected at write time with a named constraint.
String concatenation with || returns NULL when any operand is NULL, so display strings built from optional columns need COALESCE per operand.
Stream query results out as CSV with COPY ... TO STDOUT: headers on demand, RFC 4180 quoting for commas and quotes, forced quotes per column.
pg_stats.correlation measures how a column's physical row order matches its logical order: near ±1 scans stay sequential, near 0 rows scatter into random I/O.
COUNT(*) counts every row while COUNT(col) skips NULLs — so they disagree on sparse columns, and COUNT(DISTINCT col) collapses repeats before skipping NULLs.
Flip a boolean feature flag in place with SET enabled = NOT enabled and RETURNING the new state, so toggling needs no read-modify-write round trip.
A foreign key can only reference columns covered by a PRIMARY KEY or UNIQUE constraint; creating one against a plain column fails with a matching-keys error.
GROUP BY treats NULL as one group key: every NULL row lands in a single bucket, even though no WHERE comparison can ever match a NULL value.
Seed reference data idempotently with INSERT SELECT plus a WHERE NOT EXISTS guard, so replaying the script neither duplicates rows nor needs a conflict target.
Compute per-event durations by subtracting the current timestamp from LEAD of the next event, then aggregate total durations per endpoint outside.
Sort numeric codes stored as text correctly: LPAD adds leading zeros so lexicographic order matches numeric order, indexable as an expression.
Collect every descendant of a category with a recursive CTE, then delete the whole subtree in one statement that returns the removed rows.
Score customers into quintiles with three NTILE windows over recency, frequency, and spend, then concatenate the ranks into a classic RFM score string.
ROUND ties away from zero, TRUNC cuts toward zero, and FLOOR and CEIL head toward minus and plus infinity.
Close the previous version row and insert the replacement in one data-modifying CTE so slowly changing dimension history keeps a single open row.
FOR SHARE takes a row lock that blocks writers but permits other readers, unlike the plain snapshot read that lets a concurrent UPDATE slip between checks.
Enforce a one-row settings table with a CHECK (id = 1) guard so concurrent writers cannot create a second row, and mutate it with ON CONFLICT.
Build display strings with chained ||, the concat and concat_ws functions, and format() placeholders — each handles NULL and separators differently.