VACUUM Reclaims Dead Tuples After Updates
Updates and deletes leave dead tuples behind: observe them in pg_stat_user_tables, reclaim space with VACUUM, and tighten the autovacuum scale factor.
Page 6 of 7
Updates and deletes leave dead tuples behind: observe them in pg_stat_user_tables, reclaim space with VACUUM, and tighten the autovacuum scale factor.
Attach WITH CHECK OPTION to a view so inserts and updates through it must satisfy the view WHERE predicate instead of writing invisible rows.
Attach FILTER to aggregate window functions so one partition pass produces the running total and the refunded subtotal side by side.
Window functions evaluate after WHERE, so filtering on row_number output requires numbering rows in a CTE first, then selecting rn = 1 outside.
SUM over ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING walks forward to the partition end, producing remaining budget beside the usual running total.
Force sorts to spill to disk under a tiny work_mem, read the Sort Method line in EXPLAIN ANALYZE, and let an index on the sort key avoid the sort entirely.
Add a NOT NULL column with a constant default on PostgreSQL 11+ without rewriting the table, verified from pg_attribute atthasmissing metadata.
Watch the planner AND two single-column indexes with BitmapAnd for AND-ed predicates, and why a composite index replaces the merge with one scan.
Physically reorder a table with CLUSTER and watch pg_stats.correlation move toward 1, which makes range scans cheaper for the planner to choose.
Compare composite foreign keys with MATCH SIMPLE and MATCH FULL: only the full variant rejects rows that reference a parent with half-null keys.
CREATE STATISTICS (ndistinct) makes ANALYZE collect combined distinct counts for correlated columns, so the planner stops multiplying per-column selectivities.
Declare a foreign key DEFERRABLE INITIALLY DEFERRED so child rows can be inserted before their parents and the check happens once at COMMIT.
Give statuses a fixed lifecycle with CREATE TYPE AS ENUM: ORDER BY follows declaration order, comparisons rank labels, and ADD VALUE appends later states.
Show why LAST_VALUE returns the current row under the default frame and how ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING restores the real tail.
Read parallel plans in EXPLAIN ANALYZE: a Gather node over Parallel Seq Scan leaves, with Workers Planned and Workers Launched on large tables only.
Index infix LIKE searches with the pg_trgm extension: a GIN index on gin_trgm_ops serves %son% patterns and similarity ordering that a plain btree cannot.
Walk a reporting hierarchy whose dirty rows form a loop; the PostgreSQL 14 CYCLE clause flags rows that close a cycle and stops expanding them.
Let the database stamp each recursive CTE row with a breadth-first sequence via SEARCH BREADTH FIRST, so level-order output needs no manual depth bookkeeping.
Fit a trend line inside one aggregate pass: regr_slope and regr_intercept return the least squares line, and regr_r2 reports how linear the relationship is.
Rebuild a bloated index with REINDEX CONCURRENTLY: writes keep flowing while the _ccnew replacement builds, and a failed run leaves an INVALID index to drop.
Enforce tenant isolation in the database with row level security: ENABLE plus FORCE ROW LEVEL SECURITY and a policy that compares tenant to a session setting.
Concatenate group members into one delimited string with STRING_AGG, ordering inside the aggregate and narrowing inputs with FILTER.
Empty tables fast with TRUNCATE RESTART IDENTITY, see why a foreign key reference blocks it, and use CASCADE plus a transaction for a safe purge.
Bucket amounts into equal-width ranges with WIDTH_BUCKET, which keeps out-of-range values in buckets 0 and n+1 rather than dropping them.
Put equality columns before range columns in a composite index; a range predicate on the first column blocks later columns from being index-scanned.
Add INCLUDE columns to an index so the planner answers from the index alone with an index-only scan and never visits the table heap.
Build an index while the table stays writable with CREATE INDEX CONCURRENTLY, then clean up the INVALID leftovers a failed build can leave.
Compare each row to its partition average with AVG OVER (PARTITION BY): window aggregates keep every row and expose per-group deviation directly.
Define a check constraint once with CREATE DOMAIN and reuse it across columns; NULL passes, but any invalid email insertion fails loudly.
Index the lower(email) expression and repeat that exact expression in the query; comparing the raw column falls back to a sequential scan.
Leave free space on pages with fillfactor so updates that touch no indexed column stay on-page as HOT updates and skip index maintenance entirely.
Compute a column at write time with GENERATED ALWAYS AS ... STORED; reads pay no calculation and attempts to insert an explicit value are rejected.
Add grand totals next to detail rows with an empty OVER () window: aggregates without partition or order cover the whole result set.
Include tied rows as one unit with the GROUPS frame mode, so the peer count moves group by group instead of row by row like ROWS.
Let GENERATED ALWAYS AS IDENTITY own primary keys: plain inserts get sequence values, explicit ids need OVERRIDING SYSTEM VALUE.
Qualify for an index-only scan by selecting only indexed columns, then track Heap Fetches: pages not yet all-visible force heap visits until VACUUM.
Move expired rows into an archive atomically: a data-modifying CTE feeds DELETE RETURNING output straight into the outer INSERT.
Rank grouped totals in one pass because window functions are evaluated after GROUP BY and can order by aggregate expressions like SUM(revenue).
Walk a manager_id chain upward with a recursive CTE: anchor on one employee, join the next manager each step, stop when manager_id is NULL.
Compute each row's share of its partition and of the grand total by dividing by SUM() OVER with PARTITION BY and an empty window.
Treat NULLs as equal inside UNIQUE with NULLS NOT DISTINCT, so a nullable owner column cannot accumulate duplicate unowned rows.
List never-scanned indexes from pg_stat_user_indexes where idx_scan is zero, sized with pg_relation_size, before dropping anything that only slows writes.
Add a CHECK constraint online with NOT VALID so existing rows stay unscanned, then enforce them later with VALIDATE CONSTRAINT.
Force one-shot CTE evaluation with AS MATERIALIZED or allow inlining with AS NOT MATERIALIZED to control what the planner fuses into the outer query.
Rank rows as population shares with CUME_DIST and PERCENT_RANK, where tied rows receive identical values under the same window ordering.
Swap unique values between rows inside one transaction by declaring the UNIQUE constraint DEFERRABLE INITIALLY DEFERRED and checking at COMMIT.
Enforce no-overlap booking with an EXCLUDE USING gist constraint: btree_gist combines room equality with range && so conflicting inserts are rejected.
Show what ON DELETE CASCADE, RESTRICT, and SET NULL do to child rows, and why NO ACTION differs from RESTRICT by allowing DEFERRABLE checks.
Match index column directions to a mixed ORDER BY created_at DESC, id ASC so Top-N queries skip the Sort node entirely.
Name a window once in a WINDOW clause and reuse it with OVER w, appending frame clauses without repeating partition and order definitions.
Split ordered rows into near-equal buckets with NTILE(3) and NTILE(4); add a tiebreaker so equal keys land in stable buckets.
Aggregate time-ordered rows over a sliding RANGE frame with INTERVAL offset, where peer rows sharing a timestamp enter the frame together.
Serve LIKE 'prefix%' queries from a btree index by declaring the text_pattern_ops operator class, because collation-ordered indexes cannot.
Drop peers from window frames with EXCLUDE CURRENT ROW, EXCLUDE TIES, and EXCLUDE GROUP, keeping the current row where TIES does.
Rotate rows into columns with conditional aggregation — CASE inside SUM — so a variable number of rows becomes a fixed number of fields.
Guard nullable columns with COALESCE and NULLIF so blanks render as explicit defaults and divide-by-zero collapses to NULL instead of failing.
Walk a self-referencing tree table with a recursive CTE, carrying depth and path down the hierarchy and guarding against cycles.
Chain multiple CTEs for readable complex query decomposition in SQL reports.
Remove duplicate rows keeping the most recent version with window functions.
Find missing numbers in a sequence with window functions for data integrity checks.
Filter grouped results with HAVING after aggregation for group-level conditions.
Query and index JSONB columns with PostgreSQL operators for flexible schema storage.
Use MERGE or INSERT ON CONFLICT for atomic upsert without race conditions.
Handle NULL values safely with COALESCE and IS NOT DISTINCT FROM for correct comparisons.
Implement optimistic concurrency with a version column for conflict-free updates.
Traverse hierarchical trees with recursive CTEs for org chart and category navigation.
Compute running totals with SQL window functions for cumulative aggregation over ordered rows.
Compute multiple metrics in a single pass using conditional aggregation with CASE inside SUM for pivoted reporting.
Find the top N rows per group using a correlated subquery with a count of better rows for ranking.
Generate a contiguous date range using a recursive CTE for filling missing calendar gaps in time series analysis.
Remove duplicate rows keeping only the latest record per group using a window function row number filter.
Get the first and last non null values per group using window functions with ignore nulls framing.
Identify consecutive session groups using the gap and islands technique with row number difference for grouping.
Extract nested fields from JSONB columns using Postgres arrow and double arrow operators with path expressions.
Compare adjacent rows using LAG and LEAD window functions to detect anomalies between consecutive measurements.
Compute the exact median per group using the percentile_disc window function with a 0.5 fraction parameter.
Transform rows to columns for a monthly sales cross tabulation using conditional aggregation as a pivot technique.
Generate factorial numbers using a SQL recursive common table expression with a termination condition.
Compute a three period rolling average using SQL window functions with a sliding frame between preceding and following rows.
Compute period over period differences using the SQL LAG window function for sequential row comparison.
Query an employee manager hierarchy using a self join with multiple levels to flatten the organizational structure.
Update a row only when its version still matches, detecting concurrent modification through the affected row count.
Remove duplicate natural keys and keep only the most recent row using a window function and a delete, a common cleanup before adding a unique constraint.
Diagnose slow queries with EXPLAIN ANALYZE and BUFFERS, reading scans, join strategies, and actual row estimates.
Find missing values in an id sequence by comparing each row with the previous one, a common data-integrity audit query.
Read an EXPLAIN plan to confirm whether a query uses the intended index and where a sequential scan or sort is introduced.
Paginate with the seek method on a compound cursor, comparing plans against OFFSET to show why deep pages stay fast.
Detect missing intervals in time series with LAG over generated series, then backfill gaps by carrying the last known value forward.
Compare two nullable columns without nulls silently dropping rows from a WHERE clause, using IS DISTINCT FROM instead of not-equal.
Implement classic offset pagination with a single-pass window count, page metadata, and sane caps on depth and page size.
Paginate with a WHERE clause on the last seen key instead of OFFSET, keeping each page fast and stable as new rows arrive.
Contrast string-interpolated SQL with parameterized statements, allowing safe dynamic ORDER BY through whitelisting.
Pivot monthly revenue by category using conditional aggregation, generating column lists dynamically for any date range.
Turn row values into columns with conditional aggregation, producing a wide report without a dedicated pivot operator.
Serialize critical sections across application instances with advisory locks, scoping by key and releasing on session end.
Index append-only time series with tiny BRIN blocks, comparing size against B-tree for range scans over billions of rows.
Aggregate rows into nested JSONB documents with jsonb_build_object and jsonb_agg, shaping API responses directly in SQL.
Query JSONB documents with containment operators backed by a GIN index, comparing jsonb_path_query for complex predicates.
Fetch the latest N rows per group with a LATERAL join driving an indexed subquery per outer row, avoiding giant windows.
Accelerate dashboards with materialized views, refreshing concurrently without blocking readers and tracking data staleness.