Parse Key-Value Pairs With split_once
split_once cuts at the first delimiter and returns Option of two borrowed slices, while rsplit_once cuts from the right for URLs and paths.
Page 32 of 50
split_once cuts at the first delimiter and returns Option of two borrowed slices, while rsplit_once cuts from the right for URLs and paths.
Count word frequencies by feeding split_whitespace into a HashMap entry, then rank the aggregated pairs with a tie-broken sort for reproducible output.
Bound how many pieces splitn produces so the final piece keeps the untouched remainder, and use rsplitn to slice from the right edge instead.
Read stdin in a loop with read_line, clear and reuse one buffer, treat EOF as zero bytes, and match the parse Result so bad input retries instead of panicking.
Indexing a &str by bytes panics off char boundaries; get returns None instead, and is_char_boundary backs a safe truncation helper.
Choose split_terminator over split when a trailing separator should end the record, not start an empty one — the classic newline-difference.
Watch the plus operator move the left String into the result, and switch to format! or push_str when the original value must stay usable.
Drop unwanted chars from a String in place with retain: char-safe iteration, no new allocation, and the original buffer is reused across passes.
Preallocate with with_capacity, append with push_str, and reserve headroom so string building runs in amortized constant time without repeated reallocation.
strip_prefix and strip_suffix return Option of the remaining borrowed slice, so unmatched input becomes None instead of a silently wrong string.
Two mutable borrows of different fields coexist because the borrow checker proves they are disjoint, while a whole-struct method would collide.
Use take_while_inclusive when the item that fails the predicate is itself meaningful — the iterator stops after yielding the boundary element.
thread_local! gives each thread its own RefCell-backed value, so counters started in a spawned thread begin from zero instead of sharing main's state.
Move owned data into thread::spawn closures, then recover each result through join, which also surfaces worker panics as Err instead of crashing the caller.
try_fold takes a closure returning Result: the first failing element aborts the whole fold, while plain fold has no early-exit channel.
try_for_each folds a fallible closure over an iterator and returns on the first Err, so later items are never touched after a failure.
Compute absolute differences with abs_diff so unsigned results never panic, and use unsigned_abs on i32 deltas before casting to usize.
Running every validation rule and flattening the Option failures into one Vec reports all problems at once instead of stopping at the first.
Compare Vec append, which empties the source by moving elements, with extend_from_slice cloning and extend consuming an iterator chain.
Push into a Vec that grows on demand or into one preallocated with with_capacity, watching capacity() so reallocation points are observed rather than guessed.
Vec::drain removes a range and hands the elements to an owning iterator, shortening the Vec while the collected items become independent owned data.
Grow, truncate, and reset byte buffers in place with resize and fill: growing needs Clone for new slots, truncation drops the tail, fill wipes stale bytes.
Cut length with truncate or empty a Vec with clear, while capacity stays reserved — reuse the allocation for the next batch instead of reallocating.
VecDeque pushes and pops at both ends in constant time, serving queue-style head removal and stack-style tail removal from one structure.
Give a child a Weak back-reference instead of a strong Rc so parent-child loops never leak: downgrade stores it, upgrade returns Option when the parent lives.
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.
An OR over two single-column indexes cannot share one composite btree, so the planner may merge both index bitmaps with a BitmapOr node instead.
Roll up boolean flags per group with bool_and and bool_or, which ignore NULL inputs and return NULL when no non-null input exists.
Sort tickets by urgency: a CASE expression returns the numeric priority used as the leading ORDER BY key, and ELSE catches unlisted statuses.
Bind optional filters as NULL so (param IS NULL OR col = param) collapses to always true, letting one statement serve every filter combination.
Make a column conditionally required with a CHECK: status = 'closed' must carry closed_at, while other statuses leave it free; NOT NULL cannot express this.
CHECK constraints cannot contain subqueries or reference other rows, so cross-row rules need a deferrable constraint trigger that validates at commit time.
A CHECK constraint can compare several columns of the same row, rejecting bookings whose end time is not strictly after the start time at the database boundary.
Enforce exactly-one-of-two columns with a CHECK constraint over num_nonnulls, rejecting rows that assign both or neither target.
Enforce text hygiene with CHECK constraints: btrim equality rejects padded strings, char_length bounds the size, status accepts known values only.
Assign each user to the month of first activity, join follow-up months back, and render retention as conditional counts per months-since bucket.
Control string comparison per column, per query, and per index with COLLATE, so the same names sort differently per language and indexes stay usable.
UNIQUE (user_id, project_id) allows one user on many projects and one project on many users, while two single-column uniques would forbid both.
Enforce a whole-set rule like two-leads-per-team with a DEFERRABLE INITIALLY DEFERRED constraint trigger, validated at COMMIT instead of per row.
Load CSV in one atomic statement with COPY, choosing server-side file reads or the client-side \copy equivalent and skipping row-by-row inserts.
CORR measures the Pearson correlation of two columns per group, also works as a window aggregate, and returns NULL when a variance is zero.
COUNT(DISTINCT x) OVER fails in PostgreSQL with 'DISTINCT is not implemented for window functions'; deduplicate first, then window-count.
Build a full combination matrix with CROSS JOIN, then LEFT JOIN real facts onto the skeleton so empty combinations show as zero instead of disappearing.
Keep large result sets on the server and pull them batch by batch with DECLARE CURSOR, FETCH n, and CLOSE, or let WITH HOLD survive the transaction commit.
Subtracting dates returns integer days while subtracting timestamps returns an interval, so mixing the two types changes the result's shape.
Truncate timestamps to calendar boundaries with date_trunc, then group on the result so counts align to real months, weeks, and hours.
Keep the top row of every group with DISTINCT ON, where the leading ORDER BY columns decide which row survives and wrapping re-sorts the output.
ALTER TABLE DROP COLUMN finishes instantly regardless of table size because only catalog metadata flips; old bytes stay in the heap until a rewrite.
Set enable_seqscan = off so the planner prefers index paths, compare the plans, then RESET; it is session-level debugging, not a production setting.
Build dynamic statements server-side with EXECUTE format: %I quotes identifiers and %L escapes literals, so stray apostrophes cannot break or inject the SQL.
BUFFERS output splits page access into shared hit for pages already cached and shared read for disk or OS fetches; two runs expose the cache effect.
Create expression indexes only from IMMUTABLE functions: upper() qualifies, while STABLE helpers like age(timestamp) are rejected outright.
FETCH FIRST n ROWS WITH TIES extends the result to every row tied with the cutoff, so leaderboards stop truncating equal scores that bare LIMIT silently drops.
Add a foreign key online with NOT VALID to skip scanning existing rows, then validate it later under a light lock that never blocks reads or writes.
FOR UPDATE NOWAIT fails immediately with lock_not_available when another transaction holds the row, choosing a loud failure over unbounded queue waiting.
Join ledgers from both sides, keep only rows with NULL on either side or mismatched amounts, and label each difference with a CASE.
Give tables random UUID primary keys with the built-in gen_random_uuid default, and validate external identifiers with ::uuid casts.
Explain the GIN fastupdate pending list: bulk writes batch there, queries pay a periodic merge cost, and fastupdate off trades write speed for smooth reads.
Accelerate overlap queries on range columns with a GiST index, because B-tree indexes cannot serve the && operator that range types rely on.
Give a reporting role read-only access with GRANT SELECT and ALTER DEFAULT PRIVILEGES so future tables inherit the same narrow scope.
One query yields detail rows, region subtotals, and a grand total via GROUPING SETS, with GROUPING() flagging which output columns are aggregated placeholders.
Filter month and day windows with >= start AND < end because BETWEEN reads the upper bound as midnight and drops the remainder of that day.
Create a hash index for equality-only lookups on long token columns, leaving range predicates, ordering, and uniqueness to a btree companion index.
Hash partitions route rows by modulus and remainder over the partition key, with equality predicates pruning the scan to a single partition.
Compare the two aggregation paths with EXPLAIN: hash builds first, group aggregates over sorted input, and enable_hashagg flips the plan for comparison.
CREATE INDEX IF NOT EXISTS and DROP CONSTRAINT IF EXISTS keep migrations re-runnable; ADD CONSTRAINT has none, so a DO block queries pg_constraint first.
Index Cond pushes equality and range predicates into the index scan; non-indexed columns surface as a post-scan Filter with rows-removed cost.
Index foreign key child columns because PostgreSQL does not create them automatically, so parent deletes avoid scanning the child table.
A btree index serves ORDER BY with LIMIT: the scan stops after n rows in either direction, and only a mismatched sort column falls back to a full sort.
Discover table structure through INFORMATION_SCHEMA columns and table_constraints instead of hardcoding column names into migrations.
Summing a parent through a one-to-many join counts each parent once per child; pre-aggregate the child side in a CTE to keep totals honest.
PostgreSQL 17 JSON_TABLE expands a JSON document into relational rows, declaring each column with name, type, and path, and NESTED PATH flattens inner arrays.
Lock the JSONB contract at write time: jsonb_typeof pins the top-level type and required keys, and nested values get their own type checks.
Match literal underscores and percent signs in LIKE patterns by escaping them, or the wildcards silently match characters you did not intend.
Split a tickets table by region with PARTITION BY LIST: equality and IN predicates prune to the matching child tables and skip the rest.
Deliver session-to-session signals with NOTIFY, which queues messages only at commit and drops them silently when nobody is listening.
PostgreSQL 17 MERGE adds WHEN NOT MATCHED BY SOURCE, so one statement updates changed rows, inserts missing ones, and deletes stale target rows in a sync.
A plain min or max becomes an index-endpoint InitPlan in EXPLAIN, independent of table size; ORDER BY plus LIMIT 1 fetches the whole oldest row the same way.
Return the most frequent non-null value per group with mode() WITHIN GROUP, and narrow the vote with FILTER when only qualifying rows count.
Chain INSERT RETURNING output into an UPDATE within one data-modifying CTE statement so order creation and stock deduction commit atomically together.
Every UPDATE writes a new row version: ctid moves to fresh storage and xmin records the writing transaction, which is the bloat VACUUM later reclaims.
A few indexed rows make nested loop cheapest, while a full aggregate over both tables amortizes into one hash join build; EXPLAIN shows which wins.
Use NOT EXISTS for anti joins because a single NULL in a NOT IN subquery makes the predicate UNKNOWN and silently returns an empty result.
now() freezes at transaction start so every call in one transaction agrees, while clock_timestamp() keeps moving with the wall clock.
Pick the second row of a window frame with nth_value; the default frame gives a moving answer while an unbounded full frame pins one constant runner-up.
PostgreSQL treats NULL as largest, so DESC defaults to NULLS FIRST; ORDER BY DESC NULLS LAST matches only an index created with the same explicit NULLS LAST.
Store money in NUMERIC and analytics in double precision: binary floats cannot represent 0.1 exactly, so repeated sums drift away from decimal results.
Inserting two rows that hit the same conflict target fails with cannot affect row a second time; aggregate the source by key first so each target appears once.