jsonb_array_elements_text Unnests JSON Arrays
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.
Page 11 of 50
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.
Hoist a discriminant check into a const boolean once and every later branch inherits the narrowing — no repeated event.kind comparisons.
Gate a staged startup behind a one-shot barrier: each service connects at its own speed and every continuation resumes only after all parties arrive.
Try mirrors in order and keep the first success: failures accumulate into an attempts report, so a final miss lists every reason.
Wire beforeunload to unsaved form state so the browser asks before discarding edits, using preventDefault plus returnValue per current guidance.
ES2022 class fields create own properties — TypeScript rejects a subclass field over a base accessor (TS2610), so route writes through assignments instead.
Dismiss a popover on outside clicks by asking popover.contains(target) instead of re-querying the DOM, keeping trigger clicks inside the guard.
Read event.composedPath to recover the real shadow-DOM propagation path when retargeting makes event.target report the host element instead.
const preserves literal types but let widens them to string, so union-typed parameters reject the widened value until an annotation stops the widening.
Open a custom menu at the pointer, then clamp its box with Math.min and Math.max so it never spills past the viewport edges.
Type document.createElement through the tag-name map: canvas, a, and tr return their specific element interfaces while unknown tags stay HTMLElement.
Create SVG nodes with createElementNS so the tag-name map returns SVGRectElement and SVGCircleElement directly, making attribute APIs type-check without casts.
Type the payload once with CustomEvent<T> so dispatch and listeners share the same detail shape, then destructure fields without manual checks.
Gate rendering on document.fonts.ready, request specific faces with fonts.load, and probe availability synchronously with fonts.check.
Direct casts between shapes with no overlap fail with TS2352; routing through unknown works, but a real guard beats a double assertion.
Reorder list items with native drag events: draggable rows, a dragover preventDefault to allow drops, and a drop handler that moves the task in place.
Let a custom element join form validation by attaching ElementInternals: set the submitted value and drive checkValidity with setValidity.
Model absent versus explicitly undefined option fields: under exactOptionalPropertyTypes an optional property rejects undefined unless the union allows it.
Call focus({ preventScroll: true }) for keyboard navigation so focus moves between panes without scrolling the viewport away from the reader.
Pass an object with a handleEvent method to addEventListener: this binds to the listener instance and one object can serve many elements.
Await img.decode() before revealing an image so the DOM swap happens only when the bitmap is paint-ready, with a fallback when decoding fails.
Open a date input's browser picker on click, guarding TypeError for pickerless input types and keeping the call inside a user gesture.
Collect every key across a union of shapes with a distributive conditional - plain keyof only exposes the keys every member shares.
Run versioned migrations in order with an idempotency check: a second pass applies nothing, and applied versions are recorded in state.
Map each tag to a Set of ids in an inverted index, so tag lookups, unions across tags, and removals that prune empty buckets all stay cheap.
Feature-detect navigator.share, validate payloads with navigator.canShare before calling it, and await the promise the share sheet resolves.
Index reads become T | undefined under noUncheckedIndexedAccess: guard array and Record lookups explicitly and narrow without assertions.
Numeric index signatures type array-like records by position, while runtime keys stay strings — Object.keys returns string keys even for ids.
Define recursive tree types where children use the node type itself, then fold every subtree with one generic combine function instead of ad hoc loops.
Keep one list item tabbable while arrow keys move focus between options, wrapping at the ends, the standard roving tabindex pattern.
Highlight the section the reader is in with IntersectionObserver and a narrow rootMargin band, then sync aria-current on the matching nav link.
Listen for scrollend instead of debounced scroll events: it fires once scrolling has fully settled, which is the right moment to append a page.
Open the OS file dialog from a click handler with showOpenFilePicker, feature-guard the API surface, and treat AbortError as a dismissed dialog.
A one-line mapped type flattens Defaults & Overrides intersections so hover tooltips and ExpectEqual comparisons show a single clean object shape.
Listen for slotchange on shadow-DOM slots and read assignedElements() so slot membership counters stay in sync with light-DOM nodes as they move.
Listen for the storage event to react to localStorage changes made in other tabs - the writing tab itself never receives the event.
Each class field needs an inline initializer, a constructor assignment, or an optional marker — the strict build rejects anything that could read as undefined.
Template literal index signatures type whole families of dynamic keys — CSS vars must carry the -- prefix and event keys only known on-suffixes.
A truthiness check drops falsy members like empty string and 0 from literal unions, but a plain number still includes zero — equality checks are required there.
Persist typed preferences through localStorage with an unknown-narrowing guard so corrupted JSON or wrong shapes fall back to defaults.