Outer Join Filter Placement ON Versus WHERE
Right-table filters belong in ON, not WHERE: a WHERE on the right side of a LEFT JOIN discards unmatched rows and silently turns it into an inner join.
Page 33 of 50
Right-table filters belong in ON, not WHERE: a WHERE on the right side of a LEFT JOIN discards unmatched rows and silently turns it into an inner join.
A unique index on a partitioned table must include every partition key column, because per-partition enforcement alone cannot guarantee global uniqueness.
Ordered-set aggregates cannot be window functions, so compute PERCENTILE_CONT per group in a CTE and join it back to attach the median to every detail row.
List the sessions waiting on locks with pg_blocking_pids joined against pg_stat_activity, then inspect pg_locks for the exact lock modes they are stuck on.
Promote a unique index built with CREATE INDEX CONCURRENTLY to a primary key with ADD CONSTRAINT USING INDEX, without rebuilding the table.
Declare range partitions so inserts route to the right child and queries with the partition key prune every other partition in the plan.
SEARCH DEPTH FIRST BY sets the sequence column to each row key path, emitting parents before children so trees unfold in pre-order without hand-managed state.
Split a delimited string with a recursive CTE that peels one token per iteration, and prefer the built-in string_to_table on PostgreSQL 14 and later.
Clean text with regexp_replace masking, substring FROM pattern extraction, and the ~ operator for regex membership tests inside SELECT lists.
Compare each reading against a trailing frame mean and stddev_samp that exclude the current row, flagging |z| beyond 3 with NULL-safe division.
Assign queue rows to worker slots by taking ROW_NUMBER modulo the worker count, with a partitioned variant that balances within each region.
ROW_NUMBER assigns arbitrary order among rows tied on the sort key; add a unique tiebreaker to make numbering, paging, and deduplication reproducible.
Track a cumulative high-water mark with MAX() OVER ordered frames, handling the empty first-row frame whose MAX evaluates to NULL.
Keep a plain index usable by moving interval math to the constant side: a function wrapped around the indexed column blocks the index scan.
Mark a point inside a transaction with SAVEPOINT so a failed statement can be undone with ROLLBACK TO SAVEPOINT while earlier work stays intact.
Unqualified table and function names resolve through search_path left to right, so switching schemas re-points the same queries.
Increment counters inside a single self-referencing UPDATE so concurrent transactions serialize on the row lock; the read-then-write pattern loses increments.
Identity and nextval never recycle numbers: rolled-back inserts leave permanent gaps, so count rows with count(*) instead of max(id).
Split event streams into sessions: LAG measures the gap since the previous click, a flag marks 30-minute gaps, and a running SUM assigns session numbers.
ALTER COLUMN SET DEFAULT shapes only future inserts: existing rows keep their values, and DROP DEFAULT just removes the expression without rewriting data.
SET LOCAL statement_timeout caps every statement inside the current transaction only, so pooled connections return to their default limit after COMMIT.
Adding a NOT VALID check and validating it first lets SET NOT NULL skip the table scan on PostgreSQL 12+, turning a long lock into metadata work.
Seed random() with setseed to replay the exact same sequence in a session, which makes generated fixtures and sampled comparisons reproducible.
Bulk imports with explicit ids leave the IDENTITY sequence behind; setval to max(id) via pg_get_serial_sequence makes the next insert safe again.
Create a partitioned-tree index with USING spgist (url text_ops) so constant-prefix LIKE queries hit the index, while infix patterns still need trigram support.
Build running event trails with string_agg as a window aggregate: ROWS frames accumulate from the partition start or a trailing window of recent steps.
Sample rows cheaply with TABLESAMPLE SYSTEM for block-level speed or BERNOULLI for row-level evenness, pinning the draw with REPEATABLE.
Session-private temp tables either survive commits (the default) or vanish with ON COMMIT DROP, which requires an enclosing transaction.
Plain boolean predicates drop NULL rows silently; IS TRUE and IS NOT TRUE make the treatment of unknown three-valued states explicit.
Map timestamps and numbers to display strings with format patterns — quoted literals, FM trimming, and currency via the locale setting.
A BEFORE UPDATE trigger rewrites NEW.updated_at inside the database, so every UPDATE gets a fresh timestamp even when the application forgets to set one.
Answer scheduling questions with tstzrange operators: && tests overlap, @> tests containment, and lower, upper, and upper_inc expose exact boundaries.
Combine a stored tsvector generated column with a GIN index so websearch_to_tsquery queries rank matching articles without scanning every row.
Add UNIQUE to the referencing column so a foreign key allows at most one child per parent, turning a one-to-many relationship into a true one-to-one.
Trade WAL writes for speed with CREATE UNLOGGED: faster inserts for rebuildable staging data, with the table truncated after a crash and never replicated.
Expand arrays with unnest WITH ORDINALITY so each element keeps its original 1-based position through a LATERAL join instead of losing order.
Window functions cannot appear in an UPDATE's WHERE clause, so rank rows in a CTE with ROW_NUMBER and flip status through UPDATE FROM past the newest order.
Sort batch upsert input by conflict key so concurrent transactions acquire row locks in the same order instead of failing with deadlock detected.
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.
Force subclasses to implement storage contracts with abstract members while concrete helpers on the base class keep shared logic in one place.
A generic combinator lifts an element-level predicate into a whole-array guard, so validate-then-use code narrows unknown[] to T[] after a single check.
Interleaving layout reads and writes forces synchronous reflows; batching all getBoundingClientRect calls before style writes keeps one layout per frame.
Compose behaviors onto classes with mixin functions whose Constructor parameter preserves the base constructor signature and stacks instance types.
closest walks the ancestor chain to the first matching selector, and its generic form hands back the concrete element class for dataset access.
ConstructorParameters and InstanceType recover constructor tuples and instance types from class definitions, so factories stay typed without repeated shapes.
customElements.define with observedAttributes turns HTML attributes into a typed config surface, and an HTMLElementTagNameMap entry types createElement calls.
Wire a confirm dialog with typed event listeners: cancel is cancelable, close(reason) sets returnValue, and querySelector narrows type and null in one generic.
Naked type parameters in conditional types evaluate each union member and rebuild the union; tuple-wrapping the parameter disables the split.
element.animate drives keyframes from script — a horizontal shake on failed validation — with a finished promise that resolves when the run ends.
TypeScript 5.5 infers type predicates from filter callbacks whose returned expression narrows the element, so results stay narrowed without hand-written guards.
Generator signatures declare yield values, the return value, and next() arguments as three separate slots; for-of sees only the yields.
Generic type defaults supply sensible second arguments — Error for results, string cursors for pages — while explicit call sites can still override them.
Type one function parameter as Iterable<T> so arrays, Sets, Map views, and generators all flow through the same loop without per-type overloads.
Give one property a narrow read type and a wider write type: the setter accepts string or number while the getter always hands back a number.
Route single-page apps with typed history state: pushState stores a typed payload, and popstate reads it back with a null guard.
Index signatures accept any string key: reading an absent glyph yields undefined at runtime, so presence checks with in guard every lookup.
instanceof checks double as type guards: each branch sees the concrete element class with its own properties instead of the bare Element shape.
Intrinsic string types apply case transforms at the type level, so handler names and env keys derive from existing keys and renames propagate automatically.
Read and patch object properties through keys constrained by keyof, so wrong key names and mismatched value types both fail compilation.
matchMedia evaluates a CSS breakpoint once and pushes updates through change events, keeping JS layout decisions on the same query string as the stylesheet.
NoInfer pins type inference to one argument, so out-of-scope callback values fail compilation instead of silently widening the type parameter.
Object.keys returns string[] and loses the key union; a small keysOf generic restores keyof T so loop variables stay precisely typed.
Mark members that replace base-class implementations with override so accidental shadows and signature drift fail compilation under noImplicitOverride.
Derive wrapper arguments and return values from an existing function with Parameters and ReturnType, so a signature change flows through instead of diverging.
Accept Partial<RetryOptions> from callers and merge over Required defaults, so every field of the resolved options object is guaranteed present.
Return this from chainable methods so subclasses keep their own methods available: limit() can precede orderBy() and the types still line up.
Promise.allSettled never rejects as a whole: each result carries a status discriminant, narrowing to value on fulfilled and unknown reason on rejected.
Signatures that accept ReadonlyMap and readonly arrays expose views without mutation methods, so internal state stays writable while callers stay read-only.
Type a lookup table as Record over a union so a missing or extra plan is a compile error, and derive the key list from the table instead of retyping it.
A recursive mapped type collects every leaf dot path of a nested config, and a readPath helper typed over those paths makes invalid keys a compile-time error.
Type methods with an explicit this parameter so detached calls fail compilation, and bind() restores the context instead of silently losing state.
Keep type-only imports erased from the runtime output with import type, while value imports stay real and usable at execution time.
A listener helper keyed by HTMLElementEventMap narrows the callback event type from the event name and returns an unbind function for exact cleanup.
Annotate type parameters with in and out to turn silent bivariance into compile errors, before a wrong-direction assignment fails only at runtime.
Assign functions that return anything to a void-typed callback contract; the value is simply ignored, while a void function cannot fill a typed slot.
Store document.activeElement when a widget opens and restore focus to it on close, so keyboard users return to the trigger instead of the body.
@ts-expect-error marks a line that must fail to compile, so a fixed bug or a loosened type turns the stale directive itself into a build error.
Read resolved styles and custom properties with getComputedStyle; values arrive as strings, so parse numbers yourself before writing scaled values back.
Read number inputs with valueAsNumber instead of parsing .value by hand; empty or invalid fields yield NaN that Number.isNaN can catch before math.
Interfaces extend object shapes and merge across declarations; type aliases compose unions and intersections, and each side covers jobs the other cannot.
Optional properties let the whole key go missing, while a required prop of type T or undefined must exist; in checks and spreads tell the two apart.
Pass an explicit accumulator type to reduce when the initial value cannot carry it, so never[] widening is caught and Record or Map builders type-check.
Read a select through value, selectedIndex, options, and selectedOptions; programmatic value assignment fires change just like user selection.
Chunk CPU-heavy loops and await a setImmediate between slices so pending callbacks interleave and the process never blocks for the whole run.
structuredClone copies data by structure: the generic result still claims T, but class methods and prototypes are gone unless you reattach them.
Call signal.throwIfAborted() at stage boundaries so a cancelled pipeline stops between steps and surfaces rejection as AbortError, not wasted computation.
Derive timer handle types with ReturnType<typeof setTimeout> so one codebase compiles against both the DOM number and the Node Timeout object.
Coordinate lock-free handoff with atomic CompareAndSwap, where one goroutine wins the swap and concurrent counters retry until their write lands.
Stage writes in a same-directory temp file then os.Rename it over the target, so readers see the old or the new content and never a partial write.
A send to an unread unbuffered channel parks its goroutine forever — count them with runtime.NumGoroutine and cap the channel to let senders finish.
Struct fields marshal in declaration order while map keys always come out sorted, so reproducible payloads and hashes choose their carrier deliberately.
Decode optional fields into pointer types so missing or null JSON reads as nil instead of the zero value, with omitempty dropping nil fields on marshal.
Carry timestamps in encoding/json through time.Time fields, which parse and emit RFC3339 strings automatically, with time.Parse validating raw stamps.
Check payloads with json.Valid, strip whitespace with Compact, and re-indent with Indent — shaping raw JSON without building a decode tree.
Delete map entries during range safely — Go skips removed entries instead of crashing — and delete() on a missing key is a documented no-op.