Why DROP INDEX Fails On Constraint Indexes
A unique constraint owns a same-named index: DROP INDEX fails with a dependency error, while DROP CONSTRAINT removes both in one step.
Page 4 of 7
A unique constraint owns a same-named index: DROP INDEX fails with a dependency error, while DROP CONSTRAINT removes both in one step.
Enforce uniqueness for an undirected pair: a unique index on LEAST and GREATEST normalizes both directions to the same key before comparing.
Multi-argument unnest in the FROM clause expands parallel arrays of labels and values, turning one wide row into one row per month without UNION ALL repetition.
Guard upsert replay with DO UPDATE SET plus a WHERE that compares target values against EXCLUDED so unchanged rows are skipped and dead tuples avoided.
Pull only rows past a stored watermark with an incremental sync query, then advance the watermark so repeated runs move forward without reprocessing.
Compute a weighted average as SUM(value * weight) over SUM(weight), because averaging already-averaged group values weights small samples the same as big ones.
Unpack session intervals into enter and leave events, then window-sum the deltas to find the moment with the most simultaneous visitors.
A LEFT JOIN before GROUP BY keeps categories with no matching rows, and COUNT over the joined column reports 0 — filters must move into ON or they vanish.
Count subsets in one pass with the FILTER clause on aggregates, replacing repeated CASE expressions and extra scans of the same rows.
Persist server settings with ALTER SYSTEM, reload postgresql.auto.conf, inspect pg_settings, and reset a value.
Collect group values in encounter order with array_agg and an inner ORDER BY, preserving sequence that plain aggregates lose.
Create a bloom index over equality-filtered columns, inspect its definition, and see why range predicates cannot use it.
Define a parent CHECK with NO INHERIT so child tables accept rows the parent rejects, then compare inherited and local rules.
Attach documentation to tables, columns, and indexes with COMMENT ON, then read it back from the system catalogs.
Generate every grouping subset in one CUBE query, separate real nulls from rollup nulls with GROUPING, and compare with GROUPING SETS.
Run anonymous procedural code inline with a DO block, using an integer FOR loop and RAISE NOTICE to emit progress lines from a psql session.
Convert bytea values to hex and base64 with encode, parse them back with decode, and verify round trips and byte lengths.
Compare FOR UPDATE with FOR NO KEY UPDATE and FOR KEY SHARE, then check which row lock modes still block foreign key checks.
Build a gap-free calendar with generate_series and LEFT JOIN daily totals, so missing dates report zero instead of disappearing.
Store IPv4 and IPv6 subnets in inet columns, then use containment and overlap operators to match addresses.
Compare INTERSECT and INTERSECT ALL on duplicate rows, combine them with EXCEPT ALL, and confirm multiset counts in a grouped query.
Constrain a jsonb column with the IS JSON OBJECT predicate and test VALUE, ARRAY, SCALAR, and unique-key variants.
Insert into jsonb arrays and objects with jsonb_insert, choose before or after the target index, and persist the change with UPDATE.
Aggregate grouped rows into keyed JSON objects with jsonb_object_agg, expand them again, and deduplicate repeated keys first.
Create a GIN index with jsonb_path_ops, query containment with @>, and compare it with jsonb_ops for key-existence filters.
Filter JSONB documents with jsonb_path_query and its variants, using JSONPath predicates, arrays, first matches, and bound variables.
Map jsonb documents onto a composite type with jsonb_populate_record, including missing keys and ignored extras.
Remove null-valued object fields recursively with jsonb_strip_nulls and confirm that array elements keep their shape.
Turn a JSONB array into typed rows with jsonb_to_recordset, then query nested fields and arrays as ordinary relational columns.
Match a column against several patterns at once with LIKE ANY and ILIKE ANY, including patterns supplied by a subquery.
Compose a multi-stage query as named CTE layers — filter, deduplicate, then aggregate — so each stage reads independently and later stages stay simple.
Use PostgreSQL's column-list ON DELETE SET NULL so a composite foreign key clears only the reviewer column and keeps its order.
Import explicit IDs into GENERATED ALWAYS identity columns with OVERRIDING SYSTEM VALUE and contrast it with user value.
Score how each row ranks with percent_rank, including how ties collapse to the same percentile inside a window ordering.
Load a table or index into shared_buffers with pg_prewarm before benchmarking, so the first measured run does not pay the cold-cache disk read cost.
Compare sequential and index scan counts per table in pg_stat_user_tables, exposing which tables the planner reads by index and which it scans end to end.
Handle errors inside a PL/pgSQL EXCEPTION block: the block runs as a subtransaction, so failed statements roll back without aborting the caller.
Unquoted identifiers fold to lowercase while quoted identifiers keep their exact spelling, so mixed-case quoted names need quoting in every later reference.
Open read-only transactions that reject writes and row locks, then reset the session default after reporting queries finish.
Extract capture groups with regexp_matches, return every match with the g flag, and index the resulting text array.
Wrap a parameterized query in RETURNS TABLE so callers can select from it and join or aggregate the result like a view.
Grant one role to another so privileges flow through membership, and control whether members inherit automatically or must SET ROLE first.
Aggregate sales with ROLLUP to get region and month subtotals plus a grand total, then mark total rows with the GROUPING function.
Compare row constructors directly to express composite key ranges, paginate by tuple order, and match multiple keys with IN.
Grant a function owner privileges with SECURITY DEFINER, pin search_path against hijacking, and restrict execution to one role.
Run SERIALIZABLE transactions that can fail with SQLSTATE 40001, and retry the whole unit of work on serialization conflicts.
Defer a unique constraint with SET CONSTRAINTS, shift every seat number in one transaction, and validate before commit.
Use statement-level triggers with transition tables to audit an entire multi-row UPDATE once, comparing old and new rows in a single insert.
Build highlighted search snippets with ts_headline, websearch_to_tsquery, and custom StartSel and StopSel markers.
Rank matches with ts_rank and ts_rank_cd, weight title above body, and combine ranking with a GIN index on a generated tsvector column.
Run a two-phase commit with PREPARE TRANSACTION, then finish it from another session with COMMIT PREPARED or ROLLBACK PREPARED.
Swap an archive table in as a partition with ALTER TABLE ATTACH PARTITION and detach it back out, moving whole datasets without copying rows.
Default ATTACH scans the new table to prove it satisfies the bounds; a pre-checked CHECK constraint lets PostgreSQL skip that validation scan.
Bucket timestamps into fixed-width strides with date_bin anchored at an origin, where date_trunc can only align to calendar units.
Delete the rows a grouped subquery selects with DELETE FROM ... USING, pruning expired sessions of over-limit users in one statement.
EXCEPT ALL keeps duplicate multiplicities, so a multiset difference reports how many copies of each row disappeared between two loads.
Diff two row snapshots with EXCEPT in both directions: rows only in the old load are removals, rows only in the new load are additions.
Combine scalar equality with an integer-range operator in one EXCLUDE USING gist constraint so adjacent booking slots may touch but never overlap.
Scope an exclusion constraint with WHERE so cancelled bookings stop blocking new ones while active overlaps still fail.
Point at the first row of each partition with first_value, and keep the current row intact — unlike aggregate functions that collapse rows.
Clamp numbers into bounds with GREATEST and LEAST: chain both for a range clamp; PostgreSQL ignores NULL inputs, returning NULL only when all are NULL.
Use a leading-column index then sort the remainder: the plan shows an Incremental Sort node instead of a full Sort when the prefix is presorted.
Turn one JSON object per row into key/value pairs with jsonb_each_text, then filter or aggregate pairs that columns cannot express.
Update nested JSON paths with jsonb_set: provide the path array, the new value, and control whether missing keys get created.
justify_interval folds raw interval components into days, hours, and minutes so a computed duration prints as a stable single unit set.
Cap how long ALTER TABLE waits for its access-exclusive lock, so a queued migration fails fast instead of stalling every query behind it.
Build date and interval values from integers with make_date, make_timestamptz, and make_interval instead of fragile string parsing.
Feed a Merge Join with pre-sorted inputs: when both sides have matching index order the planner merges streams in one pass without a hash table.
Store non-contiguous slots in one multirange value: overlaps merge on construction, containment and intersection work across all segments.
The SQL-standard OVERLAPS predicate compares two (start, end) interval pairs with half-open semantics, no range types required.
Enforce one active row per key with a partial unique index: uniqueness applies only inside the WHERE predicate, history rows stay unlimited.
CREATE INDEX on a partitioned parent builds and attaches a child index per partition, or defers with ON ONLY until every partition attaches.
enable_partitionwise_join lets the planner pair up partitions and join per partition when both tables are partitioned on the join key.
Ordered-set aggregates interpolate or select: percentile_cont can return values that never occurred, percentile_disc always returns a real row value.
Compare octet_length and pg_column_size on a ~6KB incompressible column: the value goes out of line uncompressed and the heap row keeps only a pointer.
Rank real workload queries by total time with pg_stat_statements: enable the extension once, then read normalized call counts and timing.
After five EXECUTEs the planner may switch a prepared statement from custom to generic plans; pg_prepared_statements exposes the counters.
Value-offset RANGE frames measure distance on the sort key itself, so rows within 5 units of the current value share one frame.
Cap runaway recursion with a depth counter in the recursive term: rows past the cap stop propagating, bounding the walk on bad data.
Split a table footprint with pg_table_size, pg_indexes_size, pg_total_relation_size, and per-fork pg_relation_size to see where bytes really go.
A window ORDER BY with tied keys uses the default RANGE frame, so peer rows enter the frame together and the running total jumps instead of ticking.
Split compound identifiers like partition-host-index with split_part, and reach fields behind the first or last separator with negative indexes.
CREATE TABLE LIKE with INCLUDING ALL copies defaults, constraints, and indexes, giving staging tables the parent guarantees.
Resolve a table name to an OID with to_regclass: unknown names return NULL instead of raising, enabling guard clauses in scripts.
Point two FOREIGN KEY columns at the same parent table and give each a role name plus its own ON DELETE behavior, so sender and receiver stay distinct.
Run one UNION ALL query where each source subquery keeps its own ORDER BY and LIMIT, so per-table top rows are computed before fanning out.
Aggregate rows in a grouped subquery and join it in UPDATE ... FROM, so per-customer totals land in one deterministic statement.
Adding one month clamps to the month's last day, so Jan 31 becomes Feb 28 and repeated monthly arithmetic drifts unless each cycle uses a fixed base.
Migrate column types with ALTER COLUMN TYPE and a USING expression that converts existing values, so old rows survive the new domain.
Since Postgres 12 ADD VALUE may run inside a transaction, but the new enum label stays unusable until commit; migrations probe pg_enum for idempotency.
After a bulk load pg_class.reltuples still reports the old estimate, so EXPLAIN rows go wildly wrong until ANALYZE re-samples the table.
Compare one value against a whole list with ANY and ALL: = ANY mirrors IN, <> ALL excludes a set, and subqueries can supply the operand.
PostgreSQL 16 ANY_VALUE picks an arbitrary non-null value per group, so wide GROUP BY queries stop failing with the must-appear-in-GROUP-BY error.
Constrain array columns with CHECK using cardinality, = ANY element tests, and array_position blocklists — no subqueries are allowed in CHECK.
Mutate array columns in place with the || append, array_remove, element assignment by index, and array_cat merges inside single UPDATE statements.
Index a tag array with GIN so && overlap and @> containment filters resolve in the index instead of scanning every row.
Sort results by the id order an application already chose: array_position returns each id's index in the list, and NULLS LAST decides where unknown ids land.
The same operator turns timestamptz into a zone local wall clock and turns a bare timestamp into an instant, with DST handled by IANA rules.
An AFTER row trigger serializes each inserted, updated, or deleted row with to_jsonb, tagging TG_OP and table name so replay never depends on column lists.
Normalize swapped range bounds with BETWEEN SYMMETRIC so user-supplied min and max in either order still match, unlike plain BETWEEN which returns nothing.