Cursor Current Of Positional Update
WHERE CURRENT OF rewrites exactly the row a declared cursor currently points at: each FETCH advances the pointer and the positional UPDATE follows it.
Page 2 of 7
WHERE CURRENT OF rewrites exactly the row a declared cursor currently points at: each FETCH advances the pointer and the positional UPDATE follows it.
Grouping ledger entries by transaction and comparing SUM(debit) with SUM(credit) in HAVING exposes the unbalanced entries a running balance view would hide.
Group and count existing rows with HAVING before adding a UNIQUE constraint, because the constraint build fails while duplicated keys remain.
SUM, AVG, and MIN over an empty set return NULL rather than zero while COUNT returns 0, so wrap sums in COALESCE when downstream expects a number.
An event trigger on ddl_command_end records every CREATE, ALTER, and DROP into an audit table through pg_event_trigger_ddl_commands().
Rank posts for trending feeds with EXP decay and a gravity denominator, so fresh votes outweigh votes that have aged for days.
EXTRACT(EPOCH FROM ...) renders timestamps as seconds since 1970 and to_timestamp converts back: naive values count literally, timestamptz counts from UTC.
count(*) must scan every row while pg_class.reltuples hands back the planner row estimate instantly; ANALYZE keeps the estimate fresh.
Map each order to a July-start fiscal year with CASE on the month, then roll orders and revenue up per fiscal year through a CTE.
A foreign key needs comparable column types: integer referencing text fails at DDL time with an incompatible-types error until both ends match.
format() quotes identifiers with %I and escapes literals with %L so dynamically assembled SQL stays safe; %s inserts raw text for trusted fragments.
Rank products against a misspelled query by levenshtein edit distance from the fuzzystrmatch extension, nearest match first.
A counter table hands out invoice numbers under a row lock: UPDATE ... RETURNING increments atomically and a ROLLBACK gives the number back for reuse.
Inside an EXCEPTION handler, GET STACKED DIAGNOSTICS exposes the caught failure's SQLSTATE, message text, and PL/pgSQL call context.
WITH GRANT OPTION lets the grantee re-grant to a third role, and REVOKE with CASCADE tears the whole chain down from the source.
Grouping by the primary key lets every column of the table appear in SELECT via functional dependency, but grouping by a non-key column cannot.
Verify grants with has_table_privilege before risky DDL: test a named role, current_user, or PUBLIC, and list several privileges with OR semantics.
Compute great-circle distance from stored lat/lng to a target point with the haversine formula and rank depots nearest first.
B-tree entries have a hard row-size ceiling, so an index on an incompressible wide text column builds empty but fails on the first oversized insert.
Equality column first and sort column second lets one composite index answer WHERE, ORDER BY, and LIMIT without a separate sort step.
The literals infinity and -infinity are valid timestamps that compare past every finite moment, with isfinite separating open ends.
int4range normalizes discrete bounds so '[1,5]' equals '[1,6)', the upper edge stays exclusive, and lower_inc plus upper_inc expose endpoint inclusion.
Dividing two integers keeps the result an integer and truncates toward zero: -7 / 2 yields -3, and only a numeric cast restores the fraction.
Expand a JSONB array back into rows with jsonb_array_elements_text, keep each element's position with WITH ORDINALITY, then re-aggregate with jsonb_agg.
GREATEST lifts the floor and LEAST caps the ceiling across mixed columns; PostgreSQL ignores NULL arguments and returns NULL only when every one is NULL.
Store hierarchies as dot-separated label paths and answer descendant, pattern, and slice queries with ltree operators instead of recursive CTE walks.
A self-join with a.item < b.item counts unordered item pairs per order, and ORDER BY the pair frequency surfaces the baskets that sell together.
Assign A/B variants by hashing the user id with md5 and taking modulo 100, so bucketing is deterministic and needs no stored state.
ALTER COLUMN SET (n_distinct) corrects planner group-count estimates for skewed columns; negative values mean a fraction of rows.
NO ACTION with DEFERRABLE lets the parent delete succeed until commit, while RESTRICT rejects the same statement immediately even when deferred.
Casting numeric to integer rounds half away from zero instead of truncating: 3.7::int is 4 and -3.7::int is -4, unlike trunc().
Numeric NaN sorts above every finite value and equals itself, so max() picks NaN and unique keys treat it as one ordinary sentinel.
A numeric(8,2) column rounds 123.456 to 123.46 on insert, while a value that no longer fits the declared precision raises a field-overflow error.
round(numeric) rounds half away from zero while round(double) rounds half to even; div truncates and mod follows the dividend's sign.
Sort rows by workflow meaning instead of alphabet: ORDER BY CASE maps each status to an explicit rank, with an ELSE bucket for unknown values.
Append a unique key after the sort column so OFFSET pages follow one total order, and let a matching composite index serve the whole sort.
pg_current_xact_id() assigns an XID even when the transaction only reads, while the if_assigned variant stays NULL until a write actually needs one.
PG16 adds pg_input_is_valid to test whether a string converts cleanly to a type without raising, and pg_input_error_info to fetch the failure detail.
Snapshot pg_stat_activity to see which queries are active, how long each has run, and which sessions sit idle in transaction.
deadlocks in pg_stat_database is a per-database cumulative counter since the last stats reset; pair it with pg_blocking_pids for the live picture.
Poll pg_stat_progress_create_index for phase, blocks_done, and tuples_done while CREATE INDEX CONCURRENTLY runs in another backend.
Compare idx_blks_hit with idx_blks_read in pg_statio_user_indexes to compute a per-index cache hit ratio and spot indexes missing the shared buffers.
pg_trigger_depth() reports trigger nesting inside trigger functions and 0 outside, so re-entrant cascades can skip re-auditing the same row.
Hash passwords with pgcrypto crypt and gen_salt so every hash embeds its own salt, then verify candidates against the stored hash.
Issue API tokens from cryptographically random bytes with gen_random_bytes, stored as hex with a unique constraint.
Sign webhook payloads with pgcrypto hmac and verify by recomputing the keyed digest, which fails the moment payload changes.
Read leaf density and fragmentation from pgstatindex: freshly built btrees sit near the 90 fillfactor and decay upward in deleted pages as rows churn.
CASE maps each weight to its tier rate and charges only the portion inside that band, avoiding the full-amount-at-top-tier mistake.
RAISE ... USING attaches a custom ERRCODE and HINT to a business error, letting callers catch the exact SQLSTATE instead of parsing message text.
A recursive CTE levels every task one past its deepest dependency, so max(level) per task yields a safe execution order for the pipeline.
Evaluate stored expression trees bottom-up: recursion resolves operand leaves first, then operators consume their children results.
Walk a btree by value with a recursive CTE so a low-cardinality DISTINCT seeks each value instead of scanning every index entry.
Expand recurring calendar events with a recursive CTE that advances each rule by its own step interval until the end date.
Carry (root, member) pairs through a recursive CTE and aggregate outside it, because Postgres rejects aggregates over the recursive reference.
regexp_replace rewrites text with anchored patterns and masks digit runs; without the g flag only the first occurrence ever changes.
REVOKE strips granted privileges while the role itself survives; has_table_privilege verifies exactly which rights remain after each revoke.
After deletions leave playlist positions with gaps, ROW_NUMBER over the remaining order feeds an UPDATE through a CTE to restore 1..N.
Multiply a running series without a PRODUCT aggregate: take logs, sum them over the window frame, then exp the total back into a running product.
A scalar subquery may return at most one row; a second matching row aborts the whole statement with a cardinality error.
With ANALYZE, a highly selective equality predicate plans an index scan while a half-table range predicate plans a sequential scan.
Tag title and body lexemes with setweight A and B, concatenate the tsvectors, and let ts_rank score title hits above body hits by default.
A small LIMIT keeps only the top rows in an in-memory heap, which EXPLAIN ANALYZE labels top-N heapsort, instead of fully sorting the table.
split_part pulls the Nth field from a delimited string, counts negative indexes from the end, and returns an empty string past the last field.
sum(interval) totals durations across rows and stays correct past 24 hours; justify_interval re-splits the pile into days plus hh:mm.
TABLESAMPLE BERNOULLI flips a coin per row while SYSTEM samples whole pages; REPEATABLE seeds both so repeated runs return the exact same rows.
Adding or subtracting an interval from a time wraps on the 24-hour scale: 22:00 plus 8 hours is 06:00, and time values alone cannot say which day.
The same literal stores differently: timestamp without time zone keeps the wall clock verbatim, timestamptz normalizes to UTC and renders per session zone.
to_timestamp(text, format) is the inverse of to_char: quoted literals, ignored trailing input, missing fields filled with minimum values, mismatch raises.
Encode the state machine as a BEFORE UPDATE trigger that raises a real error for illegal status transitions, whichever client submits the UPDATE.
Gate a trigger with WHEN (OLD IS DISTINCT FROM NEW) so equal-value updates never queue the trigger, while real changes fire it once per row.
Feed ts_stat any query returning one tsvector column to rank lexemes by total occurrences and document coverage, hunting stop-word candidates.
INCLUDE columns travel in a unique index leaf without joining the key: uniqueness checks skip them while covering reads still qualify for an index-only scan.
Rank upcoming birthdays with a modulo month cycle so December and January sit adjacent instead of being split by the calendar year.
Assign two columns in one statement with SET (a, b) = row expression, using either a value row constructor or a correlated sub-SELECT snapshot.
Target ON CONFLICT at the exact lower(email) expression; naming the bare column cannot infer the unique expression index and fails.
varchar(n) rejects overlong values at write time while text stays unlimited; business caps belong in a CHECK on char_length, not the column type.
Parse user-typed search strings with websearch_to_tsquery, which tolerates quoted phrases, OR, and -excluded terms without failing.
Window aggregates keep NULL semantics: COUNT(*) over a partition counts every row while COUNT(col) skips NULLs frame by frame.
Postgres 19 lets lag and lead skip nulls inside the frame with IGNORE NULLS, so gaps read as the last real observation instead of literal nulls.
Without ORDER BY every row in the partition is a peer and the default frame is the whole partition, so aggregates report totals instead of running sums.
Without PARTITION BY, rank() orders the entire table; adding it restarts ranking inside each group, fixing silently wrong per-team standings.
RANGE frames with an offset need exactly one ORDER BY column; two ordering keys are rejected, while one timestamp column gives true time frames.
A frame bounded by ROWS ... FOLLOWING looks only at rows after the current one, turning window aggregates into backlog and next-job lookahead.
Build XML fragments with xmlelement and xmlattributes, then xpath pulls attributes and child text out of each stored document.
array_positions returns the subscripts of all occurrences of a value in a one-dimensional array, using IS NOT DISTINCT FROM so NULL can be searched too.
Attach the most recent price at or before each trade with a timestamp-filtered LEFT JOIN plus DISTINCT ON, and the ROW_NUMBER window form as an alternative.
Roll up integer permission masks per team with BIT_OR as the union of grants and BIT_AND as what every member shares, then test single bits with an & mask.
Create two identical B-tree indexes differing only in deduplicate_items and compare pg_relation_size, showing how PG13 packs duplicate TIDs into posting lists.
Create one GIN index over an array column plus a scalar text column with the btree_gin operator classes, so containment and equality share a single index.
Count business days between two dates with generate_series over the day range and an ISODOW filter, keeping Monday-Friday and dropping weekends.
The citext extension compares through lower(), so duplicates collapse case-free and PRIMARY KEY uniqueness ignores case without a functional index.
Package related fields into a composite type, build values with ROW(...), and read them back with (col).field — the parentheses are required to disambiguate.
Write one order header and its line items in a single statement by chaining INSERT RETURNING through a data-modifying CTE for atomic parent-child inserts.
currval and lastval read session-local sequence state: currval needs that sequence drawn via nextval in this session, lastval needs any nextval at all.
Run CREATE TABLE and INSERT inside a transaction and roll it back: the table vanishes, proving DDL joins the same transactional story as DML.
Suspend audit triggers with ALTER TABLE ... DISABLE TRIGGER for a bulk load, then re-enable; the USER form spares constraint triggers guarding foreign keys.
ALTER TYPE RENAME VALUE relabels an enum member without touching its sort position, and both a missing old value and an already-used new name fail outright.
Filter outer rows with EXISTS (SELECT 1 ...) as a semi join: matching rows prove existence and stop early without duplicating outer rows like an inner join.
MATCH PARTIAL would let mixed-null composite FKs satisfy the constraint, but PostgreSQL rejects it at transform with "MATCH PARTIAL not yet".
A PL/pgSQL FOR loop can walk a SELECT result row by row: the loop target is assigned each row, and EXIT stops early while keeping the last row readable.