ALTER SEQUENCE RESTART WITH And CYCLE Bounds
Reset a PostgreSQL sequence with ALTER SEQUENCE RESTART vs RESTART WITH, inspect pg_sequences metadata, and toggle NO CYCLE to CYCLE wraparound.
Reset a PostgreSQL sequence with ALTER SEQUENCE RESTART vs RESTART WITH, inspect pg_sequences metadata, and toggle NO CYCLE to CYCLE wraparound.
Partition rows into multiple arrays in one GROUP BY via ARRAY_AGG FILTER (WHERE ...), wrapping outputs with COALESCE so empty matches stay {}.
Define a custom PostgreSQL aggregate using CREATE AGGREGATE with a state type, SFUNC, INITCOND, and FINALFUNC that works in GROUP BY and OVER frames.
Detect loops on multi-column graph keys with the PostgreSQL CYCLE clause, writing custom string flags and tracking hop counts via the path array.
Contrast NTILE bucketing against peer-aware CUME_DIST and interpolated PERCENTILE_CONT thresholds when latency samples share tied values.
Step timestamptz across spring-forward and fall-back DST boundaries in an explicit target zone using PostgreSQL 16 date_add and date_subtract.
Clean temporary tables, prepared statements, GUCs, and LISTEN channels with DISCARD ALL before returning pooled connections, outside transactions.
Declare a GiST EXCLUDE constraint DEFERRABLE INITIALLY IMMEDIATE so a transaction can defer checks and shift overlapping schedule slots safely.
Recompute stored GENERATED ALWAYS AS columns with DEFAULT on UPDATE, then run DROP EXPRESSION to turn the column editable without losing stored rows.
Combine overlapping ROLLUP and GROUPING SETS clauses with PostgreSQL 14 GROUP BY DISTINCT so duplicate subtotal rows collapse cleanly.
Keep tenant unrolled with partial ROLLUP while using multi-argument GROUPING(region, category) bitmasks to tell real NULLs from subtotal rows.
Build JSON payloads with PostgreSQL 16 JSON_OBJECT and JSON_ARRAY, handling NULL ON NULL vs ABSENT ON NULL defaults and WITH UNIQUE KEYS.
Aggregate rows into JSONB objects and ordered arrays using PostgreSQL 16 JSON_OBJECTAGG and JSON_ARRAYAGG with NULL handling and WITH UNIQUE KEYS.
Query JSONB with PostgreSQL 17 JSON_EXISTS, JSON_VALUE, and JSON_QUERY using PASSING variables, RETURNING types, and ON EMPTY/ON ERROR clauses.
Navigate nested JSONB with #> and #>>, test path existence with @?, and evaluate JSONPath boolean predicates directly using the @@ operator.
Avoid prefix/suffix corruption from LTRIM and RTRIM treating arguments as character sets; strip literal prefixes and suffixes with REGEXP_REPLACE.
Run a conditional PostgreSQL MERGE that skips unchanged rows via DO NOTHING, updates or inserts diffs, and returns merge_action() per modified row.
Compare canonically equivalent NFC and NFD Unicode strings with normalize() and enforce IS NFC NORMALIZED inside PostgreSQL CHECK constraints.
Index only failed jobs with CREATE INDEX ... INCLUDE (...) WHERE so error queue queries run index-only scans while healthy rows stay unindexed.
Merge group time windows into multiranges with range_agg and isolate shared overlap via range_intersect_agg across all rows in PostgreSQL.
Lockstep-zip heterogeneous set-returning functions with PostgreSQL ROWS FROM (...) WITH ORDINALITY, padding shorter streams with NULL safely.
Attach WITH (security_barrier = true) to PostgreSQL views so outer non-leakproof predicates cannot run ahead of row-hiding WHERE filters.
Deduplicate grouped strings with STRING_AGG(DISTINCT ... ORDER BY ...), and pre-dedup in a subquery when sorting by a non-aggregated column.
Convert timestamptz and naive timestamp against the current session TimeZone using PostgreSQL 17 AT LOCAL without hardcoding zone strings.
Apply batch stock changes via UPDATE ... FROM with a non-negative guard and emit previous, delta, and resulting counts in one RETURNING clause.
Contrast WITH LOCAL CHECK OPTION against CASCADED on stacked views to see when writes enforce parent view filters versus only the top view.
Compare ROWS and RANGE frames when ORDER BY contains NULL values: RANGE treats all NULL rows as peers while ROWS steps row by row.
Shred XML documents into typed relational columns with XMLTABLE, extracting attributes, defaults, NOT NULL checks, and FOR ORDINALITY numbers.
RENAME COLUMN and RENAME TO are metadata-only changes: they take an ACCESS EXCLUSIVE lock, rewrite no data, and leave views referencing the old name broken.
Construct fixed-shape arrays with array_fill, choosing each dimension length and optionally a non-1 lower bound per dimension.
CREATE CAST tells PostgreSQL how to convert between two types, with WITH/AS assignment or implicit context deciding which casts apply without an explicit ::.
Read and write session parameters with current_setting and set_config: missing_ok returns NULL for unknown keys, and is_local scopes writes to one transaction.
daterange folds inclusive upper bounds to next-day exclusive form, reports emptiness with isempty, and joins touching bookings with the -|- adjacency operator.
Remove the current row from its own window frame with EXCLUDE CURRENT ROW, so aggregate comparisons measure peers only and never the row being scored.
Read and flip individual bits with get_bit and set_bit on a bit column, packing boolean flags where the leftmost bit is bit 0.
INSERT ... SELECT maps the select list onto the target column list by position, so column names need not match but the order must.
Test dates, timestamps, and intervals with isfinite, which flags the infinity literals that stand in for open-ended ranges.
Update nested JSON documents with jsonb_set_lax, whose null_value_treatment decides whether SQL NULL becomes JSON null, a deleted key, or an error.
PostgreSQL % and mod() return a remainder carrying the dividend sign, so negative ids hash to negative buckets unless you wrap with mod(mod(x,n)+n,n).
Use the money type for currency that stays exact through addition and SUM, while division by an integer truncates and numeric mixes need casts.
NULLIF(a, b) returns NULL when its arguments match, so empty form fields collapse to real NULLs and one COALESCE covers blank and missing alike.
Inspect pg_matviews to see every materialized view, its owner, and refresh state, then compare with pg_views for plain views.
Read pg_stat_user_functions to see how often each PL/pgSQL function runs and how much time it consumes, gated by track_functions.
pg_typeof prints the real type of any expression, exposing literal surprises like unknown-typed strings and numeric results from floor(numeric).
Under READ COMMITTED, an UPDATE blocked by a concurrent writer rechecks its WHERE against the committed new version, so conditions can silently stop matching.
REPEATABLE READ pins one snapshot for the whole transaction, so re-reads return identical rows even after other sessions commit changes.
A FROM-less SELECT evaluates one row of constant expressions, the quickest way to probe function output, casts, and operator semantics.
SET ROLE changes the effective user inside a session, RESET ROLE returns to the login role, and privileges flip with each switch.
Match whole strings with SIMILAR TO, which keeps LIKE wildcards but adds POSIX alternation, repetition, and bracket classes — while the dot stays literal.
Split one delimited column into one row per token with string_to_table, from empty segments to a null_string that turns matching fields into NULL.
SUM(DISTINCT x) collapses equal values inside one aggregate, which silently shrinks totals when legitimate duplicates exist; dedup a known key instead.
Shrink arrays from the tail with trim_array, which trims only the first dimension of multidimensional input and returns an empty array when n reaches length.
Table-level reloptions override global autovacuum triggers for hot tables: fixed thresholds instead of size ratios, with RESET to fall back.
A stored generated column computes load from crates times unit weight, and a CHECK constraint validates that derived total on every write.
COPY ingests JSONL line by line into a jsonb column, keeping nested structure intact where row-wise CSV parsing would flatten or fail.
count(DISTINCT (user_id, day)) treats the row constructor as one key, separating unique pairs from plain row and column counts.
CREATE STATISTICS with dependencies and mcv records how strongly columns correlate, so the planner stops underestimating conjunctive filters on paired columns.
A foreign key can reference a partitioned table once its columns match a unique constraint that includes the partition key.
A filtered view is read-only until an INSTEAD OF trigger routes inserts into the base table, stamping the hidden column the view never exposes.
ISO week numbering moves the year boundary to the Monday containing January 1, so late December days can belong to the next year.
With work_mem tiny, a bitmap heap scan spills to lossy whole-page bits and EXPLAIN ANALYZE reports rows removed by the index recheck.
IN returns any-of matches; grouping joined tags and comparing HAVING count(DISTINCT tag) with the required count yields rows carrying every tag.
Collapse overlapping shift records into merged spans by sorting on start and tracking the running maximum end with a window function frame.
Target the conflict by constraint name with ON CONFLICT ON CONSTRAINT, pinning the arbitration to one explicit unique constraint.
ON CONFLICT (col) errors out when col only has a plain index; only a unique index or primary key gives the clause a constraint to arbitrate on.
pg_inherits lists every partition of a table; joined with pg_class it exposes partition bounds and the reltuples row estimates ANALYZE refreshes.
pg_settings exposes value, source, and context together, so you can tell session-tunable knobs from ones waiting on reload or restart.
pgp_sym_encrypt seals text into a bytea with a passphrase and pgp_sym_decrypt opens it; random session keys make identical plaintexts encrypt differently.
PL/pgSQL SELECT INTO STRICT raises no_data_found or too_many_rows on bad row counts, while the loose form silently takes the first row.
A recursive CTE walks nested jsonb children with jsonb_array_elements, tracking depth and path until every leaf array runs out.
Postgres 15 regexp functions split the work: regexp_count tallies hits, regexp_substr grabs the nth match, regexp_instr locates it, regexp_like decides.
On an unindexed column the planner seq-scans everything; Rows Removed by Filter in EXPLAIN ANALYZE shows how many rows the predicate discarded.
The tableoid system column identifies the physical partition holding each row, so queries can attribute and count rows per partition.
A BEFORE trigger recomputes the tsvector on title or body changes, keeping search hits in step with edits on the same statement.
unnest accepts several arrays at once and zips them row by index, padding shorter arrays with nulls so ragged inputs still expand to a clean table.
array_agg works as a window function: collect rows seen so far into a running array, or gather the one-preceding-to-one-following neighbors per row.
Pre-grant rights on tables and sequences a role will create later, then read pg_default_acl to see which default grants are registered.
bt_index_check verifies btree page invariants under an AccessShareLock without blocking writes; bt_index_parent_check digs deeper but takes a ShareLock.
SQL does not guarantee left-to-right evaluation of AND terms, so a guard like y <> 0 AND y/x > 1 can still divide by zero; CASE does evaluate in order.
array_remove deletes every element equal to the target and array_replace swaps each match; missing targets return the array untouched instead of erroring.
Reading beyond an array's bounds returns NULL, not an error; writing past the end of a one-dimensional array grows it, filling skipped positions with NULL.
AVG ignores NULL inputs, so its denominator is the non-null count rather than the row count; zero-fill with COALESCE only when that is the intent.
bigint stops at 9223372036854775807: one more overflows with an explicit out-of-range error (SQLSTATE 22003) instead of silently wrapping.
bool_or over a running window taints every later request in a session once a failure appears, and bool_and confirms the whole session stayed clean.
A btree index stores NULLs at its end, so a selective IS NULL predicate is pushed down as an Index Cond instead of a whole-table scan.
A btree index on (tenant_id, created_at) can serve created_at-only filters through skip scan on PostgreSQL 17, instead of scanning every leading-column range.
char_length counts characters while octet_length counts UTF-8 bytes, so multibyte labels diverge before any length limit or threshold is applied.
CHECK constraints re-validate on UPDATE as well as INSERT, so a row that inserted cleanly can still fail when columns change.
Stop a row from being its own parent with a same-row CHECK comparison; parent existence stays the job of a self-referencing foreign key.
Materialize ancestor-to-descendant pairs once into a closure table, then subtree and size queries become plain joins with no recursion.
Create an ICU nondeterministic collation at primary strength so equality folds accents, and the unique index treats jose and josé as one key.
GRANT SELECT on a column list keeps sensitive columns out of a role's reach, and has_column_privilege reports per-column access before queries run.
concat_ws skips NULL arguments and places separators only between non-empty values, while || collapses the entire expression to NULL.
CREATE TABLE AS clones column types and rows but carries no primary keys, defaults, or indexes; LIKE ... INCLUDING ALL is the full-structure clone.
Name computed CTE columns explicitly with a column list so two aggregates stop sharing the generated name sum and downstream CTEs join unambiguously.
Data-modifying statements in WITH execute exactly once to completion even when the primary query never references them; SELECT CTEs stay lazy.
Walk a prev_id pointer chain with a recursive CTE to reconstruct the revision history of a document, newest version first.
A WITH query hides any real table sharing its name: bare references read the CTE, and only a schema-qualified name reaches the actual table.
Volatile functions stop the planner from folding a CTE into the parent query, so two references to one random-valued CTE read the very same rows.
current_user tracks the role in effect while session_user keeps the login identity; SET ROLE swaps one, RESET ROLE restores, and both reads stay honest.