{"id":"sql-snippets/ad-hoc-query-hunt","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Find single-use ad-hoc plans wasting plan cache memory in SQL Server","description":"Measures single-use ad-hoc cached plans and their memory cost, the signature of literal-concatenated SQL, with the optimize for ad hoc workloads fix.","body":{"slug":"ad-hoc-query-hunt","name":"Ad-hoc query hunt","h1":"Find single-use ad-hoc plans wasting plan cache memory in SQL Server","category":"monitoring","lede":"Thousands of one-shot query plans eat plan cache memory. One query measures the damage; one setting fixes the cause.","engine_slug":"sql-server","problem":"Applications that build SQL by pasting values into the text send a different batch for every value, and SQL Server caches a separate plan for each. Simple parameterization rescues only trivial statements such as a single-table lookup by key; anything with a join, a subquery or an IN list stays literal. Plans with usecounts = 1 and objtype Adhoc are the result, and at scale they can hold gigabytes of plan cache and push out the plans that are actually reused.","sql":"SELECT COUNT(*) AS single_use_plans,\n       CAST(SUM(CAST(size_in_bytes AS BIGINT)) / 1048576.0 AS DECIMAL(12,1)) AS wasted_mb\nFROM sys.dm_exec_cached_plans\nWHERE objtype = 'Adhoc'\n  AND usecounts = 1;","how_it_works":"sys.dm_exec_cached_plans lists every cached plan; objtype Adhoc means a non-parameterized batch, and usecounts = 1 means it has run exactly once since SQL Server cached it: compiled for one set of literal values and never reused. The cost counter is size_in_bytes summed over those plans. CAST to BIGINT keeps the sum from overflowing INT. The server-side mitigation is the optimize for ad hoc workloads option: the first execution of a batch caches only a small compiled plan stub, and SQL Server caches the full plan when the same text runs a second time, so one-shot plans cost a few hundred bytes instead of tens of kilobytes. Parameterized code (sp_executesql, parameters from the client driver) reuses plans with or without it.","variants":[{"sql":"EXEC sp_configure 'show advanced options', 1; RECONFIGURE;\nEXEC sp_configure 'optimize for ad hoc workloads', 1; RECONFIGURE;"},{"sql":"SELECT TOP 20\n    usecounts, size_in_bytes / 1024 AS size_kb,\n    LEFT(t.text, 120) AS sample_text\nFROM sys.dm_exec_cached_plans cp\nCROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) t\nWHERE cp.objtype = 'Adhoc' AND cp.usecounts = 1\nORDER BY cp.size_in_bytes DESC;"}],"see_also":["high-logical-reads-queries","buffer-cache-contents","parse-vs-execute-ratio"],"faqs":[{"question":"The count is huge. Is enabling the option enough?","answer":"It limits the damage from now on, but plans already cached keep their full size until they are evicted. DBCC FREESYSTEMCACHE('SQL Plans') removes ad hoc and prepared plans immediately, at the cost of a burst of recompiles as they come back; most systems just let normal eviction catch up. ALTER DATABASE ... SET PARAMETERIZATION FORCED is a stronger option for one database: it parameterizes literals in most statements, which also changes which plans get reused, so test it first."},{"question":"Why not just parameterize everything instead?","answer":"That is the real fix: parameters from the client driver, or sp_executesql, give one plan per statement shape and also close the SQL injection hole that literal concatenation opens. The server option is for when the application is not yours to change, or not yet."}]},"source_url":"https://sqlly.app/sql-snippets/ad-hoc-query-hunt","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/add-business-days","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Add N business days to a date in SQL","description":"Compute a ship date of five working days after the order, skipping weekends (and holidays via a table).","body":{"slug":"add-business-days","name":"Add business days to a date","h1":"Add N business days to a date in SQL","category":"text","lede":"Promises like 'ships in 5 business days' need calendar math that skips weekends.","engine_slug":"postgresql","problem":"For each order, list the next 30 calendar days, keep the weekdays, and take the 5th one.","sql":"SELECT o.order_id, o.order_date, c.business_day AS ship_by\nFROM orders o\nCROSS JOIN LATERAL (\n    SELECT d::date AS business_day\n    FROM generate_series(o.order_date + 1, o.order_date + 30, interval '1 day') AS g(d)\n    WHERE EXTRACT(ISODOW FROM d) < 6\n    ORDER BY d\n    OFFSET 4 LIMIT 1\n) c;","how_it_works":"The LATERAL subquery runs once per order, so generate_series can read that order's date. It produces the next 30 calendar days, the ISODOW filter drops Saturdays and Sundays, and OFFSET 4 LIMIT 1 keeps the fifth surviving day: an order on Wednesday 2026-03-04 ships by Wednesday 2026-03-11. Thirty days is plenty for five business days; widen it for larger N or long holiday runs.","variants":[{"sql":"DECLARE @order_date DATE = '2026-03-04';\nWITH steps AS (\n    SELECT @order_date AS d, 0 AS n\n    UNION ALL\n    SELECT DATEADD(DAY, 1, d),\n           n + CASE WHEN (DATEPART(WEEKDAY, DATEADD(DAY, 1, d)) + @@DATEFIRST - 1) % 7 IN (0, 6)\n                    THEN 0 ELSE 1 END\n    FROM steps WHERE n < 5\n)\nSELECT d AS ship_by FROM steps WHERE n = 5;"}],"see_also":["business-days-between","next-anniversary"],"faqs":[{"question":"How do holidays get in?","answer":"Add AND d::date NOT IN (SELECT holiday_date FROM holidays) next to the weekend filter. Holidays vary by country, so a small per-region table beats trying to encode them in the query."},{"question":"Why does the series miss a day around the clock change?","answer":"If order_date is a timestamptz, generate_series steps wall-clock time across the DST switch and the spring-forward day has no 02:00 to land on. Cast the start to a plain date first, as the recipe does, so the series walks calendar days instead of clock hours."}]},"source_url":"https://sqlly.app/sql-snippets/add-business-days","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/add-column-if-missing","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Add a column if it does not exist","description":"Idempotent add-column migrations: IF NOT EXISTS where supported, and the guarded equivalent on engines that lack it.","body":{"slug":"add-column-if-missing","name":"Add column if missing","h1":"Add a column if it does not exist","category":"schema","lede":"Migrations re-run, roll back and get replayed on fresh databases, so DDL should be idempotent. This is the add-column-if-missing pattern per engine.","engine_slug":"postgresql","problem":"The same migration script runs on many environments at different schema versions, and on the ones that already have the column the statement must simply do nothing.","sql":"ALTER TABLE users\n  ADD COLUMN IF NOT EXISTS last_login_at timestamptz;","how_it_works":"PostgreSQL's ADD COLUMN IF NOT EXISTS (available since 9.6) turns the statement into a no-op with a NOTICE when the column is already there, so re-running a migration is harmless. A nullable column with no default is a catalog-only change. Since PostgreSQL 11 that also holds for a column with a constant default, even NOT NULL, because the default is stored once and filled in at read time; a volatile default such as clock_timestamp() still rewrites the table.","variants":[{"sql":"IF COL_LENGTH('dbo.Users', 'last_login_at') IS NULL\n    ALTER TABLE dbo.Users\n        ADD last_login_at DATETIMEOFFSET NULL;"},{"sql":"-- no native IF NOT EXISTS on ADD COLUMN; check first\nSET @col := (SELECT COUNT(*)\n             FROM information_schema.columns\n             WHERE table_schema = 'mydb'\n               AND table_name = 'users'\n               AND column_name = 'last_login_at');\nSET @sql := IF(@col = 0,\n    'ALTER TABLE users ADD COLUMN last_login_at DATETIME NULL',\n    'SELECT ''column already exists''');\nPREPARE stmt FROM @sql;\nEXECUTE stmt;\nDEALLOCATE PREPARE stmt;"},{"sql":"-- no IF NOT EXISTS and no procedural IF; check from the\n-- application, then alter\nSELECT COUNT(*) FROM pragma_table_info('users')\nWHERE name = 'last_login_at';\n-- if 0:\nALTER TABLE users ADD COLUMN last_login_at TEXT;"}],"see_also":["rename-column-if-exists","add-foreign-key-if-missing","create-table-if-not-exists"],"faqs":[{"question":"Does ADD COLUMN lock the table?","answer":"Briefly, on modern versions. PostgreSQL 11+ and SQL Server 2012+ Enterprise add a column with a constant default as a metadata change, and MySQL 8.0.12+ uses ALGORITHM=INSTANT for most ADD COLUMN cases. Each still needs a short exclusive metadata lock, which has to wait for running queries on the table and blocks new ones while it waits, so set a lock timeout. A volatile default, or older versions, mean a full table rewrite."}]},"source_url":"https://sqlly.app/sql-snippets/add-column-if-missing","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/add-foreign-key-if-missing","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Add a foreign key if it does not exist","description":"Idempotent FK creation guarded by constraint name, plus the NOT VALID pattern for adding the check to big tables without a long lock.","body":{"slug":"add-foreign-key-if-missing","name":"Add foreign key if missing","h1":"Add a foreign key if it does not exist","category":"schema","lede":"Replayed migrations choke on duplicate constraint names. Guard FK creation on the constraint name and it becomes safely re-runnable.","engine_slug":"postgresql","problem":"Rollouts and rollbacks mean the same foreign key can be created more than once, and the second attempt should be a no-op instead of an error.","sql":"DO $$\nBEGIN\n  IF NOT EXISTS (\n    SELECT 1 FROM pg_constraint\n    WHERE conname = 'fk_orders_customer'\n      AND conrelid = 'public.orders'::regclass\n  ) THEN\n    ALTER TABLE public.orders\n      ADD CONSTRAINT fk_orders_customer\n      FOREIGN KEY (customer_id) REFERENCES public.customers (id);\n  END IF;\nEND $$;","how_it_works":"The guard checks pg_constraint for the constraint name on that specific table, so the ALTER runs only the first time. On a large orders table the plain ADD CONSTRAINT checks every customer_id while holding a SHARE ROW EXCLUSIVE lock on both tables, which blocks writes to them until it finishes. Splitting it with NOT VALID (add now, VALIDATE CONSTRAINT later) keeps that lock momentary; the validation then runs under a weaker lock that lets reads and writes continue.","variants":[{"sql":"ALTER TABLE orders\n  ADD CONSTRAINT fk_orders_customer\n  FOREIGN KEY (customer_id) REFERENCES customers (id)\n  NOT VALID;\n-- later, without blocking writes:\nALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer;"},{"sql":"IF NOT EXISTS (\n    SELECT 1 FROM sys.foreign_keys\n    WHERE name = 'FK_Orders_Customers'\n      AND parent_object_id = OBJECT_ID('dbo.Orders'))\n    ALTER TABLE dbo.Orders\n        ADD CONSTRAINT FK_Orders_Customers\n        FOREIGN KEY (customer_id) REFERENCES dbo.Customers (id);"},{"sql":"SET @sql := IF(EXISTS (\n    SELECT 1 FROM information_schema.table_constraints\n    WHERE constraint_schema = DATABASE()\n      AND table_name = 'orders'\n      AND constraint_name = 'fk_orders_customer'\n      AND constraint_type = 'FOREIGN KEY'),\n  'DO 0',\n  'ALTER TABLE orders ADD CONSTRAINT fk_orders_customer\n     FOREIGN KEY (customer_id) REFERENCES customers (id)');\nPREPARE stmt FROM @sql;\nEXECUTE stmt;\nDEALLOCATE PREPARE stmt;\n-- InnoDB adds an index on customer_id if none exists"}],"see_also":["list-foreign-keys-targets","add-column-if-missing","make-column-not-null-safely"],"faqs":[{"question":"Why does adding my foreign key fail?","answer":"Usually one of three things. Existing child rows point at parents that do not exist; find them with SELECT ... FROM orders o LEFT JOIN customers c ON c.id = o.customer_id WHERE o.customer_id IS NOT NULL AND c.id IS NULL. The two columns have different types (int against bigint, or signed against unsigned on MySQL). Or the referenced column is not covered by a primary key or unique constraint."}]},"source_url":"https://sqlly.app/sql-snippets/add-foreign-key-if-missing","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/age-in-years-months-days","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Compute age in years, months and days in SQL","description":"Get a real age (not just a year difference) from a birth date, on engines that offer an age function and those that do not.","body":{"slug":"age-in-years-months-days","name":"Age in years, months and days","h1":"Compute age in years, months and days in SQL","category":"text","lede":"A person's age is years since their last birthday, which a naive DATEDIFF(YEAR, ...) gets wrong by one around birthdays.","engine_slug":"postgresql","problem":"PostgreSQL's age() returns an interval that already respects whether the birthday has passed this year.","sql":"SELECT\n    EXTRACT(YEAR  FROM age(CURRENT_DATE, birth_date))::int AS years,\n    EXTRACT(MONTH FROM age(CURRENT_DATE, birth_date))::int AS months,\n    EXTRACT(DAY   FROM age(CURRENT_DATE, birth_date))::int AS days\nFROM patients;","how_it_works":"age(end, start) returns a year-month-day interval computed with calendar rules, not fixed day counts. Extracting the three parts gives the components people expect. A plain DATEDIFF(YEAR, birth_date, today) style difference is off by one for everyone whose birthday has not happened yet this year.","variants":[{"sql":"SELECT TIMESTAMPDIFF(YEAR, birth_date, CURDATE()) AS age_years\nFROM patients;"},{"sql":"SELECT\n    DATEDIFF(YEAR, birth_date, GETDATE())\n      - CASE WHEN DATEADD(YEAR, DATEDIFF(YEAR, birth_date, GETDATE()), birth_date) > GETDATE()\n             THEN 1 ELSE 0 END AS age_years\nFROM patients;"}],"see_also":["next-anniversary","previous-month-same-day"],"faqs":[{"question":"What about February 29 birthdays?","answer":"Engines disagree. PostgreSQL's age() and MySQL's TIMESTAMPDIFF only count the year on March 1 in non-leap years: someone born 2024-02-29 is still 2 on 2027-02-28. The SQL Server CASE counts it on Feb 28, because DATEADD(YEAR, 3, '2024-02-29') returns 2027-02-28. Legal rules differ by country too, so if it matters, decide the rule and test it on Feb 28 and Mar 1."}]},"source_url":"https://sqlly.app/sql-snippets/age-in-years-months-days","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/aggregate-children-per-parent","corpus":"sql-snippets","engine":"all","language":"en","title":"Aggregate children into one row per parent","description":"LEFT JOIN plus GROUP BY gives every customer a row with their order count and total, including zeros.","body":{"slug":"aggregate-children-per-parent","name":"One row per parent with child aggregates","h1":"Aggregate children into one row per parent","category":"querying","lede":"LEFT JOIN keeps parents without children; COUNT(child) counts 0 for them.","engine_slug":"all","problem":"You want one row per customer with how many orders they placed and how much they spent, and customers who never ordered must still appear.","sql":"SELECT c.id, c.name,\n       COUNT(o.id) AS order_count,\n       COALESCE(SUM(o.amount), 0) AS total_amount\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.id\nGROUP BY c.id, c.name\nORDER BY total_amount DESC;","how_it_works":"The LEFT JOIN keeps every customer even when no order matches, leaving the order columns NULL for those rows. COUNT(o.id) counts only non-NULL ids, so it correctly reports 0 rather than 1 for the childless rows; SUM returns NULL for them, which COALESCE turns into 0. This is the shape behind most list screens: parent attributes plus child aggregates in one pass. For the id list in the variant, SQL Server writes STRING_AGG(...) WITHIN GROUP (ORDER BY o.id), MySQL GROUP_CONCAT(o.id ORDER BY o.id) and Oracle LISTAGG(o.id, ',') WITHIN GROUP (ORDER BY o.id).","variants":[{"sql":"SELECT c.id, c.name,\n       COUNT(o.id) AS order_count,\n       STRING_AGG(CAST(o.id AS varchar), ',' ORDER BY o.id) AS order_ids\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.id\nGROUP BY c.id, c.name\nORDER BY c.name;"}],"see_also":["percentage-of-total","aggregate-into-json","distinct-counts-per-group"],"faqs":[{"question":"Why COUNT(o.id) and not COUNT(*)?","answer":"COUNT(*) counts rows, and a customer with no orders still contributes one row (all NULLs), which would read as 1 order. Counting the child column counts only real matches."}]},"source_url":"https://sqlly.app/sql-snippets/aggregate-children-per-parent","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/aggregate-into-json","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Aggregate rows into JSON","description":"Build one JSON array of order objects per customer with JSON_AGG and JSON_BUILD_OBJECT.","body":{"slug":"aggregate-into-json","name":"Aggregate rows into JSON","h1":"Aggregate rows into JSON","category":"querying","lede":"The aggregate produces the array; the build function names the fields.","engine_slug":"postgresql","problem":"An API endpoint wants each customer with their orders as a JSON array, produced by the database in one query.","sql":"SELECT customer_id,\n       JSON_AGG(\n         JSON_BUILD_OBJECT('id', id,\n                           'date', order_date,\n                           'amount', amount)\n         ORDER BY order_date\n       ) AS orders_json\nFROM orders\nGROUP BY customer_id\nORDER BY customer_id;","how_it_works":"JSON_BUILD_OBJECT turns each order row into an object with named keys; JSON_AGG collects those objects into an array per group, and the ORDER BY inside the aggregate fixes the element order. Every engine ships its own pair: MySQL has JSON_ARRAYAGG with JSON_OBJECT, SQLite json_group_array with json_object, Oracle and SQL Server 2025 have JSON_ARRAYAGG with JSON_OBJECT, and older SQL Server versions use FOR JSON PATH.","variants":[{"sql":"SELECT customer_id,\n       JSON_ARRAYAGG(JSON_OBJECT('id', id,\n                                 'date', order_date,\n                                 'amount', amount)) AS orders_json\nFROM orders\nGROUP BY customer_id;"},{"sql":"SELECT customer_id,\n       json_group_array(json_object('id', id,\n                                    'date', order_date,\n                                    'amount', amount)) AS orders_json\nFROM orders\nGROUP BY customer_id;"}],"see_also":["aggregate-children-per-parent","percentage-of-total"],"faqs":[{"question":"Is the JSON element order guaranteed?","answer":"On PostgreSQL, yes, because the ORDER BY is inside the aggregate. MySQL's JSON_ARRAYAGG accepts no ORDER BY and its element order is undefined, so sort in the application if order matters there. SQLite's json_group_array follows the order rows reach the aggregate; SQLite 3.44+ also accepts an ORDER BY inside the call."},{"question":"Why does the aggregated column behave like text on SQLite but like JSON elsewhere?","answer":"SQLite's json_group_array returns TEXT that you read back with the JSON1 functions, MySQL returns its JSON type, and PostgreSQL returns json rather than jsonb, which keeps your key order but cannot take a GIN index without a cast. Cast to ::jsonb on PostgreSQL when you plan to index or dedupe the result."}]},"source_url":"https://sqlly.app/sql-snippets/aggregate-into-json","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/anonymize-emails","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Anonymize email addresses in SQL","description":"Replace real addresses with a deterministic placeholder built from the row id, inside a transaction.","body":{"slug":"anonymize-emails","name":"Anonymize emails","h1":"Anonymize email addresses in SQL","category":"data-quality","lede":"Build a fake-but-unique address from the row id so references stay stable, and UPDATE only rows that currently hold a real-looking email.","engine_slug":"postgresql","problem":"A production copy is heading to a staging environment and every customer email must go. A deterministic placeholder keeps joins and uniqueness working while removing the personal data.","sql":"BEGIN;\nUPDATE customers\nSET email = 'user' || id || '@example.invalid'\nWHERE email LIKE '%_@_%';\n-- check the row count, then COMMIT; or ROLLBACK;","how_it_works":"The new value concatenates the row's id into a placeholder at the reserved example.invalid domain, so every anonymized address stays unique and clearly fake. The WHERE limits the write to rows that hold an email-shaped value (LIKE is never true for NULL, so NULLs stay NULL); rows with junk that is not email-shaped keep it, so check them with validate-email-shape before the copy leaves. The UPDATE runs unchanged on Oracle, SQLite and SQL Server 2025, which added the || operator; MySQL treats || as OR by default (PIPES_AS_CONCAT changes that) and SQL Server 2022 and older have no ||, so use CONCAT there. The transaction matters because this UPDATE is deliberately destructive: there is no going back to the original addresses from the database alone.","variants":[{"sql":"UPDATE customers\nSET email = 'user' || id || '@' || split_part(email, '@', 2)\nWHERE email LIKE '%_@_%';"},{"sql":"UPDATE customers\nSET email = CONCAT('user', id, '@example.invalid')\nWHERE email IS NOT NULL\n  AND email LIKE '%_@_%';"}],"see_also":["mask-names","case-insensitive-duplicate-emails","restore-able-rows"],"faqs":[{"question":"Why example.invalid and not example.com?","answer":"The .invalid top-level domain is reserved (RFC 2606) for names that must never resolve, so any mail sent to an anonymized address fails at DNS lookup. example.com is reserved too, but for documentation, and it is a real, resolving domain: mail to it is refused only because its operator publishes a null MX record. A name that cannot resolve at all is the safer placeholder."},{"question":"Can the anonymization stay reversible?","answer":"Not from the database afterwards; the UPDATE destroys the originals on purpose. If the use case needs reversal, copy id and old email into a restricted table inside the same transaction, and protect that table like the secret it has just become."}]},"source_url":"https://sqlly.app/sql-snippets/anonymize-emails","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/archive-old-rows-to-history","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Archive old rows to a history table","description":"Move expired rows out of a hot table into an archive in one statement (DELETE ... RETURNING on PostgreSQL, OUTPUT on SQL Server), plus batching.","body":{"slug":"archive-old-rows-to-history","name":"Archive old rows to a history table","h1":"Archive old rows to a history table","category":"schema","lede":"Hot tables slow down as they grow, but old rows still belong somewhere. Move them to a history table in one statement: no window where rows are in both or neither.","engine_slug":"postgresql","problem":"The events table carries years of expired rows that slow every scan, yet deleting them outright would lose data the business still occasionally needs.","sql":"WITH moved AS (\n    DELETE FROM events\n    WHERE occurred_at < now() - interval '2 years'\n    RETURNING *\n)\nINSERT INTO events_history\nSELECT * FROM moved;","how_it_works":"The CTE deletes exactly the rows it returns, and the outer INSERT writes them to the archive in the same statement, so either both happen or neither does; a crash never leaves a row in both tables or in neither. SELECT * relies on the two tables having the same columns in the same order, so list the columns explicitly once the history table can drift. Moving millions of rows at once holds row locks on all of them and leaves that many dead tuples for vacuum, so batch it as in the next variant.","variants":[{"sql":"-- repeat until 0 rows moved; each pass stays small\nWITH moved AS (\n    DELETE FROM events\n    WHERE id IN (\n        SELECT id FROM events\n        WHERE occurred_at < now() - interval '2 years'\n        LIMIT 10000)\n    RETURNING *\n)\nINSERT INTO events_history SELECT * FROM moved;"},{"sql":"-- the OUTPUT target cannot have enabled triggers or take\n-- part in a foreign key; add TOP (10000) to batch\nDELETE FROM dbo.Events\nOUTPUT deleted.* INTO dbo.Events_History\nWHERE occurred_at < DATEADD(year, -2, SYSUTCDATETIME());"},{"sql":"-- no DELETE ... RETURNING; copy, then delete the same rows.\n-- Fix the cutoff once: NOW() changes between statements.\nSET @cutoff := NOW() - INTERVAL 2 YEAR;\nSTART TRANSACTION;\nINSERT INTO events_history\n    SELECT * FROM events\n    WHERE occurred_at < @cutoff;\nDELETE FROM events\n    WHERE occurred_at < @cutoff;\nCOMMIT;"}],"see_also":["rotate-partition","truncate-all-tables-safe-order","copy-table-with-data"],"faqs":[{"question":"How often should I run the archive job?","answer":"Often enough that each run moves a bounded number of rows. A nightly job that moves one day's worth keeps locks short and gives vacuum or the transaction log a steady small load, while a quarterly purge of 50 million rows does neither. If retention is a fixed window, partition the table by date and drop or detach old partitions instead (see rotate-partition)."},{"question":"How does the MySQL path stay atomic without the CTE?","answer":"MySQL has neither data-modifying CTEs nor RETURNING, so the variant runs INSERT ... SELECT and then DELETE inside one transaction; both commit or neither does. Sessions outside the transaction never see a row in both tables."}]},"source_url":"https://sqlly.app/sql-snippets/archive-old-rows-to-history","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/autovacuum-status","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Check autovacuum status and dead-tuple backlog in PostgreSQL","description":"Shows dead tuples, dead-tuple percentage and the last autovacuum per table, so you can see whether vacuum is keeping up or falling behind.","body":{"slug":"autovacuum-status","name":"Autovacuum status","h1":"Check autovacuum status and dead-tuple backlog in PostgreSQL","category":"monitoring","lede":"Autovacuum runs in the background without telling you when it falls behind. This shows the dead-row backlog per table.","engine_slug":"postgresql","problem":"UPDATEs and DELETEs leave dead tuples that only VACUUM can reclaim. Autovacuum handles this automatically, but on high-churn tables it can lose the race: the dead-tuple backlog grows, the table bloats, and scans slow down. pg_stat_user_tables exposes the backlog and when autovacuum last touched each table.","sql":"SELECT relname AS table_name,\n       n_live_tup, n_dead_tup,\n       ROUND(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,\n       last_autovacuum, autovacuum_count,\n       last_vacuum, vacuum_count,\n       pg_size_pretty(pg_total_relation_size(relid)) AS total_size\nFROM pg_stat_user_tables\nWHERE n_dead_tup > 0\nORDER BY n_dead_tup DESC\nLIMIT 25;","how_it_works":"n_dead_tup is an estimate of dead row versions, maintained from the counts of updates and deletes and reset by each vacuum. Autovacuum starts on a table once dead rows exceed autovacuum_vacuum_threshold plus autovacuum_vacuum_scale_factor times the row count, 50 plus 20 percent by default, so a dead_pct well above 20 percent means vacuum is behind. last_autovacuum shows when the automatic process last ran; last_vacuum records manual runs. A high dead_pct with a recent last_autovacuum has two possible causes. Either churn outpaces vacuum, fixed by per-table tuning (a lower autovacuum_vacuum_scale_factor so it starts sooner, a higher autovacuum_vacuum_cost_limit so it works faster), or vacuum ran but was not allowed to remove the rows because an old transaction, replication slot or prepared transaction still needs them. Check long-transactions before tuning.","variants":[{"sql":"SELECT relname, n_dead_tup, n_live_tup, last_autovacuum\nFROM pg_stat_user_tables\nWHERE last_autovacuum IS NULL AND n_dead_tup > 0\nORDER BY n_dead_tup DESC;"},{"sql":"SELECT p.pid, p.datname, p.relid::regclass AS table_name, p.phase,\n       p.heap_blks_scanned, p.heap_blks_total,\n       ROUND(100.0 * p.heap_blks_scanned / NULLIF(p.heap_blks_total, 0), 1) AS pct_scanned,\n       p.index_vacuum_count,\n       now() - a.xact_start AS running_for\nFROM pg_stat_progress_vacuum p\nLEFT JOIN pg_stat_activity a ON a.pid = p.pid\nORDER BY running_for DESC NULLS LAST;"}],"see_also":["long-transactions","statistics-staleness","table-index-sizes-topn"],"faqs":[{"question":"Autovacuum runs constantly on one table. Is that a problem?","answer":"Not by itself. Autovacuum is triggered by churn, so constant runs on a table mean constant churn, which is fine if dead_pct stays low. It becomes a problem when each pass leaves the dead count about where it was: vacuum is scanning but cannot remove rows an old snapshot still needs. The VACUUM VERBOSE output, or the autovacuum log lines with log_autovacuum_min_duration set, report how many dead rows were not yet removable. index_vacuum_count above 1 in the progress view means the dead-row list did not fit in maintenance_work_mem and the indexes are being scanned more than once."},{"question":"What holds back vacuum besides long transactions?","answer":"An inactive replication slot (pg_replication_slots.xmin or catalog_xmin), a standby running long queries with hot_standby_feedback = on, and forgotten prepared transactions (pg_prepared_xacts) all hold back the oldest row version vacuum may remove, for every database in the cluster. A table with autovacuum_enabled = false in its storage options is simply never vacuumed automatically. Each of these shows up as dead row counts that stay high however vacuum is tuned."}]},"source_url":"https://sqlly.app/sql-snippets/autovacuum-status","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/bill-of-materials-walk","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Walk a bill of materials","description":"Explode an assembly into all its parts, multiplying quantities along the way, with a recursive CTE.","body":{"slug":"bill-of-materials-walk","name":"Walk a bill of materials","h1":"Walk a bill of materials","category":"querying","lede":"Quantities multiply down the tree; a final GROUP BY sums duplicate parts.","engine_slug":"postgresql","problem":"Assembly 100 contains sub-assemblies that contain parts. You need the flattened shopping list: every component below the assembly and the total quantity it takes to build one.","sql":"WITH RECURSIVE breakdown AS (\n  SELECT pc.child_id AS part_id, pc.quantity, 1 AS level\n  FROM part_children pc\n  WHERE pc.part_id = 100\n  UNION ALL\n  SELECT pc.child_id, pc.quantity * b.quantity, b.level + 1\n  FROM part_children pc\n  JOIN breakdown b ON pc.part_id = b.part_id\n)\nSELECT p.name, SUM(b.quantity) AS total_quantity, MIN(b.level) AS first_used_at_level\nFROM breakdown b\nJOIN parts p ON p.id = b.part_id\nGROUP BY p.name\nORDER BY p.name;","how_it_works":"Each recursive round multiplies the child's own quantity by the quantity accumulated so far, so a screw needed 4 per bracket and 3 brackets per assembly becomes 12. The final GROUP BY merges parts that appear in several sub-assemblies into one total. The list includes the sub-assemblies themselves; add WHERE NOT EXISTS (SELECT 1 FROM part_children x WHERE x.part_id = b.part_id) to keep only leaf parts. Runs as-is on PostgreSQL, MySQL 8 and SQLite; a parts loop means bad data and needs the same guard as any recursive CTE.","variants":[{"sql":"WITH RECURSIVE tree AS (\n  SELECT p.id, p.name, 0 AS level,\n         CAST(p.name AS text) AS path\n  FROM parts p\n  WHERE p.id = 100\n  UNION ALL\n  SELECT pc.child_id, p2.name, t.level + 1,\n         t.path || ' > ' || p2.name\n  FROM part_children pc\n  JOIN tree t ON pc.part_id = t.id\n  JOIN parts p2 ON p2.id = pc.child_id\n)\nSELECT REPEAT('  ', level) || name AS indented, path\nFROM tree\nORDER BY path;"},{"sql":"WITH breakdown (part_id, quantity, lvl) AS (\n  SELECT pc.child_id, pc.quantity, 1\n  FROM part_children pc\n  WHERE pc.part_id = 100\n  UNION ALL\n  SELECT pc.child_id, pc.quantity * b.quantity, b.lvl + 1\n  FROM part_children pc\n  JOIN breakdown b ON pc.part_id = b.part_id\n)\nSELECT p.name, SUM(b.quantity) AS total_quantity, MIN(b.lvl) AS first_used_at_level\nFROM breakdown b\nJOIN parts p ON p.id = b.part_id\nGROUP BY p.name\nORDER BY p.name;"}],"see_also":["transitive-closure-recursive-cte","org-chart-walk","recursive-cte-cycle-guard"],"faqs":[{"question":"Why multiply quantities instead of summing them?","answer":"Because a child's requirement is per one unit of its parent. The parent needs 3 brackets, and each bracket needs 4 screws, so the assembly needs 3 x 4 screws. Multiplying down each edge gives the true per-assembly requirement."}]},"source_url":"https://sqlly.app/sql-snippets/bill-of-materials-walk","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/blank-strings-vs-nulls","corpus":"sql-snippets","engine":"all","language":"en","title":"Find blank strings mixed with NULLs","description":"Count NULL, empty and whitespace-only values per column to expose the mixed-blank anti-pattern.","body":{"slug":"blank-strings-vs-nulls","name":"Blank strings vs NULL","h1":"Find blank strings mixed with NULLs","category":"data-quality","lede":"One row counts the kinds of 'no value' per column: real NULLs, empty strings, and blanks (empty or nothing but spaces).","engine_slug":"all","problem":"Legacy imports wrote '' instead of NULL, so customers.name is now a mix of both. Any IS NULL check undercounts the real holes until you know the split.","sql":"SELECT\n  COUNT(*) AS total_rows,\n  SUM(CASE WHEN name IS NULL THEN 1 ELSE 0 END) AS null_name,\n  SUM(CASE WHEN name = '' THEN 1 ELSE 0 END) AS empty_name,\n  SUM(CASE WHEN name IS NOT NULL\n            AND (TRIM(name) = '' OR TRIM(name) IS NULL)\n           THEN 1 ELSE 0 END) AS blank_name\nFROM customers;","how_it_works":"Each SUM(CASE) tests one definition of missing: IS NULL for true NULLs, = '' for empty strings, and a trimmed value that is empty for blanks, which includes the empty strings. The TRIM(name) IS NULL branch is there for Oracle, where TRIM('   ') returns NULL rather than ''. Repeat the expressions per suspect column; the split tells you whether to normalize before adding NOT NULL or validation constraints. Expect different numbers per engine on the same data: Oracle stores '' as NULL, so empty_name is always 0 and those rows show up as NULLs, and SQL Server ignores trailing spaces when comparing, so its empty_name already counts '   '.","variants":[{"sql":"UPDATE customers\nSET name = NULL\nWHERE name IS NOT NULL\n  AND (TRIM(name) = '' OR TRIM(name) IS NULL);"}],"see_also":["trim-and-dedupe","null-counts-per-column","per-column-fill-rate"],"faqs":[{"question":"Why does Oracle report no empty strings?","answer":"Oracle treats a zero-length VARCHAR2 as NULL: inserting '' stores NULL, and name = '' is never true. Those rows land in null_name instead. Every other engine here keeps '' and NULL apart, which is why the same import can look clean on Oracle and messy on PostgreSQL."},{"question":"Which definition of missing should the cleanup target?","answer":"Decide per column: if empty means unknown, rewrite '' to NULL so IS NULL covers it; if empty is a deliberate value, keep it and make the NOT NULL check the only rule. Oracle cannot store '' apart from NULL at all, so data landing there has already made the choice."}]},"source_url":"https://sqlly.app/sql-snippets/blank-strings-vs-nulls","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/blocking-queries","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Find blocking chains in SQL Server","description":"Lists every blocked request with the session blocking it and that blocker's own query text, so the head of the chain is always visible.","body":{"slug":"blocking-queries","name":"Blocking queries","h1":"Find blocking chains in SQL Server","category":"monitoring","lede":"Every blocked request with the session blocking it and that session's last batch, in one result set.","engine_slug":"sql-server","problem":"sys.dm_exec_requests exposes blocking_session_id: the session holding the lock each waiting request wants. Joining that back to the blocker's own request text turns a session id into a readable chain, and often reveals that the real head of the chain is an innocuous-looking SELECT inside an uncommitted transaction.","sql":"SELECT r.session_id AS blocked_session,\n       r.blocking_session_id,\n       r.wait_type, r.wait_time AS wait_ms,\n       r.wait_resource,\n       LEFT(t.text, 140) AS blocked_query,\n       bs.status AS blocker_status,\n       bs.open_transaction_count AS blocker_open_trans,\n       LEFT(bt.text, 140) AS blocker_last_batch\nFROM sys.dm_exec_requests r\nCROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t\nLEFT JOIN sys.dm_exec_sessions bs ON bs.session_id = r.blocking_session_id\nLEFT JOIN sys.dm_exec_connections bc ON bc.session_id = r.blocking_session_id\nOUTER APPLY sys.dm_exec_sql_text(bc.most_recent_sql_handle) bt\nWHERE r.blocking_session_id > 0\nORDER BY r.wait_time DESC;","how_it_works":"sys.dm_exec_requests has one row per running request, and blocking_session_id is nonzero when that request is waiting on another session. The CROSS APPLY decodes the waiting request's own SQL. The blocker is looked up through sys.dm_exec_sessions and sys.dm_exec_connections rather than dm_exec_requests, because the most common head blocker is not running anything: it ran an UPDATE inside a transaction and never committed. Such a session has no request row but does have most_recent_sql_handle, the last batch it sent, and OUTER APPLY keeps the row even when that text is unavailable. blocker_status = sleeping with blocker_open_trans above 0 is the abandoned-transaction signature. blocking_session_id > 0 skips the negative special values described below.","variants":[{"sql":"WITH waits AS (\n    SELECT session_id, blocking_session_id\n    FROM sys.dm_exec_requests\n    WHERE blocking_session_id > 0\n), heads AS (\n    SELECT DISTINCT w.blocking_session_id AS session_id\n    FROM waits w\n    WHERE w.blocking_session_id NOT IN (SELECT session_id FROM waits)\n), chain AS (\n    SELECT h.session_id, CAST(NULL AS SMALLINT) AS blocked_by, h.session_id AS head_blocker, 0 AS depth\n    FROM heads h\n    UNION ALL\n    SELECT w.session_id, CAST(w.blocking_session_id AS SMALLINT), c.head_blocker, c.depth + 1\n    FROM chain c\n    JOIN waits w ON w.blocking_session_id = c.session_id\n    WHERE c.depth < 50\n)\nSELECT head_blocker, depth, session_id, blocked_by\nFROM chain\nORDER BY head_blocker, depth, session_id;"}],"see_also":["who-blocks-whom","lock-waits-summary","long-transactions"],"faqs":[{"question":"The blocking_session_id is -2 or a session with no request. What now?","answer":"-2 means the lock belongs to an orphaned distributed transaction, -3 a deferred recovery transaction, and -4 that the owner could not be identified at that instant because of latch state changes. A positive id with no row in dm_exec_requests is an idle session holding locks in an open transaction; the main query still shows its last batch. sys.dm_tran_locks WHERE request_session_id = that id lists what it holds, and sys.dm_exec_input_buffer(session_id, NULL) shows its last statement."},{"question":"Should I kill the head blocker?","answer":"Sometimes it is the right call, but KILL rolls back the session's open transaction, and in SQL Server a large rollback can take as long as the work did, holding its locks until it finishes. Check what the blocker is doing and how much it has written first (sys.dm_tran_database_transactions shows log bytes used per transaction). KILL <id> WITH STATUSONLY reports rollback progress afterwards."}]},"source_url":"https://sqlly.app/sql-snippets/blocking-queries","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/bucketed-counts","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Count rows bucketed by time period","description":"Extract year and month (or week) from a date and GROUP BY it for row counts per period.","body":{"slug":"bucketed-counts","name":"Time bucket counts","h1":"Count rows bucketed by time period","category":"data-quality","lede":"Pull the period key out of the date with EXTRACT, group on it, and count: row counts per day, month or quarter in one query.","engine_slug":"postgresql","problem":"A per-month order census shows ingestion rhythm and dead months at once. It is the time-based cousin of the value histogram.","sql":"SELECT EXTRACT(YEAR FROM order_date) AS order_year,\n       EXTRACT(MONTH FROM order_date) AS order_month,\n       COUNT(*) AS order_count\nFROM orders\nWHERE order_date IS NOT NULL\nGROUP BY EXTRACT(YEAR FROM order_date), EXTRACT(MONTH FROM order_date)\nORDER BY order_year, order_month;","how_it_works":"EXTRACT pulls the year and month out of each date, and GROUP BY both produces one row per calendar month. Ordering by year then month reads like a timeline; gaps in the sequence are months with no rows at all (see the date-gap recipe for a calendar that fills them). The statement runs unchanged on MySQL and Oracle. SQL Server has no EXTRACT, so use YEAR() and MONTH() (second variant); on SQLite group by strftime('%Y-%m', order_date).","variants":[{"sql":"SELECT order_size, COUNT(*) AS order_count\nFROM (\n  SELECT CASE\n           WHEN total < 50 THEN 'small'\n           WHEN total < 200 THEN 'medium'\n           ELSE 'large'\n         END AS order_size\n  FROM orders\n  WHERE total IS NOT NULL\n) sized\nGROUP BY order_size\nORDER BY order_count DESC;"},{"sql":"SELECT YEAR(order_date) AS order_year,\n       MONTH(order_date) AS order_month,\n       COUNT(*) AS order_count\nFROM orders\nWHERE order_date IS NOT NULL\nGROUP BY YEAR(order_date), MONTH(order_date)\nORDER BY order_year, order_month;"},{"sql":"SELECT date_trunc('week', order_date) AS week_start,\n       COUNT(*) AS order_count\nFROM orders\nWHERE order_date IS NOT NULL\nGROUP BY 1\nORDER BY 1;"}],"see_also":["value-distribution-histogram","date-gap-detection","dominant-value-frequency"],"faqs":[{"question":"Why not GROUP BY DATE_TRUNC directly?","answer":"On PostgreSQL you can, and the result is a real date you can chart directly. Elsewhere the truncation function has a different name: TRUNC(order_date, 'MM') on Oracle, DATETRUNC(month, order_date) on SQL Server 2022+, date(order_date, 'start of month') on SQLite, and nothing built in on MySQL. Week buckets differ further: date_trunc('week') starts weeks on Monday, while SQL Server's DATETRUNC(week) follows the DATEFIRST setting, Sunday by default in US English."}]},"source_url":"https://sqlly.app/sql-snippets/bucketed-counts","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/buffer-cache-contents","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"See what is in the SQL Server buffer pool","description":"Groups sys.dm_os_buffer_descriptors by database, then drills into the top cached objects for the current database, so you know what memory is actually holding.","body":{"slug":"buffer-cache-contents","name":"Buffer cache contents","h1":"See what is in the SQL Server buffer pool","category":"monitoring","lede":"Which databases, and which tables and indexes within them, are occupying the buffer pool right now.","engine_slug":"sql-server","problem":"sys.dm_os_buffer_descriptors has one row per cached 8 KB page in the buffer pool. Grouped by database, it shows how the instance divides RAM; joined to allocation units and partitions, it names the tables and indexes holding the most pages. That is the evidence to bring to a discussion about memory pressure or a falling page life expectancy. On a server with a large buffer pool the DMV has millions of rows and the query takes a while, so avoid running it every minute.","sql":"SELECT DB_NAME(database_id) AS database_name,\n       COUNT(*) AS cached_pages,\n       CAST(COUNT(*) * 8 / 1024.0 AS DECIMAL(12,1)) AS cached_mb\nFROM sys.dm_os_buffer_descriptors\nWHERE database_id <> 32767\nGROUP BY database_id\nORDER BY cached_pages DESC;","how_it_works":"database_id 32767 is the hidden resource database, excluded here. Each row is one 8 KB page, so pages times 8 divided by 1024 gives megabytes. The per-object variant restricts to the current database (bd.database_id = DB_ID()) and joins through sys.allocation_units to sys.partitions to name the table and index; index_id 0 is a heap, 1 the clustered index, 2 and above nonclustered indexes. The join on container_id = partition_id holds for in-row, row-overflow and LOB allocation units alike, because hobt_id and partition_id have the same value. is_modified = 1 marks dirty pages that have not yet been written back to disk; add SUM(CASE WHEN is_modified = 1 THEN 1 ELSE 0 END) to see how much of the pool is waiting for a checkpoint.","variants":[{"sql":"SELECT TOP 25\n    OBJECT_SCHEMA_NAME(p.object_id) AS schema_name,\n    OBJECT_NAME(p.object_id) AS object_name,\n    p.index_id,\n    COUNT_BIG(*) AS cached_pages,\n    CAST(COUNT_BIG(*) * 8 / 1024.0 AS DECIMAL(12,1)) AS cached_mb\nFROM sys.dm_os_buffer_descriptors bd\nJOIN sys.allocation_units au ON au.allocation_unit_id = bd.allocation_unit_id\nJOIN sys.partitions p ON p.partition_id = au.container_id\nWHERE bd.database_id = DB_ID()\nGROUP BY p.object_id, p.index_id\nORDER BY cached_pages DESC;"}],"see_also":["cache-hit-ratio","table-index-sizes-topn","high-logical-reads-queries"],"faqs":[{"question":"An object I query constantly is not in the cache. Why?","answer":"Pages leave the pool when something else needs the memory more. Large scans of other tables, a table bigger than the pool, or another database on the same instance can all push it out, and this view only shows the current moment. The per-database query shows whether another database dominates; for scans, an index that lets the queries read fewer pages usually helps more than adding RAM."},{"question":"Is a low page life expectancy a problem?","answer":"Page life expectancy is the number of seconds a page is expected to stay in the pool at the current rate of reads. It starts at zero after a restart and dips during big scans or index rebuilds, so watch its trend rather than one reading, and on NUMA hardware check the per-node values under Buffer Node as well. Old fixed thresholds such as 300 seconds date from servers with a few GB of memory. A sustained drop together with rising PAGEIOLATCH waits in the wait summary is the real sign of memory pressure."}]},"source_url":"https://sqlly.app/sql-snippets/buffer-cache-contents","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/business-days-between","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Count business days between two dates in SQL","description":"Count Monday-to-Friday days between two dates, weekends excluded, holidays on top if you supply a table.","body":{"slug":"business-days-between","name":"Business days between two dates","h1":"Count business days between two dates in SQL","category":"text","lede":"SLA clocks and delivery estimates count working days only. Weekends are computable; holidays need a lookup table.","engine_slug":"sql-server","problem":"Generate one row per calendar day between the dates, keep the weekdays, and count them.","sql":"DECLARE @start_date DATE = '2026-03-02', @end_date DATE = '2026-03-31';\n\nWITH days AS (\n    SELECT @start_date AS d\n    UNION ALL\n    SELECT DATEADD(DAY, 1, d) FROM days WHERE d < @end_date\n)\nSELECT COUNT(*) AS business_days\nFROM days\nWHERE (DATEPART(WEEKDAY, d) + @@DATEFIRST - 1) % 7 NOT IN (0, 6)\nOPTION (MAXRECURSION 0);","how_it_works":"The recursive CTE walks one day at a time from start to end, and the WHERE drops Saturdays and Sundays: adding @@DATEFIRST to DATEPART(WEEKDAY) makes Sunday 0 and Saturday 6 whatever the session's DATEFIRST is, and unlike DATENAME it does not depend on the session language. March 2026 has 22 weekdays. MAXRECURSION 0 removes the 100-level default cap so long ranges work. For holidays, add AND d NOT IN (SELECT holiday_date FROM holidays).","variants":[{"sql":"SELECT COUNT(*) AS business_days\nFROM generate_series(DATE '2026-03-02', DATE '2026-03-31', interval '1 day') AS g(d)\nWHERE EXTRACT(ISODOW FROM d) < 6;"}],"see_also":["add-business-days","days-in-month"],"faqs":[{"question":"Does this count the start date?","answer":"Both queries count both ends: the recursion emits the start date and keeps going until it has emitted the end date, and generate_series includes its upper bound. For a 'days until' style count that excludes the start, begin the series one day later; decide the convention once and document it."}]},"source_url":"https://sqlly.app/sql-snippets/business-days-between","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/cache-hit-ratio","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Check the buffer cache hit ratio in PostgreSQL","description":"Computes the percentage of page reads served from cache versus disk, per database, with the SQL Server buffer pool equivalent.","body":{"slug":"cache-hit-ratio","name":"Cache hit ratio","h1":"Check the buffer cache hit ratio in PostgreSQL","category":"monitoring","lede":"The cache hit ratio: what share of page reads PostgreSQL served from shared_buffers instead of asking the operating system.","engine_slug":"postgresql","problem":"PostgreSQL reads data in 8 KB pages and first looks in shared_buffers. pg_stat_database counts, per database, the pages found there (blks_hit) and the pages it had to request from the operating system (blks_read). A ratio near 99 percent means the working set fits in memory; anything meaningfully below that on an OLTP system points to undersized shared_buffers or a working set that grew past RAM.","sql":"SELECT datname,\n       blks_hit, blks_read,\n       ROUND(100.0 * blks_hit / NULLIF(blks_hit + blks_read, 0), 2) AS cache_hit_pct\nFROM pg_stat_database\nWHERE datname IS NOT NULL\nORDER BY blks_hit + blks_read DESC;","how_it_works":"blks_hit counts pages found in shared_buffers; blks_read counts pages PostgreSQL asked the OS for. The ratio hit / (hit + read) is cumulative since the last stats reset, so a warm-up after restart barely moves a long window, and a problem that started yesterday barely moves it either. Snapshot the two counters and compute the ratio on the difference to see recent behaviour. A blks_read is not necessarily a disk read: PostgreSQL relies on the operating system's file cache too, and many of those reads are served from it. Check disk I/O at the OS level (iostat) before concluding the server needs more memory. The row with a NULL datname holds shared catalogs and is filtered out.","variants":[{"sql":"SELECT CAST(100.0 * hit.cntr_value / NULLIF(base.cntr_value, 0) AS DECIMAL(5,2)) AS buffer_cache_hit_pct\nFROM sys.dm_os_performance_counters hit\nJOIN sys.dm_os_performance_counters base\n  ON base.object_name = hit.object_name\n AND RTRIM(base.counter_name) = 'Buffer cache hit ratio base'\nWHERE hit.object_name LIKE '%Buffer Manager%'\n  AND RTRIM(hit.counter_name) = 'Buffer cache hit ratio';"},{"sql":"SELECT relname AS table_name,\n       heap_blks_hit, heap_blks_read,\n       ROUND(100.0 * heap_blks_hit / NULLIF(heap_blks_hit + heap_blks_read, 0), 1) AS heap_hit_pct\nFROM pg_statio_user_tables\nWHERE heap_blks_hit + heap_blks_read > 0\nORDER BY heap_blks_read DESC\nLIMIT 20;"}],"see_also":["buffer-cache-contents","high-read-tables","table-index-sizes-topn"],"faqs":[{"question":"Is 95 percent a bad cache hit ratio?","answer":"For an OLTP database whose working set should fit in memory, it is worth investigating; 99 percent or more is typical. A warehouse running large sequential scans will sit lower and that is expected, partly because PostgreSQL deliberately runs big sequential scans through a small ring of buffers so they do not evict everything else. A nightly batch can also drag the cumulative ratio down without hurting interactive users."},{"question":"How do I improve the ratio?","answer":"In rough order of cost: make queries touch fewer pages (better indexes, fewer full scans), raise shared_buffers (25 percent of RAM is the usual starting point on a dedicated server; it needs a restart), and add RAM. Use the per-table variant first to see which tables drive the misses, since one scan-heavy table often accounts for most of them."}]},"source_url":"https://sqlly.app/sql-snippets/cache-hit-ratio","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/cascade-impact-preview","corpus":"sql-snippets","engine":"all","language":"en","title":"Preview what a delete would cascade","description":"Before deleting a parent, count the children and grandchildren a cascading delete would remove.","body":{"slug":"cascade-impact-preview","name":"Cascade impact","h1":"Preview what a delete would cascade","category":"data-quality","lede":"Count the rows at each level that reference the target id: the exact set an ON DELETE CASCADE would take with it.","engine_slug":"all","problem":"Deleting a customer with ON DELETE CASCADE in place removes their orders and every order line. Run the preview first: the counts tell you whether the delete is a cleanup or an accident.","sql":"SELECT c.id AS customer_id, c.email,\n (SELECT COUNT(*) FROM orders o\n  WHERE o.customer_id = c.id) AS orders_deleted,\n (SELECT COUNT(*) FROM order_items oi\n  JOIN orders o ON o.id = oi.order_id\n  WHERE o.customer_id = c.id) AS order_items_deleted\nFROM customers c\nWHERE c.id = 42;","how_it_works":"Two correlated subqueries count the damage per level: direct children (orders) and grandchildren reached through the children (order_items). The customer row itself is not counted. Add one subquery per further table that cascades, following the same join path. For a batch delete, the variant sums the impact over a list of ids in one pass; COUNT(DISTINCT o.id) is needed there because the join repeats each order once per line.","variants":[{"sql":"SELECT COUNT(DISTINCT o.id) AS orders_deleted,\n       COUNT(oi.id) AS order_items_deleted\nFROM orders o\nLEFT JOIN order_items oi ON oi.order_id = o.id\nWHERE o.customer_id IN (42, 43, 44);"}],"see_also":["multi-parent-orphan-sweep","referential-audit-both-directions","soft-delete-audit"],"faqs":[{"question":"What if the FK has no ON DELETE CASCADE?","answer":"Then the DELETE fails on the first child row. The preview still matters, because it tells you how much manual cleanup the delete needs to succeed. Use the same counts to plan the order of deletes (children first), or switch the strategy to soft delete, which the soft-delete-audit recipe tracks."},{"question":"Do multiple cascade paths change what the preview counts?","answer":"A little: on PostgreSQL and MySQL a row reached through two cascade paths still gets deleted once, so the count is the union of the paths. SQL Server refuses to create two cascade paths that reach the same table at all (error 1785), so only chain shapes exist there and the preview never double counts."}]},"source_url":"https://sqlly.app/sql-snippets/cascade-impact-preview","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/case-insensitive-duplicate-emails","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find duplicate emails ignoring case","description":"Group by LOWER(col) so John@X.com and john@x.com count as one, and list the stored variants.","body":{"slug":"case-insensitive-duplicate-emails","name":"Case-insensitive dupes","h1":"Find duplicate emails ignoring case","category":"data-quality","lede":"Lowercase the column before grouping to catch duplicates that differ only in letter case, then aggregate the raw variants.","engine_slug":"postgresql","problem":"Emails are case-insensitive in practice, but the column stored them as typed. Support reports 'the same customer twice' that the exact-match duplicate check cannot see.","sql":"SELECT LOWER(email) AS email_key, COUNT(*) AS occurrences,\n       STRING_AGG(email, ', ' ORDER BY email) AS stored_variants\nFROM customers\nWHERE email IS NOT NULL\nGROUP BY LOWER(email)\nHAVING COUNT(*) > 1\nORDER BY occurrences DESC;","how_it_works":"LOWER(email) is the grouping key, so 'Ada@X.io' and 'ada@x.io' join one group. HAVING keeps groups with more than one row. STRING_AGG lists the stored spellings side by side: the raw evidence you need when merging accounts.","variants":[{"sql":"SELECT LOWER(email) AS email_key, COUNT(*) AS occurrences,\n       GROUP_CONCAT(email SEPARATOR ', ') AS stored_variants\nFROM customers\nWHERE email IS NOT NULL\nGROUP BY LOWER(email)\nHAVING COUNT(*) > 1;"},{"sql":"SELECT LOWER(TRIM(email)) AS email_key, COUNT(*) AS occurrences\nFROM customers\nWHERE email IS NOT NULL\nGROUP BY LOWER(TRIM(email))\nHAVING COUNT(*) > 1;"}],"see_also":["find-duplicates-on-a-key","trim-and-dedupe","anonymize-emails"],"faqs":[{"question":"Should I just add a case-insensitive unique index?","answer":"That is the durable fix: a unique index on LOWER(email) on PostgreSQL, Oracle, SQLite and MySQL 8.0.13+, the version that added functional key parts, or a citext column on PostgreSQL. On SQL Server and MySQL a plain unique index already ignores case under the default CI collations; a _bin or CS collation on either engine makes it case-sensitive again. The audit query still comes first: existing duplicates make CREATE UNIQUE INDEX fail, so merge them before you create it."},{"question":"Does LOWER destroy the spelling I should keep?","answer":"No: LOWER only builds the grouping key, and STRING_AGG still lists the stored spellings so the merge can keep the best-formatted one. Rewriting survivors to lowercase is a separate UPDATE and a separate decision."}]},"source_url":"https://sqlly.app/sql-snippets/case-insensitive-duplicate-emails","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/change-column-nullable","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Change a column to nullable","description":"Relax NOT NULL on a column on each engine. Allowing NULLs needs no data check, so it is fast; the cost is in application code.","body":{"slug":"change-column-nullable","name":"Change column to nullable","h1":"Change a column to nullable","category":"schema","lede":"Relaxing a column to allow NULLs is the safe direction: no data can violate it. The work is in the application code that suddenly has to handle NULL.","engine_slug":"postgresql","problem":"A field that used to be mandatory now legitimately has no value for some rows, so the constraint must be relaxed without a data check or a long lock.","sql":"ALTER TABLE orders\n  ALTER COLUMN discount_code DROP NOT NULL;","how_it_works":"DROP NOT NULL is catalog-only on PostgreSQL regardless of table size, because allowing NULLs needs no check of existing rows. The cost lands in the code that reads the column: arithmetic and || concatenation with a NULL return NULL, WHERE discount_code <> 'X' silently skips NULL rows, aggregates such as SUM and COUNT(col) ignore them, and ORM models need the field marked optional.","variants":[{"sql":"ALTER TABLE dbo.Orders\n    ALTER COLUMN DiscountCode NVARCHAR(50) NULL;\n-- restating the type is required on SQL Server"},{"sql":"ALTER TABLE orders\n  MODIFY COLUMN discount_code VARCHAR(50) NULL;\n-- restate the default and comment too; InnoDB rebuilds the\n-- table in place for this change"},{"sql":"-- SQLite cannot alter nullability in place; rebuild the\n-- table with the column declared nullable"}],"see_also":["make-column-not-null-safely","widen-column-type","remove-column-default"],"faqs":[{"question":"Can I roll this back later?","answer":"Yes, in the NOT NULL direction, but that needs the check-backfill-enforce sequence from the make-column-not-null recipe because NULLs may have appeared since. Relax first, tighten only after code guarantees a value."}]},"source_url":"https://sqlly.app/sql-snippets/change-column-nullable","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/check-constraint-violation-preview","corpus":"sql-snippets","engine":"all","language":"en","title":"Preview rows failing a CHECK constraint","description":"SELECT the rows a planned CHECK constraint would reject. Run it before the ALTER TABLE.","body":{"slug":"check-constraint-violation-preview","name":"CHECK preview","h1":"Preview rows failing a CHECK constraint","category":"data-quality","lede":"Express the planned CHECK as a predicate, then select rows where NOT (predicate) holds: exactly what ALTER TABLE ... ADD CONSTRAINT would reject.","engine_slug":"all","problem":"You plan to add CHECK (total >= 0 AND (status <> 'shipped' OR total > 0)) to orders. If any existing row fails it, the ALTER fails; this preview finds the blockers first.","sql":"-- Planned constraint:\n-- CHECK (total >= 0 AND (status <> 'shipped' OR total > 0))\nSELECT id, status, total\nFROM orders\nWHERE NOT (total >= 0 AND (status <> 'shipped' OR total > 0));","how_it_works":"A CHECK constraint rejects a row only when its predicate is false; true and unknown (a NULL somewhere in the comparison) both pass. A WHERE clause keeps only rows where its condition is true, so WHERE NOT (predicate) returns exactly the rows where the predicate is false: the ones ALTER TABLE would reject. Rows with a NULL total make both sides unknown and are correctly left out, since the constraint would accept them. An empty result means the constraint can be added right now. (SQL Server can also add it WITH NOCHECK and skip existing rows, but then the optimizer treats the constraint as untrusted.)","variants":[{"sql":"SELECT 'negative total' AS violation, COUNT(*) AS rows_blocked\nFROM orders WHERE NOT (total >= 0)\nUNION ALL\nSELECT 'shipped with non-positive total', COUNT(*)\nFROM orders WHERE status = 'shipped' AND NOT (total > 0);"}],"see_also":["rows-violating-business-rule","impossible-dates"],"faqs":[{"question":"Why wrap the predicate in NOT instead of rewriting it?","answer":"Because hand-inverting a compound rule is where previews go wrong. NOT (total >= 0 AND (status <> 'shipped' OR total > 0)) is guaranteed to be the exact complement of what the CHECK tests, with the same NULL behavior; a rewritten version such as total < 0 OR (status = 'shipped' AND total <= 0) happens to match here, but one misplaced parenthesis or flipped operator in a bigger rule and the preview no longer predicts the ALTER."},{"question":"Does the preview match what ADD CONSTRAINT would reject?","answer":"The row set matches, because the constraint check and WHERE NOT (predicate) share one truth table, but the ALTER stops at the first offending row while the query lists them all. Drive the count to zero with the preview and the constraint then validates cleanly."}]},"source_url":"https://sqlly.app/sql-snippets/check-constraint-violation-preview","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/checkpoint-warnings","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Check for checkpoint pressure in PostgreSQL","description":"Compares timed and requested checkpoints in pg_stat_checkpointer (pg_stat_bgwriter before PostgreSQL 17) to tell whether max_wal_size is forcing early checkpoints.","body":{"slug":"checkpoint-warnings","name":"Checkpoint warnings","h1":"Check for checkpoint pressure in PostgreSQL","category":"monitoring","lede":"A requested checkpoint is one that WAL volume forced before the schedule. This query shows how many of yours were forced.","engine_slug":"postgresql","problem":"A checkpoint writes every dirty page in shared_buffers to disk so older WAL can be recycled. PostgreSQL starts one when checkpoint_timeout (5 minutes by default) has passed since the last one, which counts as timed, or earlier when the WAL written since the last one approaches max_wal_size (1 GB by default), which counts as requested, as does a manual CHECKPOINT. Requested checkpoints that happen often mean max_wal_size is too small for the write load: checkpoints run back to back, and every page modified after each one writes a full-page image into WAL.","sql":"SELECT num_timed, num_requested,\n       ROUND(100.0 * num_requested / NULLIF(num_timed + num_requested, 0), 1) AS requested_pct,\n       ROUND(write_time::numeric / 1000) AS write_seconds_total,\n       ROUND(sync_time::numeric / 1000) AS sync_seconds_total,\n       buffers_written,\n       stats_reset\nFROM pg_stat_checkpointer;","how_it_works":"pg_stat_checkpointer exists from PostgreSQL 17; on older versions the same counters are columns of pg_stat_bgwriter (the variant). num_timed counts checkpoints that checkpoint_timeout scheduled, including ones the engine skipped because nothing had changed, and num_requested counts checkpoints that WAL volume or a CHECKPOINT command forced. A requested_pct that stays low means the schedule is in charge. When it runs high, raise max_wal_size until the checkpointer times most checkpoints, then confirm with log_checkpoints = on (on by default since PostgreSQL 15), which logs each checkpoint with its cause and duration. write_time and sync_time are in milliseconds. checkpoint_completion_target (0.9 by default) spreads each checkpoint's writes over most of the interval, which is why write time is large and harmless while sync time should stay small. pg_stat_reset_shared('checkpointer') zeroes every counter in this view, so record the reset time next to any percentage you chart.","variants":[{"sql":"SELECT checkpoints_timed, checkpoints_req,\n       ROUND(100.0 * checkpoints_req / NULLIF(checkpoints_timed + checkpoints_req, 0), 1) AS requested_pct,\n       ROUND(checkpoint_write_time::numeric / 1000) AS write_seconds_total,\n       ROUND(checkpoint_sync_time::numeric / 1000) AS sync_seconds_total,\n       buffers_checkpoint, buffers_clean, buffers_backend\nFROM pg_stat_bgwriter;"},{"sql":"SELECT\n  (SELECT VARIABLE_VALUE FROM performance_schema.global_status\n    WHERE VARIABLE_NAME = 'Innodb_redo_log_current_lsn')\n  - (SELECT VARIABLE_VALUE FROM performance_schema.global_status\n      WHERE VARIABLE_NAME = 'Innodb_redo_log_checkpoint_lsn') AS checkpoint_age_bytes,\n  (SELECT VARIABLE_VALUE FROM performance_schema.global_variables\n    WHERE VARIABLE_NAME = 'innodb_redo_log_capacity') AS redo_capacity_bytes,\n  (SELECT VARIABLE_VALUE FROM performance_schema.global_status\n    WHERE VARIABLE_NAME = 'Innodb_buffer_pool_pages_dirty') AS dirty_pages,\n  (SELECT VARIABLE_VALUE FROM performance_schema.global_status\n    WHERE VARIABLE_NAME = 'Innodb_log_waits') AS log_waits;"}],"see_also":["wal-redo-size","replication-lag","database-growth-by-month"],"faqs":[{"question":"What does the checkpoint warning in the log mean?","answer":"The log line LOG: checkpoints are occurring too frequently (N seconds apart), with a hint to consider increasing max_wal_size, is written when a checkpoint forced by WAL volume starts less than checkpoint_warning (30 seconds by default) after the previous one. The fix is raising max_wal_size; it can be changed with a reload, no restart. Size it so a normal busy period fits between timed checkpoints, and check that the warning stops."},{"question":"Is frequent checkpointing really harmful?","answer":"Yes, in two ways. A page updated many times between two checkpoints is written to disk once per checkpoint, so more checkpoints mean more data-file writes for the same work. And with full_page_writes on (the default), the first change to each page after a checkpoint writes the whole 8 KB page into WAL, so frequent checkpoints inflate WAL volume, archive size and replication traffic. The cost of spacing them further apart is longer crash recovery, since more WAL has to be replayed."}]},"source_url":"https://sqlly.app/sql-snippets/checkpoint-warnings","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/checksum-a-table","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Compute a checksum over a table","description":"Hash every row's concatenated values and aggregate the hashes into one checksum per table.","body":{"slug":"checksum-a-table","name":"Checksum a table","h1":"Compute a checksum over a table","category":"data-quality","lede":"Concatenate each row's columns into a stable string, hash it, then aggregate all row hashes into a single value that changes when any row does.","engine_slug":"postgresql","problem":"Two environments should hold identical orders data. Comparing every row is too slow over the wire; one checksum per table is enough to say whether they differ.","sql":"SELECT MD5(STRING_AGG(MD5(CAST(o AS TEXT)), ',' ORDER BY o.id)) AS table_checksum\nFROM orders o;","how_it_works":"CAST(o AS TEXT) turns the whole row into its text form, such as (6,,2026-01-07,,paid,0.01,...), with every column in table order and NULLs as empty fields, and MD5 hashes it. Hand-concatenating columns with || is the classic mistake here: one NULL column makes the whole string NULL, STRING_AGG skips it, and that row silently drops out of the checksum. STRING_AGG with ORDER BY o.id folds the row hashes in a fixed order, so the result does not depend on how rows are stored, and the outer MD5 reduces it to 32 hex characters. Any changed, inserted or deleted row changes it. Both sides must have the same column order and types for the text forms to match.","variants":[{"sql":"SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) AS table_checksum\nFROM orders;"},{"sql":"SELECT COUNT(*) AS row_count,\n       SUM(id) AS id_sum,\n       MAX(id) AS max_id,\n       MAX(updated_at) AS last_change\nFROM orders;"}],"see_also":["compare-table-counts","symmetric-difference-two-tables"],"faqs":[{"question":"Can two different tables share a checksum?","answer":"With MD5 an accidental collision is vanishingly unlikely. SQL Server's BINARY_CHECKSUM and CHECKSUM_AGG are a different matter: they return 32-bit integers, so unrelated changes can produce the same value, and Microsoft's docs warn that CHECKSUM_AGG can miss changes. For a stronger hash use sha256() (built into PostgreSQL 11+) or HASHBYTES('SHA2_256', ...) on SQL Server, and confirm any mismatch with a row-level diff."}]},"source_url":"https://sqlly.app/sql-snippets/checksum-a-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/column-profile-min-max-distinct","corpus":"sql-snippets","engine":"all","language":"en","title":"Profile a column: min, max, distinct","description":"A one-query column profile: row count, min, max, average and distinct values for the columns that matter.","body":{"slug":"column-profile-min-max-distinct","name":"Column profile","h1":"Profile a column: min, max, distinct","category":"data-quality","lede":"Get the shape of a table in one pass: how many rows, the range of each numeric or date column, and how many distinct values a categorical column has.","engine_slug":"all","problem":"You just inherited a database and want a feel for the orders table before writing any report: typical totals, the date range covered, and whether status is really a small set of values.","sql":"SELECT\n  COUNT(*) AS row_count,\n  MIN(order_date) AS earliest_order,\n  MAX(order_date) AS latest_order,\n  MIN(total) AS min_total,\n  MAX(total) AS max_total,\n  AVG(total) AS avg_total,\n  COUNT(DISTINCT status) AS distinct_statuses\nFROM orders;","how_it_works":"Everything aggregates over the whole table, so the result is one row. MIN and MAX give the range for dates and numbers, AVG the center, and COUNT(DISTINCT status) says how many categories exist. If that comes back as 3, status is enum-like and worth grouping by; if it is thousands, it is free text wearing a label.","variants":[{"sql":"SELECT 'order_date' AS column_name,\n       CAST(MIN(order_date) AS VARCHAR(30)) AS min_value,\n       CAST(MAX(order_date) AS VARCHAR(30)) AS max_value\nFROM orders\nUNION ALL\nSELECT 'total', CAST(MIN(total) AS VARCHAR(30)), CAST(MAX(total) AS VARCHAR(30))\nFROM orders\nUNION ALL\nSELECT 'status', MIN(status), MAX(status)\nFROM orders;"},{"sql":"SELECT MIN(total) AS min_total, MAX(total) AS max_total, AVG(total) AS avg_total\nFROM orders\nWHERE order_date >= CURRENT_DATE - 30;"}],"see_also":["null-counts-per-column","value-distribution-histogram","dominant-value-frequency"],"faqs":[{"question":"Does COUNT(DISTINCT status) include NULLs?","answer":"No. DISTINCT aggregates ignore NULLs, so a column that is 90 percent NULL but has two real values reports 2. That is usually what you want for a cardinality check; pair this query with the NULL-count recipe when the missing-data share matters too."}]},"source_url":"https://sqlly.app/sql-snippets/column-profile-min-max-distinct","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/comment-column-script","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Comment a column and its table","description":"Attach descriptions to columns and tables so the schema documents itself: COMMENT ON in PostgreSQL, COMMENT clauses in MySQL, extended properties in SQL Server.","body":{"slug":"comment-column-script","name":"Comment a column","h1":"Comment a column and its table","category":"schema","lede":"A column comment tells the next reader what the value means and what unit it is in, and it travels with the schema. Each engine stores these comments differently.","engine_slug":"postgresql","problem":"Nobody remembers what a column is for or what units a value carries, and the answer currently lives in one person's head. Write it into the schema.","sql":"COMMENT ON COLUMN public.users.email\n  IS 'Primary login address, verified at signup';\nCOMMENT ON TABLE public.users\n  IS 'Application accounts; one row per registered user';","how_it_works":"PostgreSQL stores comments in pg_description, keyed to the object, and COMMENT ON replaces any existing text, so re-running it is safe; COMMENT ... IS NULL removes one. psql shows column comments in \\d+ output, and col_description(table_oid, column_number) reads one back. Dropping and recreating a column or table drops its comment, so migrations that rebuild objects must re-apply them.","variants":[{"sql":"-- the comment is part of the column definition, so MODIFY must\n-- restate the full type, nullability and default or lose them\nALTER TABLE users\n  MODIFY COLUMN email VARCHAR(320) NOT NULL\n  COMMENT 'Primary login address, verified at signup';\n-- table comment:\nALTER TABLE users COMMENT = 'Application accounts';"},{"sql":"EXEC sp_addextendedproperty\n    @name = N'MS_Description',\n    @value = N'Primary login address, verified at signup',\n    @level0type = N'SCHEMA', @level0name = N'dbo',\n    @level1type = N'TABLE',  @level1name = N'Users',\n    @level2type = N'COLUMN', @level2name = N'Email';\n-- re-running needs sp_updateextendedproperty, or drop first"}],"see_also":["describe-table-columns","list-table-columns","set-column-default"],"faqs":[{"question":"Can I read all column comments at once?","answer":"Yes. On PostgreSQL, select col_description(format('%I.%I', table_schema, table_name)::regclass, ordinal_position) alongside information_schema.columns. MySQL has them in information_schema.columns.column_comment. On SQL Server, fn_listextendedproperty(N'MS_Description', N'SCHEMA', N'dbo', N'TABLE', N'Users', N'COLUMN', NULL) returns one row per commented column."},{"question":"How long can a comment be?","answer":"MySQL caps column comments at 1024 characters and table comments at 2048. PostgreSQL's pg_description takes text of any length, and SQL Server stores the MS_description extended property as a value that comfortably holds a paragraph."}]},"source_url":"https://sqlly.app/sql-snippets/comment-column-script","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/compare-strings-ignoring-case-accents","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Compare strings ignoring case and accents in SQL","description":"Make 'JOSE' match 'José' and 'garcia' match 'García' with collations instead of rewriting the text.","body":{"slug":"compare-strings-ignoring-case-accents","name":"Compare strings ignoring case and accents","h1":"Compare strings ignoring case and accents in SQL","category":"text","lede":"Name matching fails on case and accents. Collations let the comparison itself ignore both.","engine_slug":"sql-server","problem":"Instead of cleaning the strings, tell the comparison to ignore differences: a CI_AI (case-insensitive, accent-insensitive) collation does that per expression.","sql":"SELECT *\nFROM customers c\nWHERE c.last_name COLLATE Latin1_General_CI_AI = 'garcia';","how_it_works":"COLLATE applies only to that comparison, leaving the stored data untouched. Latin1_General_CI_AI ignores case and accents, so 'garcia' = 'García'. The cost is index use: the comparison will not use a plain index on last_name unless the column itself has a matching collation. On PostgreSQL 12+, a nondeterministic ICU collation (CREATE COLLATION ... provider = icu, deterministic = false) gives the same column-level behaviour.","variants":[{"sql":"SELECT *\nFROM customers c\nWHERE unaccent(lower(c.last_name)) = unaccent(lower('garcia'));"},{"sql":"SELECT *\nFROM customers c\nWHERE c.last_name = 'garcia' COLLATE utf8mb4_0900_ai_ci;"}],"see_also":["strip-diacritics-accents","title-case-names"],"faqs":[{"question":"Why not just LOWER both sides?","answer":"LOWER fixes case only. It does nothing about accents, so 'garcia' still misses 'García'. Case- and accent-insensitive collations (or unaccent on PostgreSQL) handle both at once."}]},"source_url":"https://sqlly.app/sql-snippets/compare-strings-ignoring-case-accents","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/compare-table-counts","corpus":"sql-snippets","engine":"all","language":"en","title":"Compare row counts across tables","description":"Stack COUNT(*) per table with UNION ALL for a one-query census, or a before/after migration diff.","body":{"slug":"compare-table-counts","name":"Compare table counts","h1":"Compare row counts across tables","category":"data-quality","lede":"COUNT each table in one UNION ALL query and, optionally, compute the difference against a baseline or a second environment.","engine_slug":"all","problem":"After a migration you want the row census of source and target tables side by side. Counts that match are the cheapest possible integrity signal.","sql":"SELECT 'customers' AS table_name, COUNT(*) AS row_count FROM customers\nUNION ALL\nSELECT 'orders', COUNT(*) FROM orders\nUNION ALL\nSELECT 'order_items', COUNT(*) FROM order_items\nUNION ALL\nSELECT 'products', COUNT(*) FROM products\nORDER BY row_count DESC;","how_it_works":"Each branch counts one table and tags the count with a name; UNION ALL glues them into a small report. There are no joins, and most engines answer COUNT(*) by scanning the smallest index rather than the table, so this is the cheapest integrity check you can run on big data. The variant extends the same pattern to source-versus-target comparisons; when the two sides live in different databases, run each half there and compare the numbers.","variants":[{"sql":"SELECT s.table_name, s.source_count, t.target_count,\n       t.target_count - s.source_count AS difference\nFROM (\n  SELECT 'customers' AS table_name, COUNT(*) AS source_count FROM customers\n  UNION ALL\n  SELECT 'orders', COUNT(*) FROM orders\n) s\nJOIN (\n  SELECT 'customers' AS table_name, COUNT(*) AS target_count FROM customers_archive\n  UNION ALL\n  SELECT 'orders', COUNT(*) FROM orders_archive\n) t ON t.table_name = s.table_name;"}],"see_also":["checksum-a-table","symmetric-difference-two-tables"],"faqs":[{"question":"Counts match. Can I trust the migration?","answer":"Matching counts are necessary but not sufficient: rows can differ in content while counting the same. Treat equal counts as the cheap first gate, then run a checksum or a symmetric difference on the tables that matter before declaring the migration done."},{"question":"Why is COUNT(*) cheap even on the big table?","answer":"Each engine reads the smallest structure that covers the whole table: PostgreSQL scans the narrowest index, and InnoDB scans its clustered index, neither of which touches long columns. A COUNT with a WHERE clause loses that shortcut and reads the actual rows."}]},"source_url":"https://sqlly.app/sql-snippets/compare-table-counts","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/conflicting-facts-across-tables","corpus":"sql-snippets","engine":"all","language":"en","title":"Find conflicting facts across tables","description":"Join tables that should agree (order vs invoice total) and list every pair that disagrees.","body":{"slug":"conflicting-facts-across-tables","name":"Conflicting facts","h1":"Find conflicting facts across tables","category":"data-quality","lede":"Join on the shared key and filter with <> on the facts that must match: every hit is one table contradicting the other.","engine_slug":"all","problem":"orders.total and invoices.amount should tell the same story for the same order. Discounts applied in one system and not the other make them drift. This finds the drift.","sql":"SELECT i.id AS invoice_id, i.order_id,\n       i.amount AS invoice_amount,\n       o.total AS order_total,\n       i.amount - o.total AS discrepancy\nFROM invoices i\nJOIN orders o ON o.id = i.order_id\nWHERE i.amount <> o.total\nORDER BY ABS(i.amount - o.total) DESC;","how_it_works":"The join pairs each invoice with its order on the shared id; the WHERE keeps pairs whose money facts disagree. Computing the discrepancy per row (and ordering by its absolute size) turns the list into a reconciliation worklist, biggest mismatches first. Rows with no counterpart on either side need the orphan checks instead.","variants":[{"sql":"SELECT i.id AS invoice_id, i.order_id,\n       i.amount AS invoice_amount, o.total AS order_total,\n       CASE WHEN o.id IS NULL THEN 'no matching order'\n            ELSE 'amounts differ' END AS issue\nFROM invoices i\nLEFT JOIN orders o ON o.id = i.order_id\nWHERE o.id IS NULL OR i.amount <> o.total;"},{"sql":"SELECT i.id, i.order_id, i.amount, o.total\nFROM invoices i\nJOIN orders o ON o.id = i.order_id\nWHERE ABS(i.amount - o.total) > 0.005;"}],"see_also":["symmetric-difference-two-tables","find-orphaned-rows","overlapping-ranges"],"faqs":[{"question":"Why the ABS tolerance variant for money?","answer":"Only when one side is a FLOAT or REAL column, or the amounts arrived through floating-point code. Binary floating point stores 0.1 approximately, so two logically equal amounts can differ by a hair and a strict <> flags them. Comparing the absolute difference against half a cent (0.005) absorbs that noise while still catching real discrepancies. With DECIMAL or NUMERIC on both sides the plain <> is exact and the tolerance only hides rounding differences you may want to see."}]},"source_url":"https://sqlly.app/sql-snippets/conflicting-facts-across-tables","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/connection-saturation","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Check connection saturation against max_connections in PostgreSQL","description":"Compares current connections to the max_connections limit with headroom and lock-wait counts, so you know you are running out before the errors start.","body":{"slug":"connection-saturation","name":"Connection saturation","h1":"Check connection saturation against max_connections in PostgreSQL","category":"monitoring","lede":"The connection refused error arrives after saturation, not before. This query shows the trend while there is still headroom.","engine_slug":"postgresql","problem":"When connections approach max_connections, new ones fail with the too many clients error, often during a traffic spike, exactly when you cannot afford it. Watching the used percentage turns that outage into a warning. Connections waiting on locks also deserve counting: they hold their slots while contributing no work.","sql":"WITH s AS (\n    SELECT current_setting('max_connections')::int AS max_conn,\n           current_setting('superuser_reserved_connections')::int\n             + COALESCE(current_setting('reserved_connections', true)::int, 0) AS reserved,\n           (SELECT COUNT(*) FROM pg_stat_activity WHERE backend_type = 'client backend') AS used,\n           (SELECT COUNT(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock') AS waiting_on_locks\n)\nSELECT used AS connections, max_conn AS max_connections, reserved,\n       ROUND(100.0 * used / NULLIF(max_conn - reserved, 0), 1) AS pct_used,\n       waiting_on_locks\nFROM s;","how_it_works":"The query counts client backends only; background processes have their own slots outside max_connections. The percentage is computed against the slots an ordinary role can use: max_connections minus superuser_reserved_connections and, on PostgreSQL 16 and later, reserved_connections (for roles granted pg_use_reserved_connections). current_setting with true as the second argument returns NULL instead of an error on older versions that lack the setting, and COALESCE turns that into 0. Sustained use above roughly 80 percent is where you add pooling (pgbouncer in transaction mode), resize the pool, or fix whichever application is leaking connections. An elevated waiting_on_locks alongside high usage often means one stuck transaction is holding up many pooled connections. In the SQL Server variant, a user connections setting of 0 means no configured limit below @@MAX_CONNECTIONS (32,767).","variants":[{"sql":"SELECT variable_name, variable_value\nFROM performance_schema.global_status\nWHERE variable_name IN ('Threads_connected', 'Threads_running', 'Max_used_connections')\nUNION ALL\nSELECT 'max_connections', variable_value\nFROM performance_schema.global_variables\nWHERE variable_name = 'max_connections';"},{"sql":"SELECT (SELECT COUNT(*) FROM sys.dm_exec_sessions WHERE is_user_process = 1) AS user_sessions,\n       (SELECT COUNT(*) FROM sys.dm_exec_connections) AS connections,\n       (SELECT CAST(value_in_use AS INT) FROM sys.configurations\n        WHERE name = 'user connections') AS user_connections_setting,\n       @@MAX_CONNECTIONS AS max_allowed;"}],"see_also":["connections-by-state","idle-in-transaction","kill-query-safely"],"faqs":[{"question":"Should I just raise max_connections?","answer":"Every connection is a process with real memory overhead, and more often means more contention, not more throughput. If you genuinely need thousands of concurrent client connections, put pgbouncer (PostgreSQL), ProxySQL (MySQL) or an app-side pool in front and raise max only as far as the workload demonstrably uses."},{"question":"What are superuser_reserved_connections for?","answer":"A small reserve, 3 slots by default, that only superusers can use once ordinary connections are exhausted, so an administrator can still log in and diagnose while applications get the too many clients error. PostgreSQL 16 added reserved_connections (default 0) for non-superuser roles granted pg_use_reserved_connections, such as a monitoring role. Neither adds capacity for applications."}]},"source_url":"https://sqlly.app/sql-snippets/connection-saturation","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/connections-by-state","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Count connections by state, database and user in PostgreSQL","description":"Groups pg_stat_activity by state, then by database and user, to see at a glance where every connection is and what it is doing.","body":{"slug":"connections-by-state","name":"Connections by state","h1":"Count connections by state, database and user in PostgreSQL","category":"monitoring","lede":"A short GROUP BY over pg_stat_activity answers the first connection questions: how many sessions, from which database and user, doing what.","engine_slug":"postgresql","problem":"Connection debugging starts with distribution, not detail. Grouping pg_stat_activity by state shows how many sessions are active, idle, or idle in transaction; grouped by database and user, the same rows show which application holds the connections. Start here before looking at individual pids.","sql":"SELECT backend_type, state, COUNT(*) AS sessions\nFROM pg_stat_activity\nGROUP BY backend_type, state\nORDER BY sessions DESC;","how_it_works":"pg_stat_activity has one row per server process, background processes included, so the query groups by backend_type as well; client connections are 'client backend'. For those, state is active while a statement runs, idle between statements, and idle in transaction inside an open transaction that is not running anything. Background processes such as the checkpointer and autovacuum launcher have a NULL state. A large idle count usually means a generously sized connection pool and is harmless; a growing idle in transaction count is not. Ordinary roles can use max_connections minus superuser_reserved_connections (and minus reserved_connections on PostgreSQL 16 and later), so applications hit the limit before the count reaches max_connections.","variants":[{"sql":"SELECT datname, usename, state,\n       COUNT(*) AS sessions,\n       COUNT(*) FILTER (WHERE wait_event_type = 'Lock') AS waiting_on_locks,\n       COUNT(*) FILTER (WHERE state = 'idle in transaction') AS idle_in_txn\nFROM pg_stat_activity\nWHERE backend_type = 'client backend'\nGROUP BY datname, usename, state\nORDER BY datname, sessions DESC;"},{"sql":"SELECT s.status, COUNT(*) AS sessions\nFROM sys.dm_exec_sessions s\nWHERE s.is_user_process = 1\nGROUP BY s.status\nORDER BY sessions DESC;"}],"see_also":["connection-saturation","idle-in-transaction","long-transactions"],"faqs":[{"question":"What is a healthy state distribution?","answer":"For a pooled OLTP application: mostly idle (the pool keeping connections ready), an active count around the number of CPU cores or below, and close to zero idle in transaction. Active sessions far above the core count mean they are queueing for CPU or locks, and a transaction-mode pooler such as PgBouncer in front of the database usually helps more than more connections."},{"question":"Why do background sessions show state NULL?","answer":"The checkpointer, WAL writer, autovacuum launcher and similar internal processes have no client session, so state is NULL. Add WHERE backend_type = 'client backend' when you only care about application connections, as the variant does."}]},"source_url":"https://sqlly.app/sql-snippets/connections-by-state","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/convert-local-to-utc","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Convert local wall time to UTC in SQL","description":"Turn wall-clock times captured in a local zone into UTC instants, DST-aware, before storing them.","body":{"slug":"convert-local-to-utc","name":"Convert local time to UTC","h1":"Convert local wall time to UTC in SQL","category":"text","lede":"Schedulers capture '2026-03-08 01:30 Eastern' but the database should store UTC. The conversion must respect DST gaps.","engine_slug":"sql-server","problem":"Declare the wall time's zone, then convert: two AT TIME ZONE steps, DST-aware both times.","sql":"SELECT local_time\n           AT TIME ZONE 'Eastern Standard Time'\n           AT TIME ZONE 'UTC' AS utc_time\nFROM schedule_items;","how_it_works":"The first AT TIME ZONE attaches the Eastern offset in force at that wall time to the naive datetime, producing a datetimeoffset; the second shifts it to +00:00, still as a datetimeoffset (CAST it to datetime2 to store a plain UTC value). On the spring-forward night a nonexistent local time like 02:30 is moved forward an hour (03:30 EDT, 07:30 UTC) on both SQL Server and PostgreSQL. On the fall-back night 01:30 happens twice and the engines disagree without warning: SQL Server takes the daylight offset (05:30 UTC), PostgreSQL the standard one (06:30 UTC).","variants":[{"sql":"SELECT local_time\n           AT TIME ZONE 'America/New_York'\n           AT TIME ZONE 'UTC' AS utc_time\nFROM schedule_items;"}],"see_also":["normalize-stored-utc","epoch-conversions-both-ways"],"faqs":[{"question":"Which zone names does each engine accept?","answer":"SQL Server wants Windows names ('Eastern Standard Time', 'W. Europe Standard Time'); PostgreSQL wants IANA names ('America/New_York', 'Europe/Berlin'). They are looked up in the OS or tzdata databases, so keep them configurable rather than hardcoded."},{"question":"Should I keep the datetimeoffset instead of casting down?","answer":"Often yes: datetimeoffset preserves the original offset, so you can still tell whether a wall time fell in the spring gap or the fall-back overlap. A plain datetime2 keeps only the converted value and throws that question away permanently."}]},"source_url":"https://sqlly.app/sql-snippets/convert-local-to-utc","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/copy-import-progress","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Track COPY and import progress in PostgreSQL","description":"Joins pg_stat_progress_copy with pg_stat_activity to show live COPY operations with bytes processed, total and percent done.","body":{"slug":"copy-import-progress","name":"COPY import progress","h1":"Track COPY and import progress in PostgreSQL","category":"monitoring","lede":"A long COPY prints nothing until it finishes. pg_stat_progress_copy shows how far it has got while it runs.","engine_slug":"postgresql","problem":"pg_stat_progress_copy (PostgreSQL 14 and later) has one row per backend running a COPY, in either direction. For COPY FROM a server-side file it knows the file size, so bytes_processed against bytes_total gives a real percentage; for every COPY it counts tuples processed. The pid joins to pg_stat_activity for the user and start time. Client-side imports such as psql's \\copy run COPY FROM STDIN on the server, so they appear here too, just without a total.","sql":"SELECT p.pid,\n       p.datname,\n       a.usename,\n       p.command,\n       p.type,\n       p.bytes_processed, p.bytes_total,\n       ROUND(100.0 * p.bytes_processed / NULLIF(p.bytes_total, 0), 1) AS pct_done,\n       p.tuples_processed,\n       now() - a.query_start AS running_for\nFROM pg_stat_progress_copy p\nLEFT JOIN pg_stat_activity a ON a.pid = p.pid\nORDER BY p.bytes_processed DESC;","how_it_works":"command is COPY FROM or COPY TO, and type is FILE, PROGRAM, PIPE (STDIN or STDOUT) or CALLBACK (logical replication's initial table sync). bytes_total is known only for COPY FROM a file; it is 0 otherwise, and NULLIF turns the percentage into NULL instead of a division error. tuples_processed is then the progress signal. The LEFT JOIN to pg_stat_activity adds who is running it and for how long. Imports done with batched INSERT statements do not appear here at all. Index builds afterwards have their own view, pg_stat_progress_create_index, shown in the variant.","variants":[{"sql":"SELECT pid, datname, relid::regclass AS table_name,\n       index_relid::regclass AS index_name, command, phase,\n       blocks_done, blocks_total,\n       ROUND(100.0 * blocks_done / NULLIF(blocks_total, 0), 1) AS pct_of_phase\nFROM pg_stat_progress_create_index\nORDER BY pid;"}],"see_also":["longest-running-queries-now","long-transactions","kill-query-safely"],"faqs":[{"question":"bytes_total is 0. How do I estimate progress?","answer":"STDIN and pipe sources stream without a declared size. Compare tuples_processed with the row count you expect (wc -l on the source file is close enough for CSV without embedded newlines), or sample tuples_processed twice a minute apart and divide the remaining rows by that rate."},{"question":"The COPY is slow but has a high percentage. Kill it or let it finish?","answer":"Usually let it finish, unless it is blocking something more important. A COPY is all or nothing: cancelling it rolls back every row loaded so far, and those rows stay behind as dead space until vacuum removes them. PostgreSQL 17 added ON_ERROR ignore for COPY FROM, which skips rows with data type errors instead of failing the whole load; the skipped count appears as tuples_skipped in this view."}]},"source_url":"https://sqlly.app/sql-snippets/copy-import-progress","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/copy-table-structure-only","corpus":"sql-snippets","engine":"mysql","language":"en","title":"Copy a table's structure only","description":"Clone a table's columns and indexes with zero rows (LIKE on MySQL and PostgreSQL, SELECT TOP 0 INTO on SQL Server) and see what each method leaves out.","body":{"slug":"copy-table-structure-only","name":"Copy a table's structure","h1":"Copy a table's structure only","category":"schema","lede":"Backups before risky work, staging twins of production tables, and test fixtures all start with an empty copy of a table's shape. Each engine has its own way.","engine_slug":"mysql","problem":"A destructive migration is scheduled and you want a scratch copy of the table's definition to test against first, without moving the data.","sql":"CREATE TABLE users_backup LIKE users;\n-- columns, types, defaults, indexes and CHECK constraints are\n-- copied; rows and foreign keys are not","how_it_works":"CREATE TABLE ... LIKE copies the column definitions, defaults, indexes and (from MySQL 8.0.16) CHECK constraints, and runs instantly because it reads no rows. Foreign keys are not copied, though the index that backed each one is, and the AUTO_INCREMENT counter starts again from 1. Triggers and grants stay with the original.","variants":[{"sql":"-- column names, types and NOT NULL only\nCREATE TABLE users_backup (LIKE users);\n-- or, including defaults, constraints and indexes:\nCREATE TABLE users_backup_full (LIKE users INCLUDING ALL);"},{"sql":"SELECT TOP 0 * INTO dbo.Users_Backup FROM dbo.Users;\n-- copies columns, nullability and the IDENTITY property;\n-- no indexes, keys, defaults, checks or triggers"},{"sql":"-- via the schema text from sqlite_master:\nSELECT sql FROM sqlite_master WHERE name = 'users';\n-- rewrite the table name in that DDL and execute it"}],"see_also":["create-empty-like-table","copy-table-with-data","create-table-if-not-exists"],"faqs":[{"question":"Why is the copy missing my foreign keys?","answer":"None of these methods copies foreign keys: MySQL's LIKE, PostgreSQL's LIKE even with INCLUDING ALL, and SELECT INTO all leave them out. Add them to the copy with ALTER TABLE ... ADD CONSTRAINT if the copy needs to enforce them; list-foreign-keys-targets shows the definitions to reproduce."},{"question":"What does the SQLite copy lose?","answer":"CREATE TABLE ... AS SELECT in SQLite creates bare columns: no primary key, no defaults, no indexes and no NOT NULL survive the copy. Declare the new table with an explicit CREATE listing the columns, then INSERT ... SELECT the rows when those properties matter."}]},"source_url":"https://sqlly.app/sql-snippets/copy-table-structure-only","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/copy-table-with-data","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Copy a table with its data","description":"Full-table clone with CREATE TABLE AS SELECT and its per-engine equivalents, and which constraints and indexes the copy loses.","body":{"slug":"copy-table-with-data","name":"Copy a table with data","h1":"Copy a table with its data","category":"schema","lede":"Copying a table with its rows gives you a snapshot to compare against or restore from before a risky change. The statement differs per engine, and so does what the copy keeps.","engine_slug":"postgresql","problem":"Before a bulk update or refactor, take a snapshot of the whole table, data included, that you can compare against or restore from.","sql":"CREATE TABLE users_backup AS\nSELECT * FROM users;","how_it_works":"CREATE TABLE AS SELECT copies every row and takes column types from the SELECT, but none of the source's constraints, indexes, defaults or NOT NULL markers, so the copy is a plain table with the same data. That makes it quick to create, and also means nothing stops duplicates or NULLs from entering it later. When you need the constraints too, create the table with LIKE ... INCLUDING ALL (see create-empty-like-table) and INSERT ... SELECT into it.","variants":[{"sql":"CREATE TABLE users_backup LIKE users;\nINSERT INTO users_backup SELECT * FROM users;\n-- LIKE keeps indexes; INSERT ... SELECT copies the rows"},{"sql":"SELECT * INTO dbo.Users_Backup FROM dbo.Users;\n-- keeps nullability and IDENTITY; no indexes, keys,\n-- defaults or checks on the copy"},{"sql":"CREATE TABLE users_backup AS SELECT * FROM users;\n-- declared types become affinities (varchar(50) -> TEXT);\n-- primary key, NOT NULL, defaults and indexes are lost"}],"see_also":["copy-table-structure-only","archive-old-rows-to-history","create-table-if-not-exists"],"faqs":[{"question":"How do I copy a table and keep its indexes?","answer":"On MySQL and PostgreSQL: CREATE TABLE ... LIKE (or LIKE ... INCLUDING ALL on PostgreSQL) first, then INSERT INTO copy SELECT * FROM source. CREATE TABLE AS never creates indexes. For a large copy it is often faster to load the rows first and create the indexes afterwards, since building an index once is cheaper than maintaining it row by row."}]},"source_url":"https://sqlly.app/sql-snippets/copy-table-with-data","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/count-if-recipe","corpus":"sql-snippets","engine":"all","language":"en","title":"Conditional counts (COUNT IF)","description":"Count only the rows matching a condition inside a grouped query, with CASE so one scan answers many questions.","body":{"slug":"count-if-recipe","name":"Conditional counts","h1":"Conditional counts (COUNT IF)","category":"querying","lede":"SUM 0/1 flags per condition instead of one query per condition.","engine_slug":"all","problem":"You want, per customer, how many orders are pending and how many shipped, in one query instead of two.","sql":"SELECT customer_id,\n       SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending_orders,\n       SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS shipped_orders,\n       COUNT(*) AS all_orders\nFROM orders\nGROUP BY customer_id\nORDER BY customer_id;","how_it_works":"The CASE emits 1 for matching rows and 0 otherwise, and the grouped SUM adds the 1s up: a conditional count in one pass. COUNT(CASE WHEN status = 'pending' THEN 1 END) works too, because COUNT skips NULLs. Engines with a FILTER clause (PostgreSQL, SQLite 3.30+) express it directly as COUNT(*) FILTER (WHERE ...).","variants":[{"sql":"SELECT customer_id,\n       COUNT(*) FILTER (WHERE status = 'pending') AS pending_orders,\n       COUNT(*) FILTER (WHERE status = 'shipped') AS shipped_orders\nFROM orders\nGROUP BY customer_id;"}],"see_also":["sum-if-recipe","pivot-rows-to-columns-case","distinct-counts-per-group"],"faqs":[{"question":"What happens if I forget the ELSE 0?","answer":"The CASE yields NULL for non-matching rows and SUM ignores NULLs, so the count is still right, except that a customer with no matching rows gets NULL instead of 0. With AVG the ELSE matters more: ELSE 0 averages over every row, while no ELSE averages over the matching rows only."}]},"source_url":"https://sqlly.app/sql-snippets/count-if-recipe","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/count-substring-occurrences","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Count how many times a substring appears in SQL","description":"Count 'error' hits in a log line with the length-difference trick, portable across engines.","body":{"slug":"count-substring-occurrences","name":"Count substring occurrences","h1":"Count how many times a substring appears in SQL","category":"text","lede":"How many times does 'error' appear in each log line? The length difference after deleting it tells you.","engine_slug":"postgresql","problem":"Count occurrences of a word or token by measuring how much shorter the string gets when the token is deleted.","sql":"SELECT (length(message) - length(replace(lower(message), 'error', ''))) / length('error') AS error_count\nFROM log_lines;","how_it_works":"replace deletes every occurrence, and the character count lost divided by the length of the search term is exactly the number of hits. Dividing by length('error') instead of writing 5 keeps the intent obvious. The count includes occurrences inside words like 'errors'; the FAQ covers that.","variants":[{"sql":"SELECT (LEN(message) - LEN(REPLACE(LOWER(message), 'error', ''))) / LEN('error') AS error_count\nFROM log_lines;"}],"see_also":["find-nth-occurrence-substring","normalize-whitespace"],"faqs":[{"question":"Does this count words or substrings?","answer":"Substrings: 'errors' contains 'error', so it counts. For whole words, pad the search with spaces (replace ' error ') after normalizing whitespace, or use regexp_count with a word-boundary pattern on PostgreSQL 15+ ('\\yerror\\y') or Oracle REGEXP_COUNT ('(^|\\W)error(\\W|$)'). On SQL Server, LEN ignores trailing spaces, so use DATALENGTH when the term can end in a space."},{"question":"Why does my MySQL count come out wrong for a multi-byte search term?","answer":"MySQL's LENGTH counts bytes while CHAR_LENGTH counts characters, and the recipe's arithmetic needs characters on both sides of the division. Swap LENGTH for CHAR_LENGTH whenever the search term can leave ASCII."}]},"source_url":"https://sqlly.app/sql-snippets/count-substring-occurrences","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/create-empty-like-table","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Create an empty table like another table","description":"Create a table with the same constraints, defaults and indexes as an existing one but no rows: INCLUDING ALL on PostgreSQL, LIKE on MySQL, scripted DDL on SQL Server.","body":{"slug":"create-empty-like-table","name":"Create an empty table like another","h1":"Create an empty table like another table","category":"schema","lede":"Rotating tables (orders becomes orders_2026_11) needs a new table with the old one's constraints, defaults and indexes but none of its rows.","engine_slug":"postgresql","problem":"Next month's shard of a rotating table must exist before rows arrive, and a hand-written CREATE TABLE drifts from the original within a release or two.","sql":"CREATE TABLE orders_next (LIKE orders INCLUDING ALL);\n-- columns, defaults, CHECK and NOT NULL constraints, indexes,\n-- identity, storage and comments; no rows and no foreign keys","how_it_works":"INCLUDING ALL turns on every INCLUDING option: comments, compression, constraints, defaults, generated columns, identity, indexes, statistics and storage. Without them, LIKE copies only column names, types and NOT NULL. Even INCLUDING ALL leaves out foreign keys, triggers, grants, ownership and row-level security policies, and an identity column gets its own new sequence that starts from the beginning, not where the original's left off.","variants":[{"sql":"CREATE TABLE orders_next LIKE orders;\n-- LIKE copies columns, indexes and defaults; FKs are skipped"},{"sql":"-- script the table (SMO, or SSMS 'Script Table as CREATE'),\n-- then execute the DDL with a new name\nSELECT TOP 0 * INTO dbo.Orders_Next FROM dbo.Orders; -- types only"},{"sql":"SELECT indexname, indexdef FROM pg_indexes\nWHERE tablename = 'orders_next';\nSELECT conname, pg_get_constraintdef(oid)\nFROM pg_constraint WHERE conrelid = 'orders_next'::regclass;"}],"see_also":["copy-table-structure-only","swap-two-table-names","copy-table-with-data"],"faqs":[{"question":"Why are my foreign keys missing from the clone?","answer":"CREATE TABLE ... LIKE never copies foreign keys on PostgreSQL or MySQL; the INCLUDING CONSTRAINTS option covers CHECK and NOT NULL only. Add them with ALTER TABLE orders_next ADD CONSTRAINT ... FOREIGN KEY, using the definitions from pg_get_constraintdef on the original table."},{"question":"Where does the clone's id counter start?","answer":"At 1: MySQL's LIKE resets the AUTO_INCREMENT counter and PostgreSQL's LIKE gives an identity column its own fresh sequence. If the clone must continue the old numbering, set AUTO_INCREMENT explicitly on MySQL or call setval() on the new sequence on PostgreSQL."}]},"source_url":"https://sqlly.app/sql-snippets/create-empty-like-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/create-table-if-not-exists","corpus":"sql-snippets","engine":"sqlite","language":"en","title":"CREATE TABLE IF NOT EXISTS variants","description":"Idempotent table creation: native IF NOT EXISTS where the engine has it, and an OBJECT_ID guard on SQL Server, which rejects the clause.","body":{"slug":"create-table-if-not-exists","name":"Create table if not exists","h1":"CREATE TABLE IF NOT EXISTS variants","category":"schema","lede":"Scripts that create tables should survive being run twice. Most engines have native IF NOT EXISTS; SQL Server needs a small guard block instead.","engine_slug":"sqlite","problem":"Bootstrap scripts should behave identically on a fresh database and on one that already has the table, without a manual check before each run.","sql":"CREATE TABLE IF NOT EXISTS settings (\n    id    INTEGER PRIMARY KEY,\n    key   TEXT NOT NULL UNIQUE,\n    value TEXT\n);","how_it_works":"IF NOT EXISTS makes CREATE TABLE do nothing when the name is taken (MySQL and PostgreSQL report it as a warning or NOTICE), which is what a replayed migration needs. It only checks the name: if a table of that name exists with different columns, the old shape stays and nothing tells you. On SQL Server, OBJECT_ID with type 'U' returns NULL when no user table of that name exists; even SQL Server 2025 rejects CREATE TABLE IF NOT EXISTS as a syntax error.","variants":[{"sql":"IF OBJECT_ID('dbo.Settings', 'U') IS NULL\nBEGIN\n    CREATE TABLE dbo.Settings (\n        Id INT IDENTITY PRIMARY KEY,\n        [Key] NVARCHAR(200) NOT NULL UNIQUE,\n        [Value] NVARCHAR(MAX) NULL\n    );\nEND;"},{"sql":"CREATE TABLE IF NOT EXISTS settings (\n    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n    key   text NOT NULL UNIQUE,\n    value text\n);"},{"sql":"CREATE TABLE IF NOT EXISTS settings (\n    id    INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n    `key` VARCHAR(200) NOT NULL UNIQUE,\n    value TEXT\n) ENGINE=InnoDB;"}],"see_also":["schema-version-table-recipe","add-column-if-missing","create-empty-like-table"],"faqs":[{"question":"Is IF NOT EXISTS enough for migrations?","answer":"It handles 'run twice', not 'changed since'. If someone added a column by hand, IF NOT EXISTS will not notice the drift. That gap is what migration tools with a versions table (see the schema-version recipe) are for."}]},"source_url":"https://sqlly.app/sql-snippets/create-table-if-not-exists","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/cross-tab-with-totals","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Cross-tab with row and column totals","description":"A status-by-customer matrix whose ROLLUP row carries the column totals, with NULL rows labelled 'All'.","body":{"slug":"cross-tab-with-totals","name":"Cross-tab with totals","h1":"Cross-tab with row and column totals","category":"querying","lede":"Pivot with CASE, then let ROLLUP add the grand-total row in the same scan.","engine_slug":"postgresql","problem":"You want the pivoted status totals per customer plus a final row with the totals for each status, without a second query.","sql":"SELECT CASE WHEN GROUPING(customer_id) = 1 THEN 'All'\n            ELSE CAST(customer_id AS varchar(10)) END AS customer,\n       SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END) AS shipped_total,\n       SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) AS pending_total\nFROM orders\nGROUP BY ROLLUP (customer_id)\nORDER BY GROUPING(customer_id), customer_id;","how_it_works":"ROLLUP adds a summary row where customer_id is NULL; GROUPING() returns 1 on that row so you can label it 'All' instead of a blank. The CASE aggregates stay the same, so the totals row sums each status column. Sorting by GROUPING(customer_id) first puts the 'All' row last and keeps customers in numeric order rather than text order. This exact statement also runs on SQL Server and Oracle; SQLite has no ROLLUP, so fall back to a UNION ALL of the detail and total queries.","variants":[{"sql":"SELECT customer_id,\n       SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END) AS shipped_total\nFROM orders\nGROUP BY customer_id WITH ROLLUP;"},{"sql":"SELECT CAST(customer_id AS CHAR(10)) AS customer,\n       SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END) AS shipped_total\nFROM orders\nGROUP BY customer_id\nUNION ALL\nSELECT 'All',\n       SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END)\nFROM orders;"}],"see_also":["pivot-rows-to-columns-case","percentage-of-total"],"faqs":[{"question":"Why GROUPING() instead of checking for NULL?","answer":"A real customer_id could itself be NULL in messy data. GROUPING() distinguishes the rolled-up summary row from a genuine NULL group, so the label is never wrong."}]},"source_url":"https://sqlly.app/sql-snippets/cross-tab-with-totals","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/cumulative-total-by-month","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Cumulative total by month","description":"Aggregate orders per month, then grow a running sum across the months with one window function.","body":{"slug":"cumulative-total-by-month","name":"Cumulative total by month","h1":"Cumulative total by month","category":"querying","lede":"Group to months first, then a running SUM over the monthly totals.","engine_slug":"postgresql","problem":"You want revenue per month plus a year-to-date running total. Doing the running sum over raw order rows mixes granularities and gives the wrong chart.","sql":"WITH monthly AS (\n  SELECT DATE_TRUNC('month', order_date)::date AS month,\n         SUM(amount) AS month_total\n  FROM orders\n  GROUP BY 1\n)\nSELECT month, month_total,\n       SUM(month_total) OVER (ORDER BY month) AS cumulative_total\nFROM monthly\nORDER BY month;","how_it_works":"The CTE collapses orders into one row per month. The window SUM then runs over those monthly rows, so each month's cumulative total is the sum of all earlier months plus itself. Aggregating first also makes missing months explicit if you fill them from a calendar spine before the window runs. month-over-month-delta swaps the running SUM for LAG when the comparison is same-month-last-year instead of cumulative.","variants":[{"sql":"WITH monthly AS (\n  SELECT DATEFROMPARTS(YEAR(order_date), MONTH(order_date), 1) AS month,\n         SUM(amount) AS month_total\n  FROM orders\n  GROUP BY DATEFROMPARTS(YEAR(order_date), MONTH(order_date), 1)\n)\nSELECT month, month_total,\n       SUM(month_total) OVER (ORDER BY month) AS cumulative_total\nFROM monthly\nORDER BY month;"}],"see_also":["month-over-month-delta","fill-gaps-calendar-spine","running-total"],"faqs":[{"question":"Why aggregate to months before the running sum?","answer":"A running sum over raw rows gives one value per order, so you would still have to pick each month's last row to chart it. Aggregating first leaves the window 12 rows a year instead of one per order, and each row is already the month-end figure."},{"question":"Will the window SUM run on MySQL 5.7 or old SQLite?","answer":"No: window functions need MySQL 8.0+ and SQLite 3.25+ (2018). On those versions a correlated subquery, SELECT (SELECT SUM(b.month_total) FROM monthly b WHERE b.month <= a.month), returns the same running numbers at a worse plan cost."}]},"source_url":"https://sqlly.app/sql-snippets/cumulative-total-by-month","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/database-growth-by-month","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Track database growth by month from backup history in SQL Server","description":"Uses msdb full-backup sizes as a monthly growth history that needs no monitoring agent, and shows how to work out when the disk runs out.","body":{"slug":"database-growth-by-month","name":"Database growth by month","h1":"Track database growth by month from backup history in SQL Server","category":"monitoring","lede":"Backup history is a free size time series you already have. This turns it into a growth chart.","engine_slug":"sql-server","problem":"SQL Server keeps no history of database size, but msdb.dbo.backupset keeps one row per backup, and full backups record backup_size and compressed_backup_size. Grouped by month, that is a growth timeline going back as far as msdb keeps backup history, with no extra monitoring. It only covers backups taken on this instance; if backups run on a secondary replica or through a tool that bypasses msdb, look there instead.","sql":"SELECT database_name,\n       YEAR(backup_start_date) AS yr,\n       MONTH(backup_start_date) AS mo,\n       CAST(MAX(backup_size) / 1048576.0 AS DECIMAL(12,1)) AS max_backup_mb,\n       CAST(MAX(ISNULL(compressed_backup_size, backup_size)) / 1048576.0 AS DECIMAL(12,1)) AS max_compressed_mb\nFROM msdb.dbo.backupset\nWHERE type = 'D'\n  AND is_copy_only = 0\n  AND backup_start_date >= DATEADD(YEAR, -2, GETDATE())\nGROUP BY database_name, YEAR(backup_start_date), MONTH(backup_start_date)\nORDER BY database_name, yr, mo;","how_it_works":"type = 'D' keeps full database backups; log and differential backups measure change, not size. backupset stores database_name rather than a database id, and backup_start_date is in the server's local time, hence GETDATE. Taking MAX per month gives one figure per period however many backups ran. backup_size counts the bytes of used pages written to the backup, so it tracks the data you hold, not the size of the data files; compressed_backup_size is what the backup takes on disk and equals backup_size when compression is off. Divide the free space on the volume by the monthly growth to get the number of months left.","variants":[{"sql":"SELECT YEAR(backup_start_date) AS yr, MONTH(backup_start_date) AS mo,\n       CAST(SUM(backup_size) / 1073741824.0 AS DECIMAL(12,2)) AS total_gb\nFROM msdb.dbo.backupset\nWHERE type = 'D'\nGROUP BY YEAR(backup_start_date), MONTH(backup_start_date)\nORDER BY yr, mo;"}],"see_also":["per-database-file-sizes","table-index-sizes-topn","checkpoint-warnings"],"faqs":[{"question":"How accurate is backup size as a size proxy?","answer":"Close enough for trends. A full backup contains the used pages plus the log needed to make it consistent, so it tracks data volume, while data files can be much larger if they were pre-sized or have free space after deletes. Compare months with each other, not with a file-size report, and use backup_size rather than the compressed figure, which moves whenever the compression setting or the data's compressibility changes."},{"question":"How do I keep backup history from being purged out from under this?","answer":"Backup history is removed by msdb.dbo.sp_delete_backuphistory, usually called from a History Cleanup task in a maintenance plan or from an Agent job, with a cutoff date. If that keeps only a few weeks, the trend disappears. Copy the monthly result into a table of your own on a schedule, or lengthen the cutoff."}]},"source_url":"https://sqlly.app/sql-snippets/database-growth-by-month","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/database-size-summary","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Database size summary","description":"Total database size with a per-schema breakdown, so you know where the space went before you start vacuuming or archiving.","body":{"slug":"database-size-summary","name":"Database size summary","h1":"Database size summary","category":"schema","lede":"The disk filled up, and the question is with what. This recipe totals the database size and breaks it down per schema so you know where the space went.","engine_slug":"postgresql","problem":"Monitoring reports fast growth in the database files and the cleanup cannot start until someone names the schema responsible.","sql":"SELECT pg_size_pretty(pg_database_size(current_database())) AS database_size;\n\n-- breakdown per schema, largest first; indexes and TOAST are\n-- already inside each table's total, so only tables and matviews\nSELECT n.nspname AS schema_name,\n       pg_size_pretty(SUM(pg_total_relation_size(c.oid))) AS total_size\nFROM pg_class c\nJOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE c.relkind IN ('r', 'm')\n  AND n.nspname NOT IN ('pg_catalog', 'information_schema')\nGROUP BY n.nspname\nORDER BY SUM(pg_total_relation_size(c.oid)) DESC;","how_it_works":"pg_database_size adds up every file in the database's directory: tables, indexes, TOAST, free-space and visibility maps. WAL is shared by the whole cluster and is not included. The per-schema query sums pg_total_relation_size over tables and materialized views; that function already counts each table's indexes and TOAST, so listing indexes separately (relkind 'i') would count them twice. The schemas add up to less than the total because the system catalogs are filtered out.","variants":[{"sql":"-- size is in 8 KB pages; FILEPROPERTY gives the used part\nSELECT name AS file_name, type_desc,\n       size * 8 / 1024 AS size_mb,\n       FILEPROPERTY(name, 'SpaceUsed') * 8 / 1024 AS used_mb\nFROM sys.database_files\nORDER BY size DESC;"},{"sql":"SELECT table_schema,\n       ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) AS size_mb\nFROM information_schema.tables\nWHERE table_schema NOT IN ('mysql', 'information_schema',\n                           'performance_schema', 'sys')\nGROUP BY table_schema\nORDER BY size_mb DESC;"},{"sql":"-- the database is one file; the size IS the file size\nPRAGMA page_count;\nPRAGMA page_size;   -- bytes = page_count * page_size"}],"see_also":["list-all-tables-sizes","table-bloat-estimate","list-schemas"],"faqs":[{"question":"Why is the sum of my tables much smaller than the database?","answer":"Look at what the per-table query counts. pg_relation_size and MySQL's data_length alone leave out indexes and TOAST, so use pg_total_relation_size or data_length + index_length. System catalogs are filtered out of most per-table lists. On SQL Server the transaction log is a separate LOG file in sys.database_files and often the largest one; tempdb is a separate database altogether."},{"question":"Why does the MySQL total sit well below the on-disk size?","answer":"Per-table data_length + index_length omits the shared InnoDB system tablespace (ibdata1), the undo and redo logs, and the binlogs. Add data_free to see internal fragmentation, and read SHOW BINARY LOGS for the log volume, before you reconcile against du."}]},"source_url":"https://sqlly.app/sql-snippets/database-size-summary","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/date-gap-detection","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Detect missing days in date data","description":"Generate every day between the first and last date and report the days with no rows: the gaps in time-series data.","body":{"slug":"date-gap-detection","name":"Missing days","h1":"Detect missing days in date data","category":"data-quality","lede":"Walk the calendar between the earliest and latest dates and keep the days that have no matching row, so broken feeds show up as holes.","engine_slug":"postgresql","problem":"daily_revenue (or any table with one row per day) should be continuous, but the chart has holes. This finds exactly which days are missing.","sql":"SELECT d::date AS missing_day\nFROM generate_series(\n  (SELECT MIN(order_date) FROM orders),\n  (SELECT MAX(order_date) FROM orders),\n  INTERVAL '1 day'\n) AS d\nWHERE NOT EXISTS (\n  SELECT 1 FROM orders o WHERE o.order_date = d::date\n)\nORDER BY missing_day;","how_it_works":"generate_series produces one timestamp per day across the table's date range; casting back to date aligns it with the stored values. NOT EXISTS keeps only days with no order row. If several rows share a day, the anti-join still behaves: it only checks existence, not counts. Engines without generate_series build the calendar with a recursive CTE instead; on SQLite that is the MySQL variant with date(day, '+1 day') as the step.","variants":[{"sql":"WITH RECURSIVE days(day) AS (\n  SELECT MIN(order_date) FROM orders\n  UNION ALL\n  SELECT day + INTERVAL 1 DAY FROM days\n  WHERE day < (SELECT MAX(order_date) FROM orders)\n)\nSELECT d.day AS missing_day\nFROM days d\nWHERE NOT EXISTS (\n  SELECT 1 FROM orders o WHERE o.order_date = d.day\n)\nORDER BY d.day;"},{"sql":"WITH bounds AS (\n  SELECT MIN(order_date) AS first_day, MAX(order_date) AS last_day\n  FROM orders\n),\ndays(day) AS (\n  SELECT first_day FROM bounds\n  UNION ALL\n  SELECT DATEADD(DAY, 1, d.day)\n  FROM days d, bounds b\n  WHERE d.day < b.last_day\n)\nSELECT d.day AS missing_day\nFROM days d\nWHERE NOT EXISTS (\n  SELECT 1 FROM orders o WHERE o.order_date = d.day\n)\nORDER BY d.day\nOPTION (MAXRECURSION 0);"},{"sql":"WITH RECURSIVE days(day) AS (\n  SELECT (SELECT MIN(order_date) FROM orders)\n  UNION ALL\n  SELECT day + 1 FROM days\n  WHERE day < (SELECT MAX(order_date) FROM orders)\n),\nmissing AS (\n  SELECT d.day\n  FROM days d\n  WHERE NOT EXISTS (\n    SELECT 1 FROM orders o WHERE o.order_date = d.day\n  )\n)\nSELECT date_trunc('month', day)::date AS month_start,\n       COUNT(*) AS missing_days\nFROM missing\nGROUP BY 1\nORDER BY 1;"}],"see_also":["missing-sequence-values","sequence-gap-detection"],"faqs":[{"question":"Why is a missing day suspicious but a missing id not?","answer":"Ids can legitimately skip values when transactions roll back, but a calendar gap means no rows exist for a whole day: a load failure, an outage, or a silent filter change. In one-row-per-day tables the sequence is a contract, so every hole is a data-quality defect worth explaining."}]},"source_url":"https://sqlly.app/sql-snippets/date-gap-detection","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/days-in-month","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Get the number of days in a month in SQL","description":"Return 28, 29, 30 or 31 for any date's month, leap years handled by the engine.","body":{"slug":"days-in-month","name":"Days in the month of a date","h1":"Get the number of days in a month in SQL","category":"text","lede":"Prorated billing and daily-rate math need the real length of each month, including leap-year February.","engine_slug":"sql-server","problem":"EOMONTH returns the month's last date; DAY of that is the length.","sql":"SELECT DAY(EOMONTH(d)) AS days_in_month\nFROM (SELECT CAST('2026-02-01' AS DATE) AS d) x;","how_it_works":"EOMONTH(d) lands on the final calendar day of d's month, so DAY() of it is the month's length. This sidesteps hand-rolled leap-year CASE logic entirely: the engine owns the calendar.","variants":[{"sql":"SELECT DAY(LAST_DAY(d)) AS days_in_month\nFROM (SELECT CURDATE() AS d) x;"},{"sql":"SELECT EXTRACT(DAY FROM (date_trunc('month', d) + interval '1 month - 1 day'))::int AS days_in_month\nFROM (SELECT DATE '2026-02-01' AS d) x;"},{"sql":"SELECT EXTRACT(DAY FROM LAST_DAY(d)) AS days_in_month\nFROM (SELECT DATE '2026-02-01' AS d FROM dual);"}],"see_also":["first-and-last-day-of-month","business-days-between"],"faqs":[{"question":"Can I get days remaining in the month?","answer":"Yes: subtract today from the month end. On SQL Server, DATEDIFF(DAY, GETDATE(), EOMONTH(GETDATE())); on PostgreSQL, (date_trunc('month', CURRENT_DATE) + interval '1 month - 1 day' - CURRENT_DATE)."},{"question":"Is there a SQLite spelling?","answer":"SQLite has no LAST_DAY function, so build the month end with date(d, 'start of month', '+1 month', '-1 day') and take CAST(strftime('%d', that) AS INTEGER) for the number. The other engines here all ship a direct function."}]},"source_url":"https://sqlly.app/sql-snippets/days-in-month","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/deadlock-history","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Find recent deadlocks in SQL Server","description":"Reads deadlock reports from the system_health Extended Events files, with the victim's session id and last statement, no tracing setup required.","body":{"slug":"deadlock-history","name":"Deadlock history","h1":"Find recent deadlocks in SQL Server","category":"monitoring","lede":"SQL Server records every deadlock into system_health automatically. Here is how to read them back out.","engine_slug":"sql-server","problem":"SQL Server runs an Extended Events session called system_health by default, and it records an xml_deadlock_report for every deadlock, so you can investigate one after the fact without having set up a trace. Each report lists the processes involved with their session ids and input buffers, the locked resources, and which process was chosen as the victim and rolled back.","sql":"WITH f AS (\n    SELECT CAST(event_data AS XML) AS x\n    FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL)\n    WHERE object_name = 'xml_deadlock_report'\n)\nSELECT f.x.value('(event/@timestamp)[1]', 'DATETIME2') AS deadlock_time_utc,\n       dl.d.value('count(process-list/process)', 'INT') AS processes,\n       dl.d.value('(process-list/process[@id = ../../victim-list/victimProcess[1]/@id]/@spid)[1]', 'INT') AS victim_spid,\n       dl.d.value('(process-list/process[@id = ../../victim-list/victimProcess[1]/@id]/inputbuf)[1]', 'NVARCHAR(2000)') AS victim_input,\n       dl.d.value('(resource-list/*/@objectname)[1]', 'NVARCHAR(256)') AS first_locked_object\nFROM f\nCROSS APPLY f.x.nodes('event/data[@name=\"xml_report\"]/value/deadlock') AS dl(d)\nORDER BY deadlock_time_utc DESC;","how_it_works":"system_health writes to two targets: a ring buffer in memory and rolling system_health*.xel files in the instance's log directory. The query reads the files with sys.fn_xe_file_target_read_file, which resolves the relative name against that directory, keeps history across restarts and returns one row per event, so the WHERE on object_name skips everything that is not a deadlock. The ring buffer is the less reliable source: it is emptied on restart and holds a limited number of recent events of every kind, so a burst of other events pushes deadlocks out. On the instance used to test this page it held 770 copies of one memory warning and not the deadlock raised seconds earlier, which the files had. nodes() steps into each report's deadlock element. The victim is found by matching each process's id attribute against victim-list/victimProcess, and inputbuf is the last batch that process sent, which is often the statement that deadlocked. The timestamp is in UTC. To see both sides, run the variant and open the report XML; SQL Server Management Studio draws it as a graph if you save it with an .xdl extension. Reading these views needs VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE on SQL Server 2022 and later).","variants":[{"sql":"SELECT x.value('(event/@timestamp)[1]', 'DATETIME2') AS deadlock_time_utc,\n       x.query('event/data[@name=\"xml_report\"]/value/deadlock') AS report\nFROM (\n    SELECT CAST(event_data AS XML) AS x\n    FROM sys.fn_xe_file_target_read_file('system_health*.xel', NULL, NULL, NULL)\n    WHERE object_name = 'xml_deadlock_report'\n) f\nORDER BY deadlock_time_utc DESC;"},{"sql":"SELECT datname, deadlocks\nFROM pg_stat_database\nWHERE deadlocks > 0\nORDER BY deadlocks DESC;"}],"see_also":["lock-waits-summary","blocking-queries","who-blocks-whom"],"faqs":[{"question":"Where does PostgreSQL record deadlocks?","answer":"In the server log. The victim's session logs ERROR: deadlock detected, with a DETAIL section naming each process, the lock it waited for and its statement. pg_stat_database.deadlocks counts them per database, so a rise in that counter tells you when to look in the log. log_lock_waits = on is a separate setting: it logs any lock wait longer than deadlock_timeout (1 second by default), which catches the near misses too."},{"question":"How do I prevent a recurring deadlock?","answer":"Read the statements from the report and make every code path touch the same rows and tables in the same order, for example by sorting batch updates by key or by locking the parent row first (UPDLOCK in SQL Server, SELECT ... FOR UPDATE in PostgreSQL). A missing index is another common cause, because a scan locks many more rows than the statement changes. Shorter transactions make deadlocks rarer but do not fix an ordering conflict."}]},"source_url":"https://sqlly.app/sql-snippets/deadlock-history","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/dedupe-with-window-functions","corpus":"sql-snippets","engine":"all","language":"en","title":"Dedupe with window functions","description":"Rank rows per key with ROW_NUMBER and keep rn = 1, the standard window-function dedupe pattern.","body":{"slug":"dedupe-with-window-functions","name":"Dedupe with windows","h1":"Dedupe with window functions","category":"data-quality","lede":"ROW_NUMBER over a partition of the duplicate key numbers the copies; the outer query keeps rank 1 and shows the rest.","engine_slug":"all","problem":"The general-purpose dedupe: number the copies within each key, decide the keep rule in the ORDER BY, and filter. It previews as easily as it deletes.","sql":"WITH ranked AS (\n  SELECT id, email, name, created_at,\n         ROW_NUMBER() OVER (\n           PARTITION BY email\n           ORDER BY created_at ASC, id ASC\n         ) AS rn\n  FROM customers\n  WHERE email IS NOT NULL\n)\nSELECT id, email, name, created_at, rn\nFROM ranked\nWHERE rn > 1\nORDER BY email, rn;","how_it_works":"PARTITION BY email starts the numbering fresh for each address; ORDER BY created_at, id decides which copy ranks first; change that ORDER BY and you change the keep rule, nothing else. rn > 1 lists every losing copy; switch to rn = 1 to preview the survivors. Rows with no email are filtered out first, or they would all share one partition and be treated as copies of each other. The DELETE variant reuses the same ranking inside a derived table, the form Oracle and MySQL accept. delete-duplicates-keep-one packages this same ranking as a preview-plus-delete runbook with the transaction handling spelled out.","variants":[{"sql":"DELETE FROM customers\nWHERE id IN (\n  SELECT id\n  FROM (\n    SELECT id,\n           ROW_NUMBER() OVER (\n             PARTITION BY email\n             ORDER BY created_at ASC, id ASC\n           ) AS rn\n    FROM customers\n    WHERE email IS NOT NULL\n  ) ranked\n  WHERE rn > 1\n);"},{"sql":"WITH ranked AS (\n  SELECT id, customer_id, total,\n         DENSE_RANK() OVER (\n           PARTITION BY customer_id\n           ORDER BY total DESC\n         ) AS rnk\n  FROM orders\n)\nSELECT id, customer_id, total\nFROM ranked\nWHERE rnk = 1;"}],"see_also":["delete-duplicates-keep-one","keep-newest-per-key","keep-oldest-per-key"],"faqs":[{"question":"ROW_NUMBER, RANK or DENSE_RANK for dedupe?","answer":"ROW_NUMBER gives every copy a distinct number, so exactly one row survives per partition, which is what dedupe usually wants. RANK and DENSE_RANK give tied rows the same rank, so a tie can keep several rows and delete none. Use ROW_NUMBER with a tiebreaker (id) in the ORDER BY to make the survivor deterministic."},{"question":"Why does the DELETE variant wrap ROW_NUMBER in one more derived table?","answer":"MySQL refuses a DELETE whose subquery reads the table being deleted unless the ranking is materialized first (error 1093), and Oracle does not accept WITH in front of DELETE. The extra nesting level satisfies both engines and is harmless on the rest."}]},"source_url":"https://sqlly.app/sql-snippets/dedupe-with-window-functions","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/deduplicate-query-output","corpus":"sql-snippets","engine":"all","language":"en","title":"Deduplicate SELECT output","description":"Collapse repeated rows with DISTINCT, or keep one whole row per business key with ROW_NUMBER.","body":{"slug":"deduplicate-query-output","name":"Deduplicate SELECT output","h1":"Deduplicate SELECT output","category":"querying","lede":"DISTINCT for value sets, ROW_NUMBER for full-row dedupe with a survivor policy.","engine_slug":"all","problem":"Your joined query repeats the same customer/status combination many times, and you want each combination once.","sql":"SELECT DISTINCT customer_id, status\nFROM orders\nORDER BY customer_id, status;","how_it_works":"DISTINCT compares the whole selected row list and removes exact duplicates after the fact. It cannot pick which of two different rows survives, because it only sees the selected columns. When a row can differ in the unselected columns and you want one deterministic survivor per key, dedupe with ROW_NUMBER instead. latest-row-per-customer and earliest-row-per-key run the same rank against newest and oldest per parent.","variants":[{"sql":"WITH ranked AS (\n  SELECT o.*,\n         ROW_NUMBER() OVER (PARTITION BY customer_id, order_date\n                            ORDER BY id) AS rn\n  FROM orders o\n)\nSELECT id, customer_id, order_date, amount, status\nFROM ranked\nWHERE rn = 1;"}],"see_also":["intersect-common-rows","latest-row-per-customer","earliest-row-per-key"],"faqs":[{"question":"Why does DISTINCT not remove rows that differ only in a column I left out?","answer":"Because deduplication happens on the projected column list only. Either add the column to the select list, or use the ROW_NUMBER variant to define exactly which row survives per key."},{"question":"Why not just SELECT DISTINCT?","answer":"DISTINCT collapses only byte-equal rows, so two orders sharing a key but differing in a timestamp both survive. The ROW_NUMBER rank defines duplicate as same-key and keeps one deterministic survivor, which is what dedupe usually means."}]},"source_url":"https://sqlly.app/sql-snippets/deduplicate-query-output","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/default-privileges-future-tables","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Default privileges for future tables","description":"Make grants apply to tables that do not exist yet with ALTER DEFAULT PRIVILEGES, which is keyed to the role that creates the tables.","body":{"slug":"default-privileges-future-tables","name":"Default privileges for future tables","h1":"Default privileges for future tables","category":"schema","lede":"GRANT ... ON ALL TABLES covers the tables that exist when it runs. Default privileges make tables created later accessible too; without them, every migration that adds a table locks the reporting role out of it.","engine_slug":"postgresql","problem":"The reader role loses access to every new table the migration user creates, and re-granting by hand each time is the current workaround.","sql":"ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public\n  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_reader;\n-- tables app_owner creates in public from now on get these\n-- grants for app_reader automatically","how_it_works":"Default privileges are keyed to the role that creates the objects. Without FOR ROLE they apply only to tables created by the role running the ALTER, so if a migration user creates the tables, name that role. Existing tables are untouched; run GRANT ... ON ALL TABLES IN SCHEMA alongside so current and future tables are both covered.","variants":[{"sql":"-- defaclobjtype: r = tables, S = sequences, f = functions,\n-- T = types, n = schemas; psql shows the same with \\ddp\nSELECT defaclrole::regrole AS creating_role,\n       defaclnamespace::regnamespace AS schema_name,\n       defaclobjtype, defaclacl\nFROM pg_default_acl;"},{"sql":"-- MySQL has no default-privilege mechanism; grant at the\n-- database level instead, which covers future tables:\nGRANT SELECT ON mydb.* TO 'analyst'@'%';"},{"sql":"-- no default privileges either; a schema-level grant already\n-- covers objects created in the schema later:\nGRANT SELECT ON SCHEMA::dbo TO app_reader;"}],"see_also":["grant-select-all-tables","list-user-privileges","revoke-all-privileges"],"faqs":[{"question":"Why do my default privileges do nothing?","answer":"Almost always the FOR ROLE clause: defaults apply to objects created by the named role, and your migrations may run as a different user. Query pg_default_acl to see which creating roles have defaults configured, and add one for whichever role actually runs your DDL."},{"question":"Why do MySQL and SQL Server not need this recipe?","answer":"A MySQL grant on mydb.* and a SQL Server grant on SCHEMA::dbo both reach tables created later automatically, because they attach to the database or schema rather than to a list of objects. PostgreSQL scopes table grants to what exists and needs ALTER DEFAULT PRIVILEGES for the future; that is a design choice, not a version gate."}]},"source_url":"https://sqlly.app/sql-snippets/default-privileges-future-tables","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/delete-duplicates-keep-one","corpus":"sql-snippets","engine":"all","language":"en","title":"Delete duplicates keeping one row","description":"Remove duplicate rows with DELETE plus ROW_NUMBER, keeping one row per key. Always SELECT the doomed rows first.","body":{"slug":"delete-duplicates-keep-one","name":"Delete duplicates","h1":"Delete duplicates keeping one row","category":"data-quality","lede":"Rank rows per duplicate key with ROW_NUMBER, preview the losers, then delete everything ranked after first. Run the DELETE inside a transaction so you can roll it back.","engine_slug":"all","problem":"customers contains repeated email addresses and you want to keep one row per email (the earliest by id) and remove the rest without touching the survivors.","sql":"-- Step 1: preview exactly which rows will be deleted\nSELECT id, email, rn\nFROM (\n  SELECT id, email,\n         ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn\n  FROM customers\n  WHERE email IS NOT NULL\n) ranked\nWHERE rn > 1;\n\n-- Step 2: open a transaction first (see below), then delete\nDELETE FROM customers\nWHERE id IN (\n  SELECT id\n  FROM (\n    SELECT id,\n           ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn\n    FROM customers\n    WHERE email IS NOT NULL\n  ) ranked\n  WHERE rn > 1\n);\n-- check the row count, then COMMIT or ROLLBACK","how_it_works":"ROW_NUMBER numbers rows within each email group, ordered by id, so rn = 1 is the keeper and every rn > 1 row is a redundant copy. The WHERE email IS NOT NULL matters: without it every customer with no email lands in one partition and all but one of them get deleted. The ranking sits in a derived table rather than a CTE because Oracle does not accept WITH in front of DELETE, and MySQL refuses a subquery that reads the DELETE's own table unless it is materialized like this (error 1093). The statement itself is portable; the transaction syntax is not: BEGIN on PostgreSQL and SQLite, START TRANSACTION on MySQL, BEGIN TRANSACTION on SQL Server, and nothing on Oracle, which opens a transaction implicitly. Also check what your collation calls equal: under MySQL's utf8mb4_0900_ai_ci or SQL Server's default CI collation, Ada@X.io and ada@x.io count as one email. The dedupe-with-window-functions recipe teaches this ranking from the SELECT side first, which suits teams that want a reviewed preview before any DELETE.","variants":[{"sql":"DELETE FROM customers\nWHERE id IN (\n  SELECT id\n  FROM (\n    SELECT id,\n           ROW_NUMBER() OVER (\n             PARTITION BY email\n             ORDER BY updated_at DESC, id DESC\n           ) AS rn\n    FROM customers\n    WHERE email IS NOT NULL\n  ) ranked\n  WHERE rn > 1\n);"},{"sql":"DELETE FROM customers\nWHERE email IS NOT NULL\n  AND id NOT IN (\n    SELECT keep_id\n    FROM (\n      SELECT MIN(id) AS keep_id\n      FROM customers\n      WHERE email IS NOT NULL\n      GROUP BY email\n    ) keepers\n  );"}],"see_also":["dedupe-with-window-functions","keep-newest-per-key","keep-oldest-per-key"],"faqs":[{"question":"Why the transaction if the preview already matched?","answer":"Other sessions can insert or change rows between your preview and the DELETE, and a transaction does not stop that. What it gives you is an undo: after the DELETE, re-run the preview (it should return nothing) and compare the deleted-row count with what the preview showed. If either looks wrong, ROLLBACK restores the table; COMMIT only when both match."},{"question":"Does the delete need an index on the key?","answer":"It runs without one, but each engine then scans and sorts the whole table to build the partitions; an index on (email, id) lets PostgreSQL, MySQL and SQL Server stream each group in order. For millions of doomed rows, delete in id batches so locks and the log stay small."}]},"source_url":"https://sqlly.app/sql-snippets/delete-duplicates-keep-one","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/describe-table-columns","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Describe a table: columns, types and defaults","description":"The equivalent of psql's \\d or MySQL's DESCRIBE, written as a query: column names, data types, nullability and defaults for one table.","body":{"slug":"describe-table-columns","name":"Describe a table","h1":"Describe a table: columns, types and defaults","category":"schema","lede":"Every engine has a DESCRIBE-style shortcut, but a plain query is scriptable and gives you the same information in a form you can filter or diff.","engine_slug":"postgresql","problem":"You are about to write against a table whose exact column names and types you do not have memorized, or you need to compare one table's shape between two environments.","sql":"SELECT column_name, data_type, is_nullable, column_default,\n       character_maximum_length, numeric_precision, numeric_scale\nFROM information_schema.columns\nWHERE table_schema = 'public' AND table_name = 'users'\nORDER BY ordinal_position;","how_it_works":"information_schema.columns is the SQL-standard metadata view, so this query shape works on PostgreSQL, MySQL and SQL Server with almost no changes. ordinal_position preserves the column order you declared. character_maximum_length and the numeric precision columns are NULL for types where they do not apply.","variants":[{"sql":"DESCRIBE users;\n-- or with more detail:\nSHOW FULL COLUMNS FROM users;"},{"sql":"EXEC sp_help 'dbo.Users';\n-- or just the columns:\nSELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Users'\nORDER BY ORDINAL_POSITION;"},{"sql":"PRAGMA table_info(users);\n-- with generated/hidden columns included:\nPRAGMA table_xinfo(users);"}],"see_also":["list-table-columns","find-tables-with-column","find-columns-by-type"],"faqs":[{"question":"How do I get the full type with length, like varchar(50)?","answer":"Combine data_type with character_maximum_length when it is not NULL, or numeric_precision and numeric_scale for numeric. PostgreSQL can print the declared form directly with format_type(atttypid, atttypmod) from pg_attribute, MySQL has it ready in information_schema.columns.column_type, and SQLite's PRAGMA table_info returns the type exactly as written in CREATE TABLE."}]},"source_url":"https://sqlly.app/sql-snippets/describe-table-columns","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/distinct-counts-per-group","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Distinct counts per group","description":"COUNT(DISTINCT ...) inside a GROUP BY answers how many different values each group has.","body":{"slug":"distinct-counts-per-group","name":"Distinct counts per group","h1":"Distinct counts per group","category":"querying","lede":"One query, several distinct counters per group: active days, statuses, products.","engine_slug":"postgresql","problem":"You want, per customer, on how many different days they ordered and how many distinct statuses their orders passed through.","sql":"SELECT customer_id,\n       COUNT(DISTINCT CAST(order_date AS date)) AS active_days,\n       COUNT(DISTINCT status) AS statuses_used,\n       COUNT(*) AS total_orders\nFROM orders\nGROUP BY customer_id\nORDER BY active_days DESC;","how_it_works":"COUNT(DISTINCT expr) deduplicates the expression inside each group before counting, and you can use it several times in one SELECT. Casting the timestamp to a date collapses same-day orders into one day; that cast works on PostgreSQL, MySQL and SQL Server. On Oracle CAST(... AS DATE) keeps the time, so use TRUNC(order_date), and on SQLite CAST(... AS date) turns '2026-06-01 12:00:00' into the number 2026, so use date(order_date). PostgreSQL, MySQL, SQL Server and SQLite reject COUNT(DISTINCT) inside OVER (Oracle allows it without an ORDER BY), so pre-aggregate in a subquery when you need a running distinct count.","variants":[{"sql":"WITH per_day AS (\n  SELECT customer_id, CAST(order_date AS date) AS day,\n         SUM(amount) AS day_total\n  FROM orders\n  GROUP BY customer_id, CAST(order_date AS date)\n)\nSELECT customer_id, day, day_total,\n       COUNT(*) OVER (PARTITION BY customer_id\n                      ORDER BY day\n                      ROWS BETWEEN UNBOUNDED PRECEDING\n                            AND CURRENT ROW) AS active_days_so_far\nFROM per_day;"}],"see_also":["count-if-recipe","aggregate-children-per-parent"],"faqs":[{"question":"Distinct counts are slow on huge tables. Any alternative?","answer":"Yes, approximate counts. SQL Server 2019+ and Oracle 12c+ have APPROX_COUNT_DISTINCT, built on HyperLogLog with an error of a few percent, and PostgreSQL gets the same from the hll extension. MySQL and SQLite have no built-in equivalent."},{"question":"Do NULLs join the distinct count?","answer":"No: COUNT(DISTINCT expr) skips NULLs on every engine, so a sparse column reports fewer distinct values than there are groups. Count DISTINCT COALESCE(expr, 'missing') when absence should count as a value of its own."}]},"source_url":"https://sqlly.app/sql-snippets/distinct-counts-per-group","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/dominant-value-frequency","corpus":"sql-snippets","engine":"all","language":"en","title":"Dominant-value frequency table","description":"Count each value, compute its share of the table with a window sum, and rank the most common values.","body":{"slug":"dominant-value-frequency","name":"Dominant values","h1":"Dominant-value frequency table","category":"data-quality","lede":"One GROUP BY produces the frequency table; a windowed sum over the group counts turns the counts into percentages.","engine_slug":"all","problem":"orders.status should be five known values, but is it? A frequency table shows every value that exists, how often it appears, and what share of the table each one owns.","sql":"SELECT status,\n       COUNT(*) AS order_count,\n       ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct_of_table\nFROM orders\nGROUP BY status\nORDER BY order_count DESC;","how_it_works":"GROUP BY status counts rows per value; SUM(COUNT(*)) OVER () sums those group counts across all groups (the table total) inside the same query. Multiplying by 100.0 first forces decimal division, so the percentage keeps its fraction. The result is a ranked, percent-share profile of the column.","variants":[{"sql":"SELECT status, COUNT(*) AS order_count\nFROM orders\nGROUP BY status\nORDER BY order_count DESC\nLIMIT 1;"},{"sql":"SELECT status,\n       COUNT(*) AS order_count,\n       ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM orders), 1) AS pct_of_table\nFROM orders\nGROUP BY status\nORDER BY order_count DESC;"}],"see_also":["value-distribution-histogram","foreign-key-value-distribution","null-counts-per-column"],"faqs":[{"question":"Why 100.0 and not 100?","answer":"PostgreSQL, SQL Server and SQLite divide integers as integers: 100 * 2 / 14 is 14, not 14.3, and a category with 1 row out of 300 shows 0. The decimal literal 100.0 turns the whole expression into decimal arithmetic before the division. MySQL and Oracle always return a fraction from /, so there it changes nothing, and it keeps the query portable."},{"question":"Can NULL end up as the dominant value?","answer":"Yes: GROUP BY puts all NULLs in one group on every engine, so a column that is mostly empty shows NULL at the top of the frequency table. Filter WHERE status IS NOT NULL first, or leave the bucket in and treat it as its own category."}]},"source_url":"https://sqlly.app/sql-snippets/dominant-value-frequency","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/dst-safe-date-arithmetic","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Do DST-safe day arithmetic on timestamps in SQL","description":"Add days to a zoned timestamp without the local time drifting an hour across a DST boundary.","body":{"slug":"dst-safe-date-arithmetic","name":"DST-safe date arithmetic","h1":"Do DST-safe day arithmetic on timestamps in SQL","category":"text","lede":"Adding 24 hours to a zoned timestamp lands an hour off after a DST switch. Calendar-day addition must happen in local time.","engine_slug":"postgresql","problem":"Convert the instant to local wall time, do the day addition there, and convert back. The local clock time survives the DST switch.","sql":"SELECT\n    (starts_at AT TIME ZONE 'America/New_York' + interval '1 day')\n        AT TIME ZONE 'America/New_York' AS next_day_same_local_time\nFROM sessions;","how_it_works":"PostgreSQL adds interval '1 day' to a timestamptz as a calendar day in the session's TimeZone. Servers usually run sessions in UTC, where that is exactly 24 hours, so a New York session starting at 10:00 on 2026-03-07 lands at 11:00 local the next day, after the spring-forward switch. Converting to New York wall time, adding the day there and converting back keeps 10:00. SQL Server needs the same round trip with datetimeoffset, shown in the variant.","variants":[{"sql":"SELECT\n    CAST(DATEADD(DAY, 1, CAST(starts_at AT TIME ZONE 'Eastern Standard Time' AS datetime2)) AS datetime2)\n        AT TIME ZONE 'Eastern Standard Time' AS next_day_same_local_time\nFROM sessions;"}],"see_also":["convert-local-to-utc","normalize-stored-utc"],"faqs":[{"question":"Is SQL Server's DATEADD DST-safe on datetimeoffset?","answer":"No. DATEADD(DAY, 1, ...) on a datetimeoffset adds a day and keeps the original offset, so 2026-03-07 10:00 -05:00 becomes 2026-03-08 10:00 -05:00, which is 11:00 in New York after the switch. The variant drops to a wall-clock datetime2, adds the day, and lets AT TIME ZONE pick the offset that applies on the new date (-04:00)."}]},"source_url":"https://sqlly.app/sql-snippets/dst-safe-date-arithmetic","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/duplicate-index-candidates","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find duplicate index candidates","description":"Pairs of indexes on one table that cover the same columns in the same order. One of each pair is dead weight; this query finds both.","body":{"slug":"duplicate-index-candidates","name":"Duplicate indexes","h1":"Find duplicate index candidates","category":"schema","lede":"ORM migrations and copy-paste DDL pile up redundant indexes over the years: same table, same columns, same order, different names. Only one of each pair earns its write overhead.","engine_slug":"postgresql","problem":"A table's write overhead keeps creeping up with each new index, and some of them may cover identical column lists under different names. Find the exact pairs.","sql":"SELECT t.relname AS table_name,\n       a.relname AS index_a,\n       b.relname AS index_b,\n       pg_get_indexdef(b.oid) AS definition\nFROM pg_index x1\nJOIN pg_class a ON a.oid = x1.indexrelid\nJOIN pg_index x2 ON x2.indrelid = x1.indrelid\n   AND x2.indexrelid > x1.indexrelid\n   AND x2.indkey::text = x1.indkey::text\n   AND x2.indisunique = x1.indisunique\n   AND COALESCE(pg_get_expr(x2.indexprs, x2.indrelid), '')\n     = COALESCE(pg_get_expr(x1.indexprs, x1.indrelid), '')\n   AND COALESCE(pg_get_expr(x2.indpred, x2.indrelid), '')\n     = COALESCE(pg_get_expr(x1.indpred, x1.indrelid), '')\nJOIN pg_class b ON b.oid = x2.indexrelid\nJOIN pg_class t ON t.oid = x1.indrelid\nORDER BY t.relname, a.relname;","how_it_works":"Every pg_index row stores the covered column numbers in indkey; casting it to text turns it into a string such as '1 3', so two indexes match when they cover the same columns in the same order. Expression columns appear as 0 in indkey, which is why the expression and partial-index predicate are compared too; without them, indexes on lower(email) and upper(email) would pair up. The indexrelid > condition keeps each pair once. Two matches can still differ in index method or operator class, so read both definitions before dropping one.","variants":[{"sql":"-- the sys schema already does this, including indexes that\n-- are a left prefix of a wider one, and writes the DROP for you\nSELECT table_name, redundant_index_name, redundant_index_columns,\n       dominant_index_name, dominant_index_columns, sql_drop_index\nFROM sys.schema_redundant_indexes\nWHERE table_schema = 'mydb';"},{"sql":"-- strip the CREATE INDEX name so identical definitions\n-- sort next to each other\nSELECT name, tbl_name, substr(sql, instr(sql, ' ON ')) AS definition\nFROM sqlite_master\nWHERE type = 'index' AND sql IS NOT NULL\nORDER BY tbl_name, definition, name;"}],"see_also":["unused-index-candidates","list-table-indexes-columns","list-all-tables-sizes"],"faqs":[{"question":"What about a 2-column index duplicating a 1-column index?","answer":"An index on (a, b) can serve queries that filter on a alone, so a separate index on (a) is usually redundant even though the column lists differ. The PostgreSQL query catches exact matches only, so check those prefix cases by hand. Keep the short index if it is unique, because it enforces a rule the wider one does not."}]},"source_url":"https://sqlly.app/sql-snippets/duplicate-index-candidates","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/duplicate-indexes","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find duplicate indexes in PostgreSQL","description":"Finds pairs of indexes on the same table with identical columns, operator classes, expressions and predicates, so you can drop one and stop paying twice on writes.","body":{"slug":"duplicate-indexes","name":"Duplicate indexes","h1":"Find duplicate indexes in PostgreSQL","category":"indexes","lede":"Two identical indexes do the same maintenance work twice on every write. This query finds the pairs nobody meant to create.","engine_slug":"postgresql","problem":"Duplicate indexes usually arrive by accident: an ORM migration adds an index someone already created by hand, or a UNIQUE constraint and a plain index end up on the same column. Every write maintains both, and the planner only ever needs one of them. The catch is that two indexes on the same column are not always duplicates: a partial index (WHERE status = 'paid'), an expression index (lower(email)) or a different operator class covers different queries.","sql":"SELECT n.nspname AS schema_name, t.relname AS table_name,\n       a.relname AS index_a, b.relname AS index_b,\n       x.indisunique AS a_unique, y.indisunique AS b_unique,\n       pg_get_indexdef(a.oid) AS definition_a,\n       pg_get_indexdef(b.oid) AS definition_b,\n       pg_size_pretty(pg_relation_size(a.oid) + pg_relation_size(b.oid)) AS combined_size\nFROM pg_index x\nJOIN pg_index y ON y.indrelid = x.indrelid\n   AND y.indexrelid > x.indexrelid\n   AND y.indnkeyatts = x.indnkeyatts\n   AND y.indkey::text = x.indkey::text\n   AND y.indclass::text = x.indclass::text\n   AND y.indcollation::text = x.indcollation::text\n   AND y.indoption::text = x.indoption::text\n   AND pg_get_expr(y.indexprs, y.indrelid) IS NOT DISTINCT FROM pg_get_expr(x.indexprs, x.indrelid)\n   AND pg_get_expr(y.indpred, y.indrelid) IS NOT DISTINCT FROM pg_get_expr(x.indpred, x.indrelid)\nJOIN pg_class a ON a.oid = x.indexrelid\nJOIN pg_class b ON b.oid = y.indexrelid\nJOIN pg_class t ON t.oid = x.indrelid\nJOIN pg_namespace n ON n.oid = t.relnamespace\nORDER BY pg_relation_size(a.oid) + pg_relation_size(b.oid) DESC;","how_it_works":"The query self-joins pg_index on the same table. indkey is the list of indexed column numbers (0 marks an expression), indnkeyatts separates key columns from INCLUDE columns, indclass and indcollation hold the operator class and collation per column, and indoption holds ASC/DESC and NULLS ordering. indkey and the others are vector types, so they are compared as text. Expressions and partial-index predicates are stored as node trees, so pg_get_expr decompiles them and IS NOT DISTINCT FROM treats two NULLs (no expression, no predicate) as equal. y.indexrelid > x.indexrelid lists each pair once. The unique flags are shown because a UNIQUE index and a plain index on the same column count as duplicates, but only the plain one should go. The sort is on the byte sum; sorting the pg_size_pretty text would put 9 MB above 10 GB.","variants":[{"sql":"WITH pairs AS (\n    SELECT x.indexrelid AS a, y.indexrelid AS b,\n           x.indisunique AS a_unique, y.indisunique AS b_unique,\n           EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = x.indexrelid) AS a_con,\n           EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = y.indexrelid) AS b_con\n    FROM pg_index x\n    JOIN pg_index y ON y.indrelid = x.indrelid\n       AND y.indexrelid > x.indexrelid\n       AND y.indnkeyatts = x.indnkeyatts\n       AND y.indkey::text = x.indkey::text\n       AND y.indclass::text = x.indclass::text\n       AND y.indcollation::text = x.indcollation::text\n       AND y.indoption::text = x.indoption::text\n       AND pg_get_expr(y.indexprs, y.indrelid) IS NOT DISTINCT FROM pg_get_expr(x.indexprs, x.indrelid)\n       AND pg_get_expr(y.indpred, y.indrelid) IS NOT DISTINCT FROM pg_get_expr(x.indpred, x.indrelid)\n), pick AS (\n    SELECT CASE WHEN b_con OR (b_unique AND NOT a_unique) THEN a ELSE b END AS drop_oid,\n           CASE WHEN b_con OR (b_unique AND NOT a_unique) THEN a_con ELSE b_con END AS drop_con,\n           CASE WHEN b_con OR (b_unique AND NOT a_unique) THEN a_unique AND NOT b_unique\n                ELSE b_unique AND NOT a_unique END AS drop_only_unique\n    FROM pairs\n)\nSELECT DISTINCT format('DROP INDEX CONCURRENTLY %s;', drop_oid::regclass) AS drop_statement\nFROM pick\nWHERE NOT drop_con AND NOT drop_only_unique;"}],"see_also":["unused-indexes","redundant-prefix-indexes","largest-indexes"],"faqs":[{"question":"Which index of a pair should I drop?","answer":"Keep the one that backs a PRIMARY KEY, UNIQUE or exclusion constraint, because dropping it would mean dropping the constraint (PostgreSQL refuses a plain DROP INDEX on it anyway). If one is UNIQUE and the other is not, keep the UNIQUE one: it serves the same lookups and also enforces the rule. The variant applies both rules and skips pairs where both indexes back constraints."},{"question":"Two indexes list the same column but one has a WHERE clause. Are they duplicates?","answer":"No. A partial index only contains the rows matching its predicate, and an expression index such as lower(email) answers different predicates than an index on email. That is why the query compares the decompiled expressions and predicates, not only the column numbers. A partial index whose predicate is a subset of a full index on the same column can still be worth reviewing, but that is a judgment call, not a duplicate."}]},"source_url":"https://sqlly.app/sql-snippets/duplicate-indexes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/duplicate-natural-keys-different-ids","corpus":"sql-snippets","engine":"all","language":"en","title":"Duplicate natural keys with different ids","description":"Composite natural keys duplicated across different surrogate ids: the merge-candidate list.","body":{"slug":"duplicate-natural-keys-different-ids","name":"Dup natural keys","h1":"Duplicate natural keys with different ids","category":"data-quality","lede":"Group by the natural key and count distinct surrogate ids: more than one id per natural key means the same real-world thing is stored twice.","engine_slug":"all","problem":"order_items should hold one line per (order_id, product_id), but re-runs of an importer created several rows, each with its own surrogate id, for the same line. Those id groups are your merge candidates.","sql":"SELECT order_id, product_id,\n       COUNT(*) AS line_copies,\n       COUNT(DISTINCT id) AS distinct_ids,\n       MIN(id) AS keep_id,\n       MAX(id) AS merge_id\nFROM order_items\nGROUP BY order_id, product_id\nHAVING COUNT(DISTINCT id) > 1\nORDER BY line_copies DESC;","how_it_works":"The natural key (order_id, product_id) is the GROUP BY; HAVING keeps keys stored under more than one surrogate id. MIN(id) is a sensible survivor and MAX(id) the newest copy; when line_copies is above 2 there are more ids in between, which the variant lists in full. If id is a real primary key, COUNT(*) and COUNT(DISTINCT id) are always equal; when they differ, the surrogate id itself is duplicated and you have a second problem to fix first.","variants":[{"sql":"WITH dupes AS (\n  SELECT order_id, product_id\n  FROM order_items\n  GROUP BY order_id, product_id\n  HAVING COUNT(*) > 1\n)\nSELECT oi.*\nFROM order_items oi\nJOIN dupes d\n  ON d.order_id = oi.order_id AND d.product_id = oi.product_id\nORDER BY oi.order_id, oi.product_id, oi.id;"}],"see_also":["find-duplicates-on-a-key","re-parent-children-merge-duplicates","find-candidate-keys"],"faqs":[{"question":"Natural key or surrogate id: which one defines a duplicate?","answer":"The natural key does: it identifies the real-world thing (this order line for this product), while surrogate ids merely distinguish stored copies. Duplicates on the natural key with different surrogate ids are the signature of a missing uniqueness enforcement. The data-quality fix is the merge now and the UNIQUE constraint after."},{"question":"Can NULLs hide from this check?","answer":"COUNT ignores NULLs on all five engines, and PostgreSQL, SQLite and Oracle treat NULLs as distinct in a unique index, so a NULL natural key can repeat without tripping anything. Declare the natural key NOT NULL, or the census and the constraint will disagree about what counts as a duplicate."}]},"source_url":"https://sqlly.app/sql-snippets/duplicate-natural-keys-different-ids","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/earliest-row-per-key","corpus":"sql-snippets","engine":"all","language":"en","title":"Earliest row per key","description":"Get each customer's first order with ROW_NUMBER over an ascending sort, or a NOT EXISTS anti-join.","body":{"slug":"earliest-row-per-key","name":"Earliest row per key","h1":"Earliest row per key","category":"querying","lede":"Same recipe as latest-row, sorted the other way, plus the anti-join alternative.","engine_slug":"all","problem":"You want each customer's first-ever order, full row, to study acquisition behaviour.","sql":"WITH ranked AS (\n  SELECT o.*,\n         ROW_NUMBER() OVER (PARTITION BY customer_id\n                            ORDER BY order_date, id) AS rn\n  FROM orders o\n)\nSELECT id, customer_id, order_date, amount, status\nFROM ranked\nWHERE rn = 1;","how_it_works":"Sorting the window ascending puts each customer's oldest order at number one. The id tiebreaker keeps the result stable when two orders landed on the same timestamp. The NOT EXISTS variant answers the same question without a window function: keep an order only if no earlier order (or same-time order with a lower id) exists for that customer. This is latest-row-per-customer with the sort reversed, and deduplicate-query-output applies the identical rank to keep one row per duplicate key.","variants":[{"sql":"SELECT o.*\nFROM orders o\nWHERE NOT EXISTS (\n  SELECT 1\n  FROM orders o2\n  WHERE o2.customer_id = o.customer_id\n    AND (o2.order_date < o.order_date\n         OR (o2.order_date = o.order_date AND o2.id < o.id))\n);"}],"see_also":["latest-row-per-customer","top-n-per-group","deduplicate-query-output"],"faqs":[{"question":"When is the anti-join version better?","answer":"It runs on engines without window functions, such as MySQL 5.7. With an index on (customer_id, order_date, id) each NOT EXISTS probe is a short index seek, so it can beat the window version when customers have many orders each; without that index it degrades to a nested scan, and the window version, which sorts once, wins."}]},"source_url":"https://sqlly.app/sql-snippets/earliest-row-per-key","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/ellipsize-long-text","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Ellipsize long text with a trailing ellipsis in SQL","description":"Shorten to a hard cap and append '...' only when the text was actually cut.","body":{"slug":"ellipsize-long-text","name":"Ellipsize long text","h1":"Ellipsize long text with a trailing ellipsis in SQL","category":"text","lede":"Fixed-width UI slots need a hard cap, and the dots tell readers the text continues.","engine_slug":"sql-server","problem":"Cap the preview at 120 characters and add three dots only when something was actually removed.","sql":"SELECT CASE WHEN LEN(blurb) > 120\n            THEN LEFT(blurb, 117) + '...'\n            ELSE blurb END AS preview\nFROM articles;","how_it_works":"The CASE checks the full length first. Long values keep 117 characters, and the three dots bring the display total back to exactly 120. LEN ignores trailing spaces on SQL Server, which is usually harmless for prose but matters if your strings can be all-spaces.","variants":[{"sql":"SELECT CASE WHEN length(blurb) > 120\n            THEN left(blurb, 117) || '...'\n            ELSE blurb END AS preview\nFROM articles;"},{"sql":"SELECT CASE WHEN CHAR_LENGTH(blurb) > 120\n            THEN CONCAT(LEFT(blurb, 117), '...')\n            ELSE blurb END AS preview\nFROM articles;"}],"see_also":["truncate-word-boundary"],"faqs":[{"question":"Can I combine this with word-boundary truncation?","answer":"Yes: replace LEFT(blurb, 117) with the word-boundary expression limited to 117 characters. That gives previews that never cut a word and never exceed the cap."}]},"source_url":"https://sqlly.app/sql-snippets/ellipsize-long-text","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/epoch-conversions-both-ways","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Convert between Unix epoch and timestamps in SQL","description":"Turn timestamps into epoch seconds and back, per engine, without letting a session time zone shift the result.","body":{"slug":"epoch-conversions-both-ways","name":"Epoch conversions, both ways","h1":"Convert between Unix epoch and timestamps in SQL","category":"text","lede":"APIs and queues speak Unix seconds; databases speak their own timestamp types. Both directions of the bridge are needed constantly.","engine_slug":"postgresql","problem":"extract(epoch) reads a timestamp as epoch seconds; to_timestamp builds one back from seconds.","sql":"SELECT\n    extract(epoch FROM occurred_at)::bigint AS epoch_seconds,\n    to_timestamp(1787500000) AS from_epoch\nFROM events;","how_it_works":"extract(epoch FROM timestamptz) counts true elapsed seconds since 1970-01-01 UTC, so it is DST-proof and orderable; on a plain timestamp PostgreSQL treats the value as UTC. to_timestamp reverses it and returns a timestamptz: to_timestamp(1787500000) is 2026-08-23 15:46:40 UTC, displayed in the session's zone. Milliseconds need a 1000 factor in both directions; keep the unit in the column name or someone will assume seconds.","variants":[{"sql":"SELECT\n    UNIX_TIMESTAMP(occurred_at) AS epoch_seconds,\n    FROM_UNIXTIME(1787500000) AS from_epoch\nFROM events;"},{"sql":"SELECT\n    DATEDIFF_BIG(SECOND, '1970-01-01 00:00:00', occurred_at) AS epoch_seconds,\n    DATEADD(SECOND, 1787500000, '1970-01-01 00:00:00') AS from_epoch\nFROM events;"}],"see_also":["timestamp-bucketing-5-minutes","normalize-stored-utc"],"faqs":[{"question":"Why did my epoch round-trip land an hour off?","answer":"Usually a session time zone got involved. MySQL's UNIX_TIMESTAMP and FROM_UNIXTIME read and write DATETIME values in the session time_zone, so run SET time_zone = '+00:00' when the column holds UTC. On PostgreSQL, casting to_timestamp's timestamptz result to a plain timestamp applies the session zone; use AT TIME ZONE 'UTC' instead. SQL Server's DATEDIFF from '1970-01-01' has no zone at all, so it is only right if occurred_at holds UTC."}]},"source_url":"https://sqlly.app/sql-snippets/epoch-conversions-both-ways","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/except-differences","corpus":"sql-snippets","engine":"all","language":"en","title":"Rows in one query but not another (EXCEPT)","description":"Use EXCEPT to find values present in the first result set and absent from the second.","body":{"slug":"except-differences","name":"Rows in one query but not another","h1":"Rows in one query but not another (EXCEPT)","category":"querying","lede":"A minus B is one line with EXCEPT; the operand order is the whole meaning.","engine_slug":"all","problem":"You want the customers whose orders are all still pending: customers with pending orders, minus customers who have had anything shipped.","sql":"SELECT customer_id\nFROM orders\nWHERE status = 'pending'\nEXCEPT\nSELECT customer_id\nFROM orders\nWHERE status = 'shipped'\nORDER BY customer_id;","how_it_works":"EXCEPT keeps the rows of the first query that do not appear in the second, deduplicated. Swapping the operands answers the opposite question, so read it as A minus B. Oracle accepts EXCEPT from 21c and has always had MINUS with the same meaning; MySQL supports EXCEPT from 8.0.31, and older versions can use the NOT EXISTS anti-join below.","variants":[{"sql":"SELECT DISTINCT a.customer_id\nFROM orders a\nWHERE a.status = 'pending'\n  AND NOT EXISTS (\n    SELECT 1 FROM orders b\n    WHERE b.customer_id = a.customer_id\n      AND b.status = 'shipped'\n  );"}],"see_also":["intersect-common-rows","full-outer-join-compare"],"faqs":[{"question":"Why dedupe in the emulation but not need to in EXCEPT?","answer":"EXCEPT removes duplicates by definition. In the NOT EXISTS version the same customer appears once per pending order, so DISTINCT restores the set semantics."},{"question":"What traps hide in the NOT IN emulation?","answer":"One: if the subquery returns a single NULL, NOT IN compares against NULL and returns no rows at all, on every engine. NOT EXISTS or the JOIN form is the NULL-safe spelling; MySQL needed one of them until EXCEPT arrived at 8.0.31."}]},"source_url":"https://sqlly.app/sql-snippets/except-differences","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/exists-flag-in-select","corpus":"sql-snippets","engine":"all","language":"en","title":"Exists flag in SELECT","description":"Add a 1/0 column per row saying whether a related row exists, without a join or a GROUP BY.","body":{"slug":"exists-flag-in-select","name":"Exists flag in SELECT","h1":"Exists flag in SELECT","category":"querying","lede":"EXISTS inside CASE stops at the first match, so it stays cheap even on big children.","engine_slug":"all","problem":"You want a customer list with a has-returns column, without joining orders and without inflating rows.","sql":"SELECT c.id, c.name,\n       CASE WHEN EXISTS (\n         SELECT 1\n         FROM orders o\n         WHERE o.customer_id = c.id\n           AND o.status = 'returned'\n       ) THEN 1 ELSE 0 END AS has_returns\nFROM customers c\nORDER BY c.name;","how_it_works":"For each customer the subquery just asks whether one matching order exists; the engine stops scanning at the first hit. No join means no duplicate rows to dedupe and no aggregate to keep in step with GROUP BY. PostgreSQL, MySQL, SQLite and Oracle 23ai also let you select the bare EXISTS (...) AS has_returns; SQL Server does not, so the CASE with 1/0 is the portable spelling.","variants":[{"sql":"SELECT c.id, c.name,\n       EXISTS (\n         SELECT 1\n         FROM orders o\n         WHERE o.customer_id = c.id\n           AND o.status = 'returned'\n       ) AS has_returns\nFROM customers c\nORDER BY c.name;"}],"see_also":["aggregate-children-per-parent","count-if-recipe","except-differences"],"faqs":[{"question":"Why not a LEFT JOIN with COUNT?","answer":"A join fetches every matching order just to answer yes/no, and needs a GROUP BY to fold the rows back to one per customer. EXISTS stops at the first match (an index on (customer_id, status) makes that a single seek) and adds one column, nothing more."}]},"source_url":"https://sqlly.app/sql-snippets/exists-flag-in-select","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/expensive-stored-procedures","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Find the most expensive stored procedures in SQL Server","description":"Ranks stored procedures by total and average elapsed time from sys.dm_exec_procedure_stats, with call counts, to point tuning at the right routine.","body":{"slug":"expensive-stored-procedures","name":"Expensive stored procedures","h1":"Find the most expensive stored procedures in SQL Server","category":"monitoring","lede":"Object-level stats for stored procedures: which routines burn the most server time, per call and in total.","engine_slug":"sql-server","problem":"sys.dm_exec_procedure_stats aggregates elapsed time, CPU, logical reads and call counts per cached procedure plan: the same shape as sys.dm_exec_query_stats but rolled up to the procedure, so a 500-statement routine becomes one row. That is the level most tuning conversations actually happen at: this procedure got slower, why.","sql":"SELECT TOP 25\n    OBJECT_SCHEMA_NAME(ps.object_id, ps.database_id) AS schema_name,\n    OBJECT_NAME(ps.object_id, ps.database_id) AS procedure_name,\n    ps.execution_count AS calls,\n    CAST(ps.total_elapsed_time / 1000.0 AS DECIMAL(18,1)) AS total_ms,\n    CAST(ps.total_elapsed_time / 1000.0 / NULLIF(ps.execution_count, 0) AS DECIMAL(18,2)) AS mean_ms,\n    CAST(ps.total_worker_time / 1000.0 / NULLIF(ps.execution_count, 0) AS DECIMAL(18,2)) AS mean_cpu_ms,\n    ps.last_execution_time\nFROM sys.dm_exec_procedure_stats ps\nWHERE ps.database_id = DB_ID()\n  AND ps.object_id IS NOT NULL\nORDER BY ps.total_elapsed_time DESC;","how_it_works":"total_elapsed_time is wall-clock across all executions since the plan was cached; dividing by execution_count gives mean time per call, which separates a fast procedure called a million times from a slow one called rarely; both need attention, for different reasons. mean_cpu_ms beside it shows whether the time is CPU-bound or mostly waiting (I/O, locks). The counters reset when the procedure's plan is evicted or the instance restarts; Query Store gives the durable version of this analysis for databases that need history. Triggers show up in sys.dm_exec_trigger_stats with the same columns.","variants":[{"sql":"SELECT TOP 25\n    OBJECT_SCHEMA_NAME(ps.object_id, ps.database_id) AS schema_name,\n    OBJECT_NAME(ps.object_id, ps.database_id) AS procedure_name,\n    ps.execution_count AS calls,\n    CAST(ps.total_elapsed_time / 1000.0 / NULLIF(ps.execution_count, 0) AS DECIMAL(18,2)) AS mean_ms\nFROM sys.dm_exec_procedure_stats ps\nWHERE ps.database_id = DB_ID()\n  AND ps.execution_count > 10\nORDER BY mean_ms DESC;"}],"see_also":["top-queries-by-total-time","high-logical-reads-queries","plan-regressions-query-store"],"faqs":[{"question":"A procedure is slow per call. What next?","answer":"Get inside it: sys.dm_exec_query_stats per statement (matched via the procedure's plan handle) or Query Store's per-query view shows which statement inside the routine owns the time. Procedure-level stats say where to look; statement-level stats say what to fix."},{"question":"Why do counts reset after a deploy?","answer":"Altering a procedure recompiles and replaces its cached plan, which resets its counters, so a deploy makes every touched procedure look freshly cheap. Check last_execution_time and correlate with deployment times before concluding a regression or a fix; Query Store survives this because its stats live in the database, not the cache."}]},"source_url":"https://sqlly.app/sql-snippets/expensive-stored-procedures","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/expiring-soon-checks","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find rows expiring within N days in SQL","description":"Label subscriptions and certificates as expired, expiring in the next 30 days, active or never-expiring in one CASE.","body":{"slug":"expiring-soon-checks","name":"Find rows expiring soon","h1":"Find rows expiring within N days in SQL","category":"querying","lede":"Renewal notices and cleanup jobs key off expiry dates: soon-to-expire, already-expired, and never-expires rows each need different handling.","engine_slug":"postgresql","problem":"One CASE splits the timeline into expired, expiring soon and active, with NULL handled as never expires.","sql":"SELECT\n    subscription_id,\n    expires_at,\n    CASE\n        WHEN expires_at IS NULL THEN 'never'\n        WHEN expires_at < CURRENT_TIMESTAMP THEN 'expired'\n        WHEN expires_at < CURRENT_TIMESTAMP + interval '30 days' THEN 'expiring'\n        ELSE 'active'\n    END AS status\nFROM subscriptions;","how_it_works":"NULL means no expiry, so the first CASE branch must run before any comparison, because NULL < anything is NULL, not true. The order of the WHEN branches matters too: 'expired' must be tested before 'expiring', because an expired row also satisfies expires_at < now + 30 days. Use the clock that matches how expires_at is stored: SYSUTCDATETIME() in the SQL Server variant assumes UTC values, while CURRENT_TIMESTAMP and NOW() follow the session time zone.","variants":[{"sql":"SELECT\n    subscription_id,\n    expires_at,\n    CASE\n        WHEN expires_at IS NULL THEN 'never'\n        WHEN expires_at < SYSUTCDATETIME() THEN 'expired'\n        WHEN expires_at < DATEADD(DAY, 30, SYSUTCDATETIME()) THEN 'expiring'\n        ELSE 'active'\n    END AS status\nFROM subscriptions;"},{"sql":"SELECT\n    subscription_id,\n    expires_at,\n    CASE\n        WHEN expires_at IS NULL THEN 'never'\n        WHEN expires_at < NOW() THEN 'expired'\n        WHEN expires_at < NOW() + INTERVAL 30 DAY THEN 'expiring'\n        ELSE 'active'\n    END AS status\nFROM subscriptions;"}],"see_also":["overlap-of-two-ranges","month-over-month-delta"],"faqs":[{"question":"Why compare to the database clock, not the app clock?","answer":"Using CURRENT_TIMESTAMP / SYSUTCDATETIME() keeps every row evaluated against one clock and one time zone: the database's. App-server clocks drift and may run in local time, which silently shifts who counts as 'expiring'."},{"question":"Do rows that expire today keep appearing in the sweep?","answer":"Yes: expires_at < now + 30 days includes today, so a daily job re-reports the row until the date passes. Add AND expires_at >= CURRENT_DATE when only strictly future expiries belong in the list, and keep the IS NULL branch first either way."}]},"source_url":"https://sqlly.app/sql-snippets/expiring-soon-checks","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/explain-query-plan-workflow","corpus":"sql-snippets","engine":"sqlite","language":"en","title":"Read EXPLAIN QUERY PLAN output in SQLite","description":"Prefix any query with EXPLAIN QUERY PLAN and read the SCAN vs SEARCH tree: which table walks every row, which uses an index, and where a temp b-tree appears.","body":{"slug":"explain-query-plan-workflow","name":"EXPLAIN QUERY PLAN","h1":"Read EXPLAIN QUERY PLAN output in SQLite","category":"indexes","lede":"SQLite's EXPLAIN QUERY PLAN is a short report: SCAN means a full pass over a table, SEARCH means an index lookup, TEMP B-TREE means an extra sort.","engine_slug":"sqlite","problem":"SQLite usually runs inside an application, often on a phone, where a query that scans a 200,000-row table on every screen load is the difference between instant and visibly slow. EXPLAIN QUERY PLAN prints how SQLite will access each table, one line per step, and four phrases cover most of what you need: SCAN, SEARCH, USING INDEX and USE TEMP B-TREE.","sql":"EXPLAIN QUERY PLAN\nSELECT o.id, o.total, c.name\nFROM orders o\nJOIN customers c ON c.id = o.customer_id\nWHERE o.created_at >= '2026-01-01'\nORDER BY o.total DESC;","how_it_works":"For a join, the table lines appear at the same level in loop order: the first is the outer loop and each later line runs once per row of the lines above it. Subqueries and CTEs are the parts drawn as indented children. With an index on orders.created_at, the output here is SEARCH o USING INDEX idx_orders_created (created_at>?), then SEARCH c USING INTEGER PRIMARY KEY (rowid=?), then USE TEMP B-TREE FOR ORDER BY. SCAN o would mean SQLite reads every row of o. A rowid lookup is the cheapest access there is. The temp B-tree means the ORDER BY does not match an index, so SQLite collects the rows and sorts them: fine for 100 rows, slow for a million. A SCAN on any table after the first is the line to fix, because it repeats once per outer row.","variants":[{"sql":"EXPLAIN\nSELECT o.id, o.total\nFROM orders o\nWHERE o.customer_id = 42;"},{"sql":"ANALYZE;\nEXPLAIN QUERY PLAN\nSELECT * FROM orders WHERE customer_id = 42 AND status = 'paid';"}],"see_also":["table-scan-detector","non-sargable-detector","sort-heavy-queries"],"faqs":[{"question":"SCAN shows up even though I created an index. Why?","answer":"Common causes: the WHERE clause wraps the column in a function (upper(status) = 'X' gives SCAN even with an index on status), the index does not lead with the filtered column, the column and the value have different type affinities, or the planner has no statistics. SQLite only knows how selective an index is after ANALYZE (or PRAGMA optimize) fills sqlite_stat1, so run it after creating indexes or loading data."},{"question":"What does USING COVERING INDEX mean?","answer":"Every column the query needs is in the index, so SQLite answers from the index and skips the lookup into the table for each row. SQLite has no INCLUDE clause, so you get it by adding the selected columns to the end of the index key: with CREATE INDEX ix_cc ON orders(customer_id, created_at), SELECT customer_id, created_at FROM orders WHERE customer_id = 5 shows SEARCH orders USING COVERING INDEX ix_cc."}]},"source_url":"https://sqlly.app/sql-snippets/explain-query-plan-workflow","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/extract-domain-from-email","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Extract the domain from an email address in SQL","description":"Get 'example.com' out of 'user@example.com' and group by it to find free-mail vs company accounts.","body":{"slug":"extract-domain-from-email","name":"Extract the domain from an email","h1":"Extract the domain from an email address in SQL","category":"text","lede":"Grouping signups by email domain (gmail.com vs corporate) is a common segmentation need.","engine_slug":"postgresql","problem":"The domain is whatever follows the @. split_part returns that piece directly and handles missing @ gracefully.","sql":"SELECT lower(split_part(email, '@', 2)) AS email_domain,\n       count(*) AS signups\nFROM users\nGROUP BY 1\nORDER BY signups DESC;","how_it_works":"split_part(text, '@', 2) returns the text after the first @, or an empty string when there is none, so malformed rows group under '' rather than erroring. Lowercasing first keeps Gmail.com and gmail.com in one bucket.","variants":[{"sql":"SELECT RIGHT(email, CHARINDEX('@', REVERSE(email) + '@') - 1) AS email_domain,\n       COUNT(*) AS signups\nFROM users\nGROUP BY RIGHT(email, CHARINDEX('@', REVERSE(email) + '@') - 1);"},{"sql":"SELECT LOWER(SUBSTRING_INDEX(email, '@', -1)) AS email_domain,\n       COUNT(*) AS signups\nFROM users\nGROUP BY email_domain;"}],"see_also":["split-full-name-first-last","mask-email-address"],"faqs":[{"question":"What about addresses with quotes or multiple @?","answer":"Quoted local parts technically may contain @ (rare and legal in RFC 5321). split_part and SUBSTRING_INDEX split on the first or last @ depending on the index argument; the SQL Server variant uses the last @ and returns the whole value when there is no @ at all. For a real system, validate addresses on input instead of parsing defensively in every query."},{"question":"What happens to rows with no @ at all?","answer":"PostgreSQL's split_part returns an empty string, so malformed rows group together under one blank bucket, while MySQL's SUBSTRING_INDEX hands back the whole raw value, so each malformed row gets its own group. Normalize or filter the missing-@ rows before you read the report."}]},"source_url":"https://sqlly.app/sql-snippets/extract-domain-from-email","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/extract-leading-digits","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Extract leading digits from a string in SQL","description":"Pull the numeric prefix out of codes like '123-ABC' with a regex substring or PATINDEX.","body":{"slug":"extract-leading-digits","name":"Extract leading digits","h1":"Extract leading digits from a string in SQL","category":"text","lede":"Codes like '123-ABC' or '42 Main St' begin with digits you need on their own for sorting or joining.","engine_slug":"postgresql","problem":"The house number in '42 Main St' is everything before the first letter. A pattern anchored at the start grabs it.","sql":"SELECT NULLIF(substring(address_line FROM '^[0-9]+'), '')::int AS house_number\nFROM addresses;","how_it_works":"substring with the pattern '^[0-9]+' returns the leading run of digits, or an empty string when there is none. NULLIF turns that empty string into NULL so the cast does not fail and rows without a leading number surface as NULL instead of erroring. extract-trailing-digits runs the mirror pattern, [0-9]+$, for version and sequence suffixes.","variants":[{"sql":"SELECT CAST(REGEXP_SUBSTR(address_line, '^[0-9]+') AS UNSIGNED) AS house_number\nFROM addresses;"},{"sql":"SELECT CAST(LEFT(address_line, PATINDEX('%[^0-9]%', address_line + ' ') - 1) AS INT) AS house_number\nFROM addresses;"}],"see_also":["extract-trailing-digits","safe-string-to-number"],"faqs":[{"question":"How does the SQL Server PATINDEX trick work?","answer":"PATINDEX finds the first non-digit; appending a space guarantees it always finds one, so subtracting 1 gives the length of the leading digit run. LEFT then takes exactly those digits. With no leading digits LEFT returns '', and CAST('' AS INT) is 0 on SQL Server, not NULL; wrap the LEFT in NULLIF(..., '') if you need NULL."}]},"source_url":"https://sqlly.app/sql-snippets/extract-leading-digits","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/extract-trailing-digits","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Extract trailing digits from a string in SQL","description":"Get the number off the end of 'Invoice-2026-047' for sorting and version comparison.","body":{"slug":"extract-trailing-digits","name":"Extract trailing digits","h1":"Extract trailing digits from a string in SQL","category":"text","lede":"Versioned names like 'report-3' and 'report-10' need the trailing number as a real integer for natural ordering.","engine_slug":"postgresql","problem":"The version number is the digit run at the end of the name. Anchor the pattern at the end to grab it.","sql":"SELECT NULLIF(substring(doc_name FROM '[0-9]+$'), '')::int AS version_no\nFROM documents;","how_it_works":"The pattern '[0-9]+$' matches digits only at the end of the string. Wrapping in NULLIF keeps rows with no numeric suffix as NULL rather than failing the cast. This is the same key used in the natural-sort recipe, shown here as a plain projection. This is extract-leading-digits anchored at the end of the string instead of the start.","variants":[{"sql":"SELECT CAST(REGEXP_SUBSTR(doc_name, '[0-9]+$') AS UNSIGNED) AS version_no\nFROM documents;"},{"sql":"SELECT CAST(RIGHT(doc_name, PATINDEX('%[^0-9]%', REVERSE(doc_name) + ' ') - 1) AS INT) AS version_no\nFROM documents;"}],"see_also":["extract-leading-digits","natural-sort-padded-numbers"],"faqs":[{"question":"What if digits appear in the middle too?","answer":"Only the final run matches: 'v2-fix-10' yields 10, not 210 or 2. If you need all digit groups, split the string with a regex-splitting function instead."}]},"source_url":"https://sqlly.app/sql-snippets/extract-trailing-digits","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/fifo-queue-consume","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Consume a FIFO queue","description":"Claim the oldest pending jobs safely with ORDER BY, LIMIT and FOR UPDATE SKIP LOCKED.","body":{"slug":"fifo-queue-consume","name":"FIFO queue consume","h1":"Consume a FIFO queue","category":"querying","lede":"Oldest-first selection plus row locks that skip what other workers already hold.","engine_slug":"postgresql","problem":"Several workers poll a jobs table. Each should take the oldest pending jobs and no two workers may take the same job.","sql":"WITH next_jobs AS (\n  SELECT id\n  FROM jobs\n  WHERE status = 'pending'\n  ORDER BY created_at, id\n  LIMIT 10\n  FOR UPDATE SKIP LOCKED\n)\nUPDATE jobs j\nSET status = 'processing'\nFROM next_jobs n\nWHERE j.id = n.id\nRETURNING j.id, j.created_at;","how_it_works":"The CTE sorts pending jobs oldest-first, locks the first ten, and SKIP LOCKED silently skips rows another worker locked a moment ago, so concurrent workers never double-claim. The UPDATE then flips exactly those rows and RETURNING hands them back. Without SKIP LOCKED workers queue behind each other's locks; without FOR UPDATE they race and process the same job twice. SKIP LOCKED needs PostgreSQL 9.5+, MySQL 8.0+ or Oracle; SQL Server gets the same effect from the READPAST hint, and its plain UPDATE TOP (10) would pick arbitrary rows, which is why the variant sorts inside a CTE.","variants":[{"sql":"UPDATE jobs j\nJOIN (\n  SELECT id FROM jobs\n  WHERE status = 'pending'\n  ORDER BY created_at, id\n  LIMIT 10\n  FOR UPDATE SKIP LOCKED\n) n ON n.id = j.id\nSET j.status = 'processing';"},{"sql":"WITH next_jobs AS (\n  SELECT TOP (10) id, created_at, status\n  FROM jobs WITH (ROWLOCK, UPDLOCK, READPAST)\n  WHERE status = 'pending'\n  ORDER BY created_at, id\n)\nUPDATE next_jobs\nSET status = 'processing'\nOUTPUT inserted.id, inserted.created_at;"}],"see_also":["next-job-id","keyset-pagination"],"faqs":[{"question":"Why not just SELECT the oldest rows and update them after?","answer":"Between the SELECT and the UPDATE another worker can claim the same rows. The lock must be taken while reading, which is exactly what FOR UPDATE SKIP LOCKED does in one round trip."}]},"source_url":"https://sqlly.app/sql-snippets/fifo-queue-consume","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/fill-gaps-calendar-spine","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Fill gaps with a calendar spine","description":"LEFT JOIN daily totals onto generate_series dates so empty days show as zero instead of vanishing.","body":{"slug":"fill-gaps-calendar-spine","name":"Fill gaps with a calendar spine","h1":"Fill gaps with a calendar spine","category":"querying","lede":"Build the date range first, then attach the facts. Charts stop lying about missing days.","engine_slug":"postgresql","problem":"Your revenue chart skips days with no orders, which makes quiet periods invisible. You want every day in the range, with a zero where nothing sold.","sql":"WITH days AS (\n  SELECT generate_series(DATE '2026-06-01', DATE '2026-06-30',\n                         INTERVAL '1 day')::date AS day\n),\nsales AS (\n  SELECT CAST(order_date AS date) AS day, SUM(amount) AS total\n  FROM orders\n  GROUP BY 1\n)\nSELECT d.day, COALESCE(s.total, 0) AS total\nFROM days d\nLEFT JOIN sales s ON s.day = d.day\nORDER BY d.day;","how_it_works":"The CTE builds every day in the range with generate_series, regardless of whether orders exist. LEFT JOINing the sales onto the spine keeps all days; COALESCE turns the missing totals into zero. Other engines build the same spine with a recursive CTE; SQLite can use either a recursive CTE or the generate_series table-valued function from its series extension, which the sqlite3 CLI includes.","variants":[{"sql":"WITH RECURSIVE days AS (\n  SELECT DATE '2026-06-01' AS day\n  UNION ALL\n  SELECT day + INTERVAL 1 DAY\n  FROM days\n  WHERE day < DATE '2026-06-30'\n)\nSELECT d.day, COALESCE(SUM(o.amount), 0) AS total\nFROM days d\nLEFT JOIN orders o\n       ON o.order_date >= d.day\n      AND o.order_date <  d.day + INTERVAL 1 DAY\nGROUP BY d.day\nORDER BY d.day;"},{"sql":"WITH days AS (\n  SELECT CAST('2026-06-01' AS date) AS day\n  UNION ALL\n  SELECT DATEADD(day, 1, day)\n  FROM days\n  WHERE day < '2026-06-30'\n)\nSELECT d.day, COALESCE(SUM(o.amount), 0) AS total\nFROM days d\nLEFT JOIN orders o\n       ON o.order_date >= d.day\n      AND o.order_date <  DATEADD(day, 1, d.day)\nGROUP BY d.day\nORDER BY d.day;"}],"see_also":["cumulative-total-by-month","month-over-month-delta","hourly-buckets"],"faqs":[{"question":"Why a LEFT JOIN and not an INNER JOIN?","answer":"An INNER JOIN joins only the days that have sales, which is exactly the skipping you are trying to fix. The spine drives the row set; the facts attach to it."},{"question":"How wide should the calendar spine be?","answer":"From the first to the last day the chart names, not from MIN to MAX of the data: a spine that outruns the data pads leading and trailing zeros most charts should not show. Generate it per query, or materialize a calendar table once and LEFT JOIN against it."}]},"source_url":"https://sqlly.app/sql-snippets/fill-gaps-calendar-spine","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/find-candidate-keys","corpus":"sql-snippets","engine":"all","language":"en","title":"Find candidate key columns","description":"Measure distinct-value counts per column against the row count: a full match marks a candidate key.","body":{"slug":"find-candidate-keys","name":"Candidate keys","h1":"Find candidate key columns","category":"data-quality","lede":"Compare COUNT(DISTINCT col) with COUNT(*) for each key-hopeful column; equality means the column is unique today.","engine_slug":"all","problem":"You suspect order_ref or the email column could carry a unique constraint. Today's distinct counts tell you which columns are actually unique, and which just look unique in small samples.","sql":"SELECT 'email' AS column_name,\n       COUNT(*) AS total_rows,\n       COUNT(email) AS non_null_values,\n       COUNT(DISTINCT email) AS distinct_values,\n       CASE WHEN COUNT(email) = COUNT(DISTINCT email)\n            THEN 'unique where set'\n            ELSE 'has duplicates'\n       END AS verdict\nFROM customers\nUNION ALL\nSELECT 'phone', COUNT(*), COUNT(phone), COUNT(DISTINCT phone),\n       CASE WHEN COUNT(phone) = COUNT(DISTINCT phone)\n            THEN 'unique where set'\n            ELSE 'has duplicates'\n       END\nFROM customers;","how_it_works":"COUNT(col) counts the non-NULL values and COUNT(DISTINCT col) the distinct ones; when they are equal, no value repeats. Comparing against COUNT(*) instead would call any column with a NULL a duplicate. If non_null_values is below total_rows the column is unique but not a primary key candidate until the NULLs are filled; a UNIQUE constraint still accepts it on every engine except SQL Server, which allows only one NULL in a unique index. The CASE turns the counts into a verdict and UNION ALL stacks the checked columns into one report. Run it before any CREATE UNIQUE INDEX: the index fails the moment a duplicate exists.","variants":[{"sql":"SELECT email, COUNT(*) AS occurrences\nFROM customers\nWHERE email IS NOT NULL\nGROUP BY email\nHAVING COUNT(*) > 1;"},{"sql":"SELECT t.total_rows, d.distinct_pairs\nFROM (SELECT COUNT(*) AS total_rows FROM order_items) t\nCROSS JOIN (\n  SELECT COUNT(*) AS distinct_pairs\n  FROM (SELECT DISTINCT order_id, product_id FROM order_items) pairs\n) d;"}],"see_also":["find-duplicates-on-a-key","case-insensitive-duplicate-emails","duplicate-natural-keys-different-ids"],"faqs":[{"question":"The column is unique today. Is that a candidate key?","answer":"Only provisionally: uniqueness in a snapshot is a property of the data, while a key is a property of the rules. If the business guarantees the value is never reused, add the unique constraint; if not, the next load will break the index. Unique-today columns with no business rule behind them are a trap, not a key."}]},"source_url":"https://sqlly.app/sql-snippets/find-candidate-keys","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/find-columns-by-type","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find columns by data type","description":"Every column in a schema of a given type, optionally with a given length or precision, such as all the varchar(50) phone numbers you plan to widen.","body":{"slug":"find-columns-by-type","name":"Find columns by type","h1":"Find columns by data type","category":"schema","lede":"Planning a type migration starts with a census: which columns are varchar(50), which are float, which still use money. This query lists every column of a given type and length.","engine_slug":"postgresql","problem":"A type is being retired or widened, and before touching anything you need the complete inventory of columns declared with that type and length.","sql":"SELECT table_schema, table_name, column_name,\n       data_type, character_maximum_length\nFROM information_schema.columns\nWHERE table_schema = 'public'\n  AND data_type = 'character varying'\n  AND character_maximum_length = 50\nORDER BY table_name, column_name;","how_it_works":"information_schema.columns exposes type plus the length and precision attributes, so filtering on both finds exactly varchar(50)-style columns. data_type for varchar reads 'character varying'; for timestamp-with-time-zone it reads 'timestamp with time zone', so match the full spelled-out type. On MySQL, data_type reads 'int' for both int and int unsigned, so a type filter cannot tell them apart there; COLUMN_TYPE carries the unsigned flag. Drop the length filter to see every column of the type.","variants":[{"sql":"SELECT SCHEMA_NAME(tb.schema_id) AS schema_name,\n       tb.name AS table_name,\n       c.name AS column_name,\n       t.name AS type_name, c.max_length\nFROM sys.columns c\nJOIN sys.tables tb ON tb.object_id = c.object_id\nJOIN sys.types t ON t.user_type_id = c.user_type_id\nWHERE t.name = 'varchar' AND c.max_length = 50\nORDER BY schema_name, table_name;"},{"sql":"SELECT table_name, column_name, column_type\nFROM information_schema.columns\nWHERE table_schema = 'mydb' AND column_type = 'varchar(50)'\nORDER BY table_name;"}],"see_also":["find-tables-with-column","widen-column-type","describe-table-columns"],"faqs":[{"question":"Why does max_length look doubled for nvarchar on SQL Server?","answer":"sys.columns.max_length is measured in bytes, and nvarchar stores UTF-16, so nvarchar(50) reports 100 and nvarchar(max) reports -1. Adjust the comparison accordingly: max_length = 100 for nvarchar(50)."},{"question":"Why do signed and unsigned int columns look identical on MySQL?","answer":"information_schema.columns.data_type reads 'int' for both; the unsigned flag lives in COLUMN_TYPE ('int unsigned'). Match on column_type when signedness or display width matters to the migration."}]},"source_url":"https://sqlly.app/sql-snippets/find-columns-by-type","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/find-control-characters","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find rows containing control characters","description":"A regex over ASCII control ranges catches tabs, newlines and invisible characters hiding in text columns.","body":{"slug":"find-control-characters","name":"Control characters","h1":"Find rows containing control characters","category":"data-quality","lede":"Match any character in the ASCII 0x01-0x1F control range and list the offending rows; a REPLACE chain is the portable fallback.","engine_slug":"postgresql","problem":"CSV exports break and JSON parsers choke on invisible characters that copy-paste brought into customers.name. Find every row carrying one before the next integration failure.","sql":"SELECT id, name,\n       LENGTH(name) AS name_length\nFROM customers\nWHERE name ~ '[\\x01-\\x1F]'\nORDER BY id;","how_it_works":"The pattern [\\x01-\\x1F] matches any character with a code point between 1 and 31: tab (9), newline (10), carriage return (13), and the invisible controls around them. NUL (0) cannot be stored in PostgreSQL text at all, so the range starts at 1. Rows that match are the ones to clean with REPLACE or at the import boundary. The REPLACE chain variant uses CHR(); on MySQL, SQL Server and SQLite write CHAR(9), CHAR(13) and CHAR(10) instead.","variants":[{"sql":"SELECT id, name\nFROM customers\nWHERE name IS NOT NULL\n  AND name <> REPLACE(REPLACE(REPLACE(\n        name, CHR(9), ''), CHR(13), ''), CHR(10), '');"},{"sql":"SELECT id, name,\n       (REGEXP_MATCHES(name, '[\\x01-\\x1F]', 'g'))[1] AS control_found\nFROM customers\nWHERE name ~ '[\\x01-\\x1F]';"}],"see_also":["trim-whitespace-duplicates","validate-email-shape","find-truncated-values"],"faqs":[{"question":"Why not just trim the column?","answer":"Plain TRIM only removes spaces from the ends, so a tab at the start of a name and a newline in the middle both survive it. This query finds control characters wherever they sit, and the REPLACE chain turns into the cleanup when you move it into an UPDATE ... SET name = REPLACE(...)."}]},"source_url":"https://sqlly.app/sql-snippets/find-control-characters","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/find-duplicate-rows-all-columns","corpus":"sql-snippets","engine":"all","language":"en","title":"Find duplicate rows across all columns","description":"Spot exact duplicate rows in a table with no primary key, using GROUP BY and HAVING over every column.","body":{"slug":"find-duplicate-rows-all-columns","name":"Duplicate rows, all columns","h1":"Find duplicate rows across all columns","category":"data-quality","lede":"A table without a primary key or an import that ran twice can hold byte-for-byte identical rows. This recipe surfaces each distinct row that appears more than once, with its copy count.","engine_slug":"all","problem":"imported_orders landed without a key and the ETL may have loaded the same file twice. Before you can dedupe or add a primary key you need to know which rows repeat and how often.","sql":"SELECT customer_id, order_date, status, total, COUNT(*) AS copies\nFROM imported_orders\nGROUP BY customer_id, order_date, status, total\nHAVING COUNT(*) > 1\nORDER BY copies DESC;","how_it_works":"GROUP BY over every column collapses identical rows into one group; HAVING COUNT(*) > 1 keeps only the groups that repeated, and the ORDER BY puts the worst offenders first. GROUP BY treats NULLs as equal, so two rows that both have a NULL status still count as copies, which is what a dedupe wants. What counts as identical text depends on collation: MySQL 8's default utf8mb4_0900_ai_ci and SQL Server's SQL_Latin1_General_CP1_CI_AS are case-insensitive, and SQL Server also ignores trailing spaces when comparing, so those engines can report more copies than PostgreSQL, SQLite or Oracle on the same data.","variants":[{"sql":"SELECT COALESCE(SUM(copies - 1), 0) AS surplus_rows\nFROM (\n  SELECT customer_id, order_date, status, total, COUNT(*) AS copies\n  FROM imported_orders\n  GROUP BY customer_id, order_date, status, total\n  HAVING COUNT(*) > 1\n) dupes;"},{"sql":"SELECT DISTINCT customer_id, order_date, status, total\nFROM imported_orders;"}],"see_also":["find-duplicates-on-a-key","delete-duplicates-keep-one","trim-whitespace-duplicates"],"faqs":[{"question":"Why not just GROUP BY the primary key?","answer":"A primary key is unique by definition, so grouping by it can never reveal duplicates. This recipe is for tables that lack a key, or for the non-key columns that should have been unique together. Once you confirm the shape of the duplicates, add a key so it cannot happen again."},{"question":"Can this result become a unique index?","answer":"Only after the extras go: CREATE UNIQUE INDEX fails while duplicate groups exist on every engine. Run delete-duplicates-keep-one first, then add the index so the shape cannot come back."}]},"source_url":"https://sqlly.app/sql-snippets/find-duplicate-rows-all-columns","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/find-duplicates-on-a-key","corpus":"sql-snippets","engine":"all","language":"en","title":"Find duplicates on a key column","description":"List every repeated value in a key column with its occurrence count, worst first.","body":{"slug":"find-duplicates-on-a-key","name":"Duplicates on a key","h1":"Find duplicates on a key column","category":"data-quality","lede":"The classic duplicate check: group by the column that should be unique and keep only the values that appear more than once.","engine_slug":"all","problem":"customers.email is supposed to be unique but was never given a unique constraint. You need the list of offending values before you can merge accounts or add the constraint.","sql":"SELECT email, COUNT(*) AS occurrences\nFROM customers\nGROUP BY email\nHAVING COUNT(*) > 1\nORDER BY occurrences DESC;","how_it_works":"GROUP BY email collects all rows sharing an address; HAVING filters down to values with more than one row and ORDER BY ranks the repeats. Swap email for any column that should be unique: a phone number, an SKU, an invoice number.","variants":[{"sql":"WITH dupes AS (\n  SELECT email\n  FROM customers\n  GROUP BY email\n  HAVING COUNT(*) > 1\n)\nSELECT c.*\nFROM customers c\nJOIN dupes d ON d.email = c.email\nORDER BY c.email, c.id;"},{"sql":"SELECT order_id, product_id, COUNT(*) AS occurrences\nFROM order_items\nGROUP BY order_id, product_id\nHAVING COUNT(*) > 1;"}],"see_also":["case-insensitive-duplicate-emails","dedupe-with-window-functions","delete-duplicates-keep-one"],"faqs":[{"question":"How do I see which rows to keep and which to merge?","answer":"Join the duplicate values back to the table (first variant) and you get the full rows side by side. Each group of equal emails is a merge candidate: pick the survivor, point its children at it, and remove the rest. The delete-duplicates-keep-one recipe automates that for the common case."},{"question":"Why do MySQL and SQL Server report fewer duplicate emails than PostgreSQL?","answer":"Their default collations are case-insensitive, so Ada@X.io and ada@x.io land in one group there, while PostgreSQL, SQLite and Oracle compare bytes and count two. Lower the column before grouping when the answer must match across engines."}]},"source_url":"https://sqlly.app/sql-snippets/find-duplicates-on-a-key","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/find-identity-columns","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find auto-increment and identity columns","description":"Every auto-generated key column in a schema (identity, serial or AUTO_INCREMENT), the list you need before moving int keys to bigint.","body":{"slug":"find-identity-columns","name":"Find identity columns","h1":"Find auto-increment and identity columns","category":"schema","lede":"Auto-generated key columns come in engine-specific flavors: IDENTITY, serial, AUTO_INCREMENT. A census of them tells you which sequences are approaching overflow and which tables depend on generated ids.","engine_slug":"postgresql","problem":"Planning a key-type migration starts with knowing every generated key column in the schema and how each one is declared.","sql":"SELECT table_schema, table_name, column_name,\n       is_identity, identity_generation, column_default\nFROM information_schema.columns\nWHERE table_schema = 'public'\n  AND (is_identity = 'YES'\n       OR column_default LIKE 'nextval%')\nORDER BY table_name;","how_it_works":"PostgreSQL has two kinds of auto-generated key: identity columns (is_identity = 'YES', available since PostgreSQL 10) and serial columns, which are a plain DEFAULT nextval(...) on a sequence. The OR catches both, and identity_generation tells ALWAYS from BY DEFAULT. The difference matters when you alter them: an identity column is changed with ALTER COLUMN ... SET/RESTART, a serial one through its sequence. For overflow checks, pair this output with last_value from the sequences recipe. find-tables-with-column drives the same catalog sweep with a column-name filter.","variants":[{"sql":"SELECT SCHEMA_NAME(t.schema_id) AS schema_name,\n       t.name AS table_name,\n       ic.name AS column_name,\n       TYPE_NAME(ic.system_type_id) AS type_name,\n       ic.seed_value, ic.increment_value,\n       ic.last_value   -- NULL until the first insert\nFROM sys.identity_columns ic\nJOIN sys.tables t ON t.object_id = ic.object_id\nORDER BY schema_name, table_name;"},{"sql":"SELECT table_name, column_name, column_type, extra\nFROM information_schema.columns\nWHERE table_schema = 'mydb' AND extra = 'auto_increment'\nORDER BY table_name;"},{"sql":"-- a single-column INTEGER PRIMARY KEY is the rowid alias and\n-- auto-generates; AUTOINCREMENT only stops ids being reused\nSELECT m.name AS table_name, ti.name AS column_name,\n       m.sql LIKE '%AUTOINCREMENT%' AS has_autoincrement\nFROM sqlite_master m\nJOIN pragma_table_info(m.name) ti ON ti.pk = 1\nWHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%'\n  AND upper(ti.type) = 'INTEGER'\n  AND (SELECT COUNT(*) FROM pragma_table_info(m.name) p\n       WHERE p.pk > 0) = 1;"}],"see_also":["list-sequences-current-values","list-table-columns","find-columns-by-type","find-tables-with-column"],"faqs":[{"question":"What is the difference between IDENTITY and SERIAL in PostgreSQL?","answer":"Both draw ids from a sequence. IDENTITY is the SQL-standard form: the sequence belongs to the column, GENERATED ALWAYS rejects hand-supplied values unless the INSERT says OVERRIDING SYSTEM VALUE, and roles that can insert need no separate grant on the sequence. SERIAL is shorthand for an integer column with a nextval() default; the sequence is a separate object that needs its own USAGE grant, and the default can be changed or dropped like any other. Prefer IDENTITY for new tables."},{"question":"How does the MySQL census differ from the PostgreSQL one?","answer":"MySQL marks the column in information_schema.columns.EXTRA as 'auto_increment' and allows one such column per table, so a string match on EXTRA is the whole check. On SQLite only the CREATE statement text in sqlite_master shows the AUTOINCREMENT keyword, and plain rowid tables get generated ids without it."}]},"source_url":"https://sqlly.app/sql-snippets/find-identity-columns","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/find-nth-occurrence-substring","corpus":"sql-snippets","engine":"oracle","language":"en","title":"Find the position of the nth occurrence of a substring in SQL","description":"Locate the third comma or second hyphen with INSTR and REGEXP_INSTR instead of nested CHARINDEX calls.","body":{"slug":"find-nth-occurrence-substring","name":"Find the nth occurrence of a substring","h1":"Find the position of the nth occurrence of a substring in SQL","category":"text","lede":"Parsing fixed-format codes ('AA-BB-CC-DD') means finding the second or third delimiter, not the first.","engine_slug":"oracle","problem":"The position of the third delimiter is the anchor for parsing 'AA-BB-CC-DD'. Oracle's INSTR takes an occurrence number directly.","sql":"SELECT INSTR(code, '-', 1, 3) AS third_dash\nFROM parts;","how_it_works":"INSTR(search, target, start, occurrence) starts at position 1 and returns the position of the nth match, or 0 when there is no nth match. SQL Server has no occurrence argument, so there you nest CHARINDEX calls, each starting one past the previous match. MySQL 8 and PostgreSQL 15+ take the same occurrence argument in REGEXP_INSTR (the target is a regex there, so escape metacharacters such as '.').","variants":[{"sql":"SELECT REGEXP_INSTR(code, '-', 1, 3) AS third_dash\nFROM parts;"},{"sql":"SELECT REGEXP_INSTR(code, '-', 1, 3) AS third_dash\nFROM parts;"}],"see_also":["count-substring-occurrences","extract-trailing-digits"],"faqs":[{"question":"What does a result of 0 mean?","answer":"INSTR and REGEXP_INSTR return 0 when there is no nth occurrence, not NULL. Decide whether 0 should mean 'not present' for your parse; usually you guard with NULLIF(pos, 0) or a CASE."}]},"source_url":"https://sqlly.app/sql-snippets/find-nth-occurrence-substring","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/find-orphaned-rows","corpus":"sql-snippets","engine":"all","language":"en","title":"Find rows orphaned from their parent","description":"Find child rows whose parent id no longer matches any row in the parent table, with a LEFT JOIN anti-join.","body":{"slug":"find-orphaned-rows","name":"Orphaned rows","h1":"Find rows orphaned from their parent","category":"data-quality","lede":"When a parent row is deleted without cleaning up its children, the children become orphans. A LEFT JOIN against the parent with an IS NULL test finds every one of them.","engine_slug":"all","problem":"orders.customer_id should always point at a customers row, but manual deletes and broken imports have left orders whose customer no longer exists. You need the list before you reassign or remove those orders.","sql":"SELECT o.id AS order_id, o.customer_id, o.order_date, o.total\nFROM orders o\nLEFT JOIN customers c ON c.id = o.customer_id\nWHERE o.customer_id IS NOT NULL\n  AND c.id IS NULL;","how_it_works":"The LEFT JOIN keeps every order and carries NULLs for the ones whose customer is gone. The first WHERE condition ignores orders that deliberately have no customer; the second keeps only orders whose lookup found no parent. A NOT EXISTS variant is equivalent and sometimes reads better.","variants":[{"sql":"SELECT o.id AS order_id, o.customer_id\nFROM orders o\nWHERE o.customer_id IS NOT NULL\n  AND NOT EXISTS (\n    SELECT 1 FROM customers c WHERE c.id = o.customer_id\n  );"},{"sql":"SELECT o.customer_id, COUNT(*) AS orphaned_orders\nFROM orders o\nLEFT JOIN customers c ON c.id = o.customer_id\nWHERE o.customer_id IS NOT NULL AND c.id IS NULL\nGROUP BY o.customer_id\nORDER BY orphaned_orders DESC;"}],"see_also":["multi-parent-orphan-sweep","referential-audit-both-directions","missing-parent-references"],"faqs":[{"question":"Why exclude o.customer_id IS NULL?","answer":"A NULL customer_id means 'no parent on purpose', which is not an orphan: the row simply has no relationship. Filtering it out leaves only rows that claim a parent the parent table cannot find. Drop the condition if NULLs in this column are themselves a rule violation in your schema."},{"question":"Does the cleanup DELETE need the same guard?","answer":"Yes: carry WHERE o.customer_id IS NOT NULL into the DELETE, or a scheduled cleanup will remove every row whose optional reference is legitimately unset. Preview with this recipe, then keep the guard in the destructive statement."}]},"source_url":"https://sqlly.app/sql-snippets/find-orphaned-rows","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/find-tables-with-column","corpus":"sql-snippets","engine":"mysql","language":"en","title":"Find every table that has a given column","description":"Search a whole schema for a column name to find every table that stores an email, tenant_id or other shared key before you change it.","body":{"slug":"find-tables-with-column","name":"Find tables with a column","h1":"Find every table that has a given column","category":"schema","lede":"Rename a column and half the schema breaks, unless you first find everywhere it appears. This query searches the metadata for every table that has a column with a given name.","engine_slug":"mysql","problem":"A shared column shows up in far more tables than anyone remembers, and work such as a rename or encryption pass needs the complete hit list up front.","sql":"SELECT table_schema, table_name, column_name, data_type\nFROM information_schema.columns\nWHERE column_name = 'email'\n  AND table_schema = 'mydb'\nORDER BY table_name;","how_it_works":"information_schema.columns is one row per column of every table, so a filter on column_name finds every table storing that field. Add table_schema to scope the search; without it you also scan system schemas. Column names are case-insensitive in MySQL, so 'email' also matches Email. On PostgreSQL the match is exact against the stored name, which is lowercase unless the column was created with a quoted mixed-case identifier. find-identity-columns sweeps the same catalogs with a type filter instead of a name filter.","variants":[{"sql":"SELECT table_schema, table_name, column_name, data_type\nFROM information_schema.columns\nWHERE column_name = 'email'\n  AND table_schema NOT IN ('pg_catalog', 'information_schema')\nORDER BY table_schema, table_name;"},{"sql":"SELECT SCHEMA_NAME(t.schema_id) AS schema_name,\n       t.name AS table_name,\n       c.name AS column_name\nFROM sys.columns c\nJOIN sys.tables t ON t.object_id = c.object_id\nWHERE c.name = 'email'\nORDER BY schema_name, table_name;\n-- join sys.objects instead to include views and functions"},{"sql":"SELECT m.name AS table_name, ti.name AS column_name\nFROM sqlite_master m\nJOIN pragma_table_info(m.name) ti ON true\nWHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%'\n  AND ti.name = 'email'\nORDER BY m.name;"}],"see_also":["find-columns-by-type","describe-table-columns","rename-column-if-exists","find-identity-columns"],"faqs":[{"question":"Does this also search views?","answer":"The information_schema version does: views appear in information_schema.columns alongside tables. Join information_schema.tables and filter table_type = 'BASE TABLE' to drop them. The SQL Server and SQLite variants above list tables only; use sys.objects, or m.type IN ('table', 'view'), to include views."}]},"source_url":"https://sqlly.app/sql-snippets/find-tables-with-column","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/find-truncated-values","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find values truncated at the max length","description":"Flag strings sitting exactly at the column's max length, the signature of silent truncation.","body":{"slug":"find-truncated-values","name":"Truncated values","h1":"Find values truncated at the max length","category":"data-quality","lede":"Compare each value's length against the column limit and list the rows pinned at the ceiling, where silent truncation leaves its mark.","engine_slug":"postgresql","problem":"products.name is VARCHAR(50) and old loaders cut overflow silently. Values measuring exactly 50 characters are the ones to re-check against the source feed.","sql":"SELECT id, name, LENGTH(name) AS name_length\nFROM products\nWHERE LENGTH(name) = 50\nORDER BY name_length DESC, id;","how_it_works":"LENGTH(name) measures each value in characters; the predicate keeps only values exactly at the column's declared limit. A value that hits the ceiling exactly is rarely a coincidence. It is usually the visible stump of a longer source string. Repeat with each width-limited column.","variants":[{"sql":"SELECT id, name, DATALENGTH(name) AS name_bytes\nFROM products\nWHERE DATALENGTH(name) = 50\nORDER BY id;"},{"sql":"SELECT c.column_name, c.character_maximum_length\nFROM information_schema.columns c\nWHERE c.table_name = 'products'\n  AND c.data_type = 'character varying'\nORDER BY c.ordinal_position;"}],"see_also":["trim-whitespace-duplicates","find-control-characters"],"faqs":[{"question":"Why characters and not bytes?","answer":"Because PostgreSQL declares VARCHAR(50) in characters, and so does MySQL. Measure the same unit the limit uses: LENGTH on PostgreSQL and SQLite, CHAR_LENGTH on MySQL (its LENGTH counts bytes). The other two differ: Oracle's VARCHAR2(50) means 50 bytes unless declared with CHAR semantics, so use LENGTHB there, and SQL Server's VARCHAR(50) is 50 bytes, so use DATALENGTH, which unlike LEN also counts trailing spaces."},{"question":"Can the truncation be stopped before it happens?","answer":"PostgreSQL and SQL Server reject the over-long insert outright (SQL Server raises error 8152), while MySQL outside strict mode silently truncates with a warning. Run the writer under STRICT_TRANS_TABLES; this query is for catching what already slipped through."}]},"source_url":"https://sqlly.app/sql-snippets/find-truncated-values","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/first-and-last-day-of-month","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Get the first and last day of the month in SQL","description":"Bucket a date to its month boundaries with EOMONTH, date_trunc, LAST_DAY or TRUNC.","body":{"slug":"first-and-last-day-of-month","name":"First and last day of the month","h1":"Get the first and last day of the month in SQL","category":"text","lede":"Monthly reports and billing periods need clean month-start and month-end boundaries from any date.","engine_slug":"sql-server","problem":"EOMONTH is purpose-built for month end; the first of the month comes from DATEFROMPARTS with day 1.","sql":"SELECT\n    DATEFROMPARTS(YEAR(d), MONTH(d), 1) AS month_start,\n    EOMONTH(d) AS month_end\nFROM (SELECT CAST('2026-03-04' AS DATE) AS d) x;","how_it_works":"DATEFROMPARTS rebuilds the date with day 1 to get the month start, and EOMONTH(d) returns the last day of d's month, leap years included. Both exist since SQL Server 2012 and avoid the old DATEADD/DAY arithmetic that is easy to get wrong. first-and-last-day-of-quarter is the PostgreSQL variant of this page with 'quarter' in the date_trunc call.","variants":[{"sql":"SELECT\n    date_trunc('month', d)::date AS month_start,\n    (date_trunc('month', d) + interval '1 month - 1 day')::date AS month_end\nFROM (SELECT DATE '2026-03-04' AS d) x;"},{"sql":"SELECT\n    DATE_SUB(d, INTERVAL DAY(d) - 1 DAY) AS month_start,\n    LAST_DAY(d) AS month_end\nFROM (SELECT CURDATE() AS d) x;"},{"sql":"SELECT\n    TRUNC(d, 'MM') AS month_start,\n    LAST_DAY(d) AS month_end\nFROM (SELECT DATE '2026-03-04' AS d FROM dual);"}],"see_also":["first-and-last-day-of-week","first-and-last-day-of-quarter","days-in-month"],"faqs":[{"question":"How do I bucket a timestamp range by month?","answer":"Group by the month_start expression, or filter with ts >= month_start AND ts < next month's start. Do not filter a timestamp column with <= month_end: month_end is midnight at the start of the last day, so everything later that day is missed. Oracle's LAST_DAY also keeps the time part of its input."},{"question":"What about SQL Server 2008?","answer":"EOMONTH and DATEFROMPARTS arrived in SQL Server 2012, so 2008 needs the older DATEADD/DATEDIFF arithmetic against the zero date for both boundaries. Everything else on this page already speaks that dialect, so the change stays local to the two expressions."}]},"source_url":"https://sqlly.app/sql-snippets/first-and-last-day-of-month","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/first-and-last-day-of-quarter","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Get the first and last day of the quarter in SQL","description":"Snap any date to its quarter boundaries (Jan 1, Apr 1, Jul 1, Oct 1 and friends).","body":{"slug":"first-and-last-day-of-quarter","name":"First and last day of the quarter","h1":"Get the first and last day of the quarter in SQL","category":"text","lede":"Quarterly reporting buckets every date into three-month windows that start in January, April, July and October.","engine_slug":"sql-server","problem":"Integer arithmetic maps month 1-12 onto quarter start months 1, 4, 7, 10; EOMONTH finishes the job.","sql":"SELECT\n    DATEFROMPARTS(YEAR(d), (MONTH(d) - 1) / 3 * 3 + 1, 1) AS quarter_start,\n    EOMONTH(d, 2 - (MONTH(d) - 1) % 3) AS quarter_end\nFROM (SELECT CAST('2026-05-20' AS DATE) AS d) x;","how_it_works":"(MONTH(d) - 1) / 3 * 3 + 1 turns months 1-3 into 1, 4-6 into 4, and so on. For the end, EOMONTH(d, n) moves n months from d's month end; the offset 2 - (MONTH(d) - 1) % 3 lands on the quarter's final month, whose last day is the quarter end. Leap-year Feb 29 is handled by EOMONTH itself. This is the month recipe from first-and-last-day-of-month with the trunc unit changed.","variants":[{"sql":"SELECT\n    date_trunc('quarter', d)::date AS quarter_start,\n    (date_trunc('quarter', d) + interval '3 months - 1 day')::date AS quarter_end\nFROM (SELECT DATE '2026-05-20' AS d) x;"}],"see_also":["first-and-last-day-of-month","first-and-last-day-of-year","fiscal-year-mapping"],"faqs":[{"question":"Can I group by quarter directly?","answer":"Yes: GROUP BY the quarter_start expression and every date in the quarter shares one key. On PostgreSQL, date_trunc('quarter', d) is the shortest form of that key."},{"question":"Why does the month-to-quarter expression break when ported to MySQL?","answer":"(MONTH(d) - 1) / 3 is integer division on SQL Server, but MySQL's / returns a decimal, so the quarter start computes to a fraction. Use DIV, or wrap the division in FLOOR, in the MySQL spelling."}]},"source_url":"https://sqlly.app/sql-snippets/first-and-last-day-of-quarter","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/first-and-last-day-of-week","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Get the first and last day of the week in SQL","description":"Round any date down to its Monday and up to its Sunday for weekly reporting buckets.","body":{"slug":"first-and-last-day-of-week","name":"First and last day of the week","h1":"Get the first and last day of the week in SQL","category":"text","lede":"Weekly reports need every day of a week to share one key: the Monday it starts on.","engine_slug":"postgresql","problem":"date_trunc('week', ...) snaps to Monday, and adding six days gives the Sunday. ISO weeks are Monday-based.","sql":"SELECT\n    date_trunc('week', ordered_at)::date AS week_start,\n    (date_trunc('week', ordered_at) + interval '6 days')::date AS week_end\nFROM orders;","how_it_works":"date_trunc('week', ts) returns midnight of that week's Monday per the ISO definition. Casting to date drops the time, and adding six days yields the Sunday that closes the week. SQL Server's DATEPART(WEEKDAY) and MySQL's DAYOFWEEK number the days differently, and SQL Server's even depends on SET DATEFIRST, so pin the convention in the query rather than trusting session settings.","variants":[{"sql":"SELECT\n    DATEADD(DAY, -(DATEPART(WEEKDAY, d) + @@DATEFIRST + 5) % 7, d) AS week_start,\n    DATEADD(DAY, 6 - (DATEPART(WEEKDAY, d) + @@DATEFIRST + 5) % 7, d) AS week_end\nFROM (SELECT CAST('2026-03-04' AS DATE) AS d) x;"},{"sql":"SELECT\n    d - INTERVAL WEEKDAY(d) DAY AS week_start,\n    d + INTERVAL (6 - WEEKDAY(d)) DAY AS week_end\nFROM (SELECT CURDATE() AS d) x;"}],"see_also":["first-and-last-day-of-month","iso-week-number"],"faqs":[{"question":"Why do SQL Server week formulas involve @@DATEFIRST?","answer":"DATEPART(WEEKDAY) is relative to the DATEFIRST setting (which day counts as day 1). The combination of DATEPART and @@DATEFIRST in one expression cancels that setting out, giving a stable ISO Monday regardless of server configuration."},{"question":"Is there a SQLite spelling for the Monday key?","answer":"Yes: date(d, '-6 days', 'weekday 1') lands on the week's Monday, because 'weekday 1' steps forward to the next Monday and the six-day offset keeps it inside the original week. SQLite has no date_trunc to do it in one call."}]},"source_url":"https://sqlly.app/sql-snippets/first-and-last-day-of-week","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/first-and-last-day-of-year","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Get the first and last day of the year in SQL","description":"Build Jan 1 and Dec 31 of a date's year, leap years included, with one expression per boundary.","body":{"slug":"first-and-last-day-of-year","name":"First and last day of the year","h1":"Get the first and last day of the year in SQL","category":"text","lede":"Yearly rollups need the year window. Both boundaries come from the year number alone.","engine_slug":"postgresql","problem":"make_date builds a date from year, month, day integers, so the year of d gives both boundaries directly.","sql":"SELECT\n    make_date(EXTRACT(YEAR FROM d)::int, 1, 1) AS year_start,\n    make_date(EXTRACT(YEAR FROM d)::int, 12, 31) AS year_end\nFROM (SELECT DATE '2026-03-04' AS d) x;","how_it_works":"EXTRACT(YEAR FROM d) is the only variable; months and days are constants, so Dec 31 is always correct and leap years never enter the picture. The cast to int is required because make_date takes integers, not numerics.","variants":[{"sql":"SELECT\n    DATEFROMPARTS(YEAR(d), 1, 1) AS year_start,\n    DATEFROMPARTS(YEAR(d), 12, 31) AS year_end\nFROM (SELECT CAST('2026-03-04' AS DATE) AS d) x;"},{"sql":"SELECT\n    MAKEDATE(YEAR(d), 1) AS year_start,\n    DATE_SUB(MAKEDATE(YEAR(d) + 1, 1), INTERVAL 1 DAY) AS year_end\nFROM (SELECT CURDATE() AS d) x;"}],"see_also":["first-and-last-day-of-month","first-and-last-day-of-quarter"],"faqs":[{"question":"Do I even need year_end?","answer":"For range filters, prefer the half-open form d >= year_start AND d < next_year_start. On a timestamp column, d <= year_end compares against midnight at the start of Dec 31 and misses everything later that day; the half-open form cannot."}]},"source_url":"https://sqlly.app/sql-snippets/first-and-last-day-of-year","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/first-last-value-in-partition","corpus":"sql-snippets","engine":"all","language":"en","title":"First and last value in a partition","description":"Carry each customer's first and last order amount onto every row with FIRST_VALUE and LAST_VALUE.","body":{"slug":"first-last-value-in-partition","name":"First and last value in a partition","h1":"First and last value in a partition","category":"querying","lede":"Two window functions, one frame each. LAST_VALUE needs the full frame or it lies.","engine_slug":"all","problem":"You want every order row to show the customer's first and most recent order amount, so you can compute change since the first order inline.","sql":"SELECT customer_id, order_date, amount,\n       FIRST_VALUE(amount) OVER (PARTITION BY customer_id\n                                 ORDER BY order_date, id\n                                 ROWS BETWEEN UNBOUNDED PRECEDING\n                                       AND UNBOUNDED FOLLOWING) AS first_order_amount,\n       LAST_VALUE(amount) OVER (PARTITION BY customer_id\n                                ORDER BY order_date, id\n                                ROWS BETWEEN UNBOUNDED PRECEDING\n                                      AND UNBOUNDED FOLLOWING) AS last_order_amount\nFROM orders;","how_it_works":"FIRST_VALUE with an ordered window is straightforward: the first row of the partition. LAST_VALUE is the famous trap, because the default frame stops at the current row, which makes it return the current row's own value; extending the frame to UNBOUNDED FOLLOWING makes it see the whole partition. Both calls repeat the same OVER clause; the variant names it once with a WINDOW clause, which SQL Server accepts from 2022 (compatibility level 160) and Oracle from 21c.","variants":[{"sql":"SELECT customer_id, order_date, amount,\n       FIRST_VALUE(amount) OVER w AS first_order_amount,\n       LAST_VALUE(amount)  OVER w AS last_order_amount\nFROM orders\nWINDOW w AS (PARTITION BY customer_id\n             ORDER BY order_date, id\n             ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING);"}],"see_also":["lag-compare-within-group","latest-row-per-customer"],"faqs":[{"question":"Why does LAST_VALUE return the current row by default?","answer":"Because the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and 'current row' includes its peers. The function is doing what the frame says; extend the frame to UNBOUNDED FOLLOWING and it reports the true last row."},{"question":"Where do NULLs land in the window order?","answer":"SQL Server, MySQL and SQLite treat NULL as the smallest value, so it becomes FIRST_VALUE of an ascending partition; PostgreSQL and Oracle sort NULLs last by default. Add NULLS LAST to the OVER clause, or filter NULLs out, when the winner must be a real value."}]},"source_url":"https://sqlly.app/sql-snippets/first-last-value-in-partition","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/fiscal-year-mapping","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Map a calendar date to a fiscal year in SQL","description":"Assign every date to the fiscal year it belongs to, for fiscal years that start in any month.","body":{"slug":"fiscal-year-mapping","name":"Map a date to a fiscal year","h1":"Map a calendar date to a fiscal year in SQL","category":"text","lede":"Companies run fiscal years that start in July, April or October. Every report needs dates mapped into those years.","engine_slug":"postgresql","problem":"One CASE decides whether the date falls in the first or second half of the fiscal year and labels it accordingly.","sql":"SELECT\n    d,\n    CASE WHEN EXTRACT(MONTH FROM d) >= 7\n         THEN EXTRACT(YEAR FROM d)::int + 1\n         ELSE EXTRACT(YEAR FROM d)::int\n    END AS fiscal_year\nFROM (VALUES (DATE '2026-03-15'), (DATE '2026-08-01')) AS t(d);","how_it_works":"With a fiscal year starting July 1 and labeled by its ending year, July-through-December dates belong to next year's number and the rest to the current one. Change the 7 to your fiscal start month and the label to your convention (starting year or ending year) and the same shape works for any mapping.","variants":[{"sql":"SELECT\n    d,\n    CASE WHEN MONTH(d) >= 7 THEN YEAR(d) + 1 ELSE YEAR(d) END AS fiscal_year\nFROM (VALUES (CAST('2026-03-15' AS DATE)), (CAST('2026-08-01' AS DATE))) AS t(d);"}],"see_also":["first-and-last-day-of-quarter","iso-week-number"],"faqs":[{"question":"Is FY2026 the year that starts or ends in 2026?","answer":"Both conventions exist. Labelling by the ending year is common in the US (the US federal FY2026 runs October 2025 to September 2026); others label by the starting year or write both years, as in the UK's 2026-27 tax year. The query above labels by ending year. State the convention in your reports or the numbers will be a year off for part of your audience."},{"question":"Why do some rows come back with a NULL fiscal year?","answer":"A NULL date satisfies no WHEN branch, so the CASE hands back NULL on all five engines. Filter those rows out if a missing date is bad data, or put an explicit IS NULL branch first to bucket them on purpose."}]},"source_url":"https://sqlly.app/sql-snippets/fiscal-year-mapping","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/foreign-key-value-distribution","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Distribution of foreign-key values","description":"Join the child table to its parent and rank by row count to see skew and spot hot parents.","body":{"slug":"foreign-key-value-distribution","name":"FK distribution","h1":"Distribution of foreign-key values","category":"data-quality","lede":"Group child rows by parent, count them, and order descending: the top of the list is your skew, the tail is your long tail.","engine_slug":"postgresql","problem":"One customer owns most of the orders and you want proof, plus the list of parents with suspiciously many children before a cascade or archive touches them.","sql":"SELECT c.id AS customer_id, c.email,\n       COUNT(o.id) AS order_count\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.id\nGROUP BY c.id, c.email\nORDER BY order_count DESC\nLIMIT 20;","how_it_works":"LEFT JOIN keeps zero-order customers in the census, with COUNT(o.id) returning 0 for them instead of dropping them. Grouping by the parent and ordering by the child count descending ranks the skew; LIMIT trims the head. The tail end of the same query (flip to ASC) shows dormant parents worth archiving.","variants":[{"sql":"SELECT TOP 20 c.id AS customer_id, c.email, COUNT(o.id) AS order_count\nFROM customers c\nLEFT JOIN orders o ON o.customer_id = c.id\nGROUP BY c.id, c.email\nORDER BY order_count DESC;"},{"sql":"SELECT\n  (SELECT COUNT(*) FROM orders WHERE customer_id = (\n     SELECT customer_id FROM orders GROUP BY customer_id ORDER BY COUNT(*) DESC LIMIT 1\n  )) AS top_customer_orders,\n  (SELECT COUNT(*) FROM customers c\n   WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)) AS customers_without_orders;"}],"see_also":["dominant-value-frequency","cascade-impact-preview","find-candidate-keys"],"faqs":[{"question":"Why LEFT JOIN here instead of an inner join?","answer":"With an inner join, parents whose children were all deleted vanish from the report, and those are exactly the rows an archiver needs to see. The LEFT JOIN plus COUNT(child.id) pattern reports them as zero, giving you the full distribution from empty parents to the hottest one."},{"question":"Can I run this against a production primary?","answer":"The count touches every child row, so on PostgreSQL a multi-million-row child table pays a full scan each run. Point the query at a replica, or bound it with a date filter on the child before you schedule it."}]},"source_url":"https://sqlly.app/sql-snippets/foreign-key-value-distribution","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/format-money-string","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Format money and currency values as strings in SQL","description":"Render 1234.5 as '$1,234.50' with the engine's own currency formatting functions.","body":{"slug":"format-money-string","name":"Format money as a string","h1":"Format money and currency values as strings in SQL","category":"text","lede":"Reports and exports need money with a currency symbol and thousands separators, not a bare decimal.","engine_slug":"sql-server","problem":"A bare decimal like 1234.5 reads badly in exports. FORMAT with the C specifier adds the currency symbol and grouping for a locale.","sql":"SELECT FORMAT(total_amount, 'C', 'en-US') AS amount_display\nFROM orders;","how_it_works":"FORMAT uses .NET format strings, so 'C' means currency and the third argument fixes the culture, which decides symbol placement and separators. It is convenient but slow, because each call goes through the .NET runtime; on large result sets format in the application or use CONVERT(varchar, CAST(x AS money), 1), which adds thousands separators without a symbol.","variants":[{"sql":"SELECT to_char(total_amount, 'FML999G999G990D00') AS amount_display\nFROM orders;"},{"sql":"SELECT CONCAT('$', FORMAT(total_amount, 2)) AS amount_display\nFROM orders;"},{"sql":"SELECT TO_CHAR(total_amount, 'FM$999G999G990D00') AS amount_display\nFROM orders;"}],"see_also":["pad-numbers-zeros","replace-multiple-patterns"],"faqs":[{"question":"Why does the PostgreSQL mask start with FM?","answer":"FM (fill mode) suppresses the padding TO_CHAR adds to fill the mask width. Without it, to_char(1234.5, 'L999G999G990D00') returns '$       1,234.50'. L prints the currency symbol of the lc_monetary setting, so the result depends on server configuration; Oracle's mask hardcodes '$' instead."}]},"source_url":"https://sqlly.app/sql-snippets/format-money-string","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/full-outer-join-compare","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Full outer compare of two result sets","description":"FULL OUTER JOIN two result sets on the key and surface rows that exist on only one side.","body":{"slug":"full-outer-join-compare","name":"Compare two result sets fully","h1":"Full outer compare of two result sets","category":"querying","lede":"Rows with NULL on either side are the differences; everything else lines up.","engine_slug":"postgresql","problem":"This month's customer totals should match last month's. You want a single query listing only the customers present on one side but not the other.","sql":"WITH this_month AS (\n  SELECT customer_id, SUM(amount) AS total\n  FROM orders\n  WHERE order_date >= DATE '2026-07-01'\n  GROUP BY customer_id\n),\nlast_month AS (\n  SELECT customer_id, SUM(amount) AS total\n  FROM orders\n  WHERE order_date >= DATE '2026-06-01'\n    AND order_date <  DATE '2026-07-01'\n  GROUP BY customer_id\n)\nSELECT COALESCE(t.customer_id, l.customer_id) AS customer_id,\n       t.total AS this_month_total,\n       l.total AS last_month_total\nFROM this_month t\nFULL OUTER JOIN last_month l ON l.customer_id = t.customer_id\nWHERE t.customer_id IS NULL OR l.customer_id IS NULL\nORDER BY customer_id;","how_it_works":"FULL OUTER JOIN keeps every customer from both sides; rows that matched show both totals and rows that did not show NULL on the missing side. The WHERE keeps only the one-sided rows, which is the difference set in both directions at once. MySQL has no FULL OUTER JOIN, so emulate it with two LEFT JOINs, one from each side, each keeping only its unmatched rows, glued with UNION ALL.","variants":[{"sql":"WITH this_month AS (\n  SELECT customer_id, SUM(amount) AS total\n  FROM orders\n  WHERE order_date >= DATE '2026-07-01'\n  GROUP BY customer_id\n),\nlast_month AS (\n  SELECT customer_id, SUM(amount) AS total\n  FROM orders\n  WHERE order_date >= DATE '2026-06-01'\n    AND order_date <  DATE '2026-07-01'\n  GROUP BY customer_id\n)\nSELECT t.customer_id,\n       t.total AS this_month_total,\n       l.total AS last_month_total\nFROM this_month t\nLEFT JOIN last_month l ON l.customer_id = t.customer_id\nWHERE l.customer_id IS NULL\nUNION ALL\nSELECT l.customer_id, NULL, l.total\nFROM last_month l\nLEFT JOIN this_month t ON t.customer_id = l.customer_id\nWHERE t.customer_id IS NULL\nORDER BY customer_id;"}],"see_also":["except-differences","intersect-common-rows","month-over-month-delta"],"faqs":[{"question":"How do I also catch rows that exist on both sides but differ in value?","answer":"Extend the WHERE: OR (t.customer_id = l.customer_id AND t.total <> l.total). The same query then lists added, removed and changed customers. If totals can be NULL, use t.total IS DISTINCT FROM l.total (PostgreSQL, SQL Server 2022+, SQLite 3.39+) or NOT (t.total <=> l.total) on MySQL."}]},"source_url":"https://sqlly.app/sql-snippets/full-outer-join-compare","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/fuzzy-match-levenshtein","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Fuzzy match strings with Levenshtein distance in SQL","description":"Match 'Jon Smith' to 'John Smyth' by edit distance, and what each engine ships for it (often nothing).","body":{"slug":"fuzzy-match-levenshtein","name":"Fuzzy match with Levenshtein distance","h1":"Fuzzy match strings with Levenshtein distance in SQL","category":"text","lede":"Typos in names defeat exact matching. Edit distance scores how many single-character edits separate two strings.","engine_slug":"postgresql","problem":"The fuzzystrmatch extension provides levenshtein() and levenshtein_less_equal() for tolerant name matching.","sql":"CREATE EXTENSION IF NOT EXISTS fuzzystrmatch;\n\nSELECT a.name AS name_a, b.name AS name_b,\n       levenshtein(lower(a.name), lower(b.name)) AS edit_distance\nFROM contacts a\nJOIN contacts b\n  ON a.id < b.id\n AND levenshtein(lower(a.name), lower(b.name)) <= 2;","how_it_works":"levenshtein returns the number of insertions, deletions and substitutions between two strings; a distance of 2 or less usually means a typo. The self-join pairs every candidate, which is O(n squared), so restrict one side first (same city, same first letter) before the distance check.","variants":[{"sql":"SELECT a.name AS name_a, b.name AS name_b,\n       UTL_MATCH.EDIT_DISTANCE_SIMILARITY(a.name, b.name) AS similarity_pct\nFROM contacts a\nJOIN contacts b ON a.id < b.id\nWHERE UTL_MATCH.EDIT_DISTANCE_SIMILARITY(a.name, b.name) >= 80;"},{"sql":"SELECT a.name, b.name, DIFFERENCE(a.name, b.name) AS soundex_score\nFROM contacts a\nJOIN contacts b ON a.id < b.id\nWHERE DIFFERENCE(a.name, b.name) >= 3;"}],"see_also":["compare-strings-ignoring-case-accents","count-substring-occurrences"],"faqs":[{"question":"MySQL has no Levenshtein either?","answer":"Right: stock MySQL ships no edit-distance function, and stock SQLite does not either. Options are a stored function, a UDF, or computing candidates in application code. SQL Server 2025 adds EDIT_DISTANCE and EDIT_DISTANCE_SIMILARITY as preview features (enable with ALTER DATABASE SCOPED CONFIGURATION SET PREVIEW_FEATURES = ON); older versions only have the coarse phonetic SOUNDEX and DIFFERENCE."}]},"source_url":"https://sqlly.app/sql-snippets/fuzzy-match-levenshtein","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/generate-drop-table-statements","corpus":"sql-snippets","engine":"mysql","language":"en","title":"Generate DROP TABLE statements","description":"Build the DROP script for all tables in a schema from the metadata, with foreign-key ordering handled by CASCADE or by turning FK checks off.","body":{"slug":"generate-drop-table-statements","name":"Generate DROP statements","h1":"Generate DROP TABLE statements","category":"schema","lede":"Dropping thirty tables by hand invites typos and missed ones. Generate the statements from the metadata, review the script, then run it.","engine_slug":"mysql","problem":"A scratch schema holds dozens of tables that all have to go, and the removal should be scripted from the metadata rather than typed out.","sql":"SELECT CONCAT('DROP TABLE IF EXISTS `', table_schema, '`.`', table_name, '`;') AS drop_statement\nFROM information_schema.tables\nWHERE table_schema = 'mydb'\n  AND table_type = 'BASE TABLE'\nORDER BY table_name;","how_it_works":"The query turns each table row into a complete DROP statement for you to review and then run. IF EXISTS keeps the script re-runnable, and the backtick quoting survives table names that are reserved words (a name containing a backtick would still break it). Foreign keys decide whether it works: on MySQL, run SET FOREIGN_KEY_CHECKS = 0 in the same session first, or drop children before parents. SQL Server refuses to drop a table that a foreign key still references, so drop those constraints first or order the list with the table-dependency-order recipe.","variants":[{"sql":"SELECT string_agg(\n    format('DROP TABLE IF EXISTS %I.%I CASCADE;', table_schema, table_name),\n    E'\\n' ORDER BY table_name)\nFROM information_schema.tables\nWHERE table_schema = 'public' AND table_type = 'BASE TABLE';\n-- one statement that drops in any order thanks to CASCADE"},{"sql":"SELECT 'DROP TABLE IF EXISTS ' + QUOTENAME(SCHEMA_NAME(schema_id))\n       + '.' + QUOTENAME(name) + ';'\nFROM sys.tables\nORDER BY name;"},{"sql":"SELECT 'DROP TABLE IF EXISTS \"' || replace(name, '\"', '\"\"') || '\";'\nFROM sqlite_master\nWHERE type = 'table' AND name NOT LIKE 'sqlite_%';"}],"see_also":["truncate-all-tables-safe-order","table-dependency-order","create-empty-like-table"],"faqs":[{"question":"Is DROP ... CASCADE dangerous here?","answer":"It drops more than the table. On PostgreSQL, CASCADE also drops views that read the table and the foreign key constraints on other tables that point at it (the other tables survive). That is what makes the script order-independent. Run it inside BEGIN and read the NOTICE lines listing what else it dropped before you COMMIT."},{"question":"Why can the DROP still fail after the script is generated?","answer":"MySQL 8 refuses to drop a table that a foreign key still points at (error 3730) unless the children go first or the session runs SET FOREIGN_KEY_CHECKS = 0, and that setting scopes to your session only. SQL Server behaves the same way and has no such switch, so its script must order the drops."}]},"source_url":"https://sqlly.app/sql-snippets/generate-drop-table-statements","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/grant-select-all-tables","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Grant SELECT on all tables","description":"Read access for an analyst across a whole schema in two statements, plus the generated per-table script for engines that lack schema-wide grants.","body":{"slug":"grant-select-all-tables","name":"Grant SELECT on all tables","h1":"Grant SELECT on all tables","category":"schema","lede":"Granting SELECT table by table is slow and misses tables added later. Each engine has a schema- or database-wide form; the per-table script is the fallback.","engine_slug":"postgresql","problem":"A new analyst needs read access across a whole schema, and granting table by table takes forever and goes stale with the next migration.","sql":"GRANT SELECT ON ALL TABLES IN SCHEMA public TO analyst;\n-- plus usage of the schema itself, or the grant above is not enough\nGRANT USAGE ON SCHEMA public TO analyst;","how_it_works":"The table grant alone is not enough: without USAGE on the schema, every query fails with permission denied for schema public. ON ALL TABLES also covers views and materialized views, but not sequences; reading a serial column needs no sequence privilege, calling nextval() does. The grant applies only to tables that exist when it runs, so pair it with default privileges for future ones. Re-running it is harmless.","variants":[{"sql":"SELECT format('GRANT SELECT ON %I.%I TO analyst;', table_schema, table_name)\nFROM information_schema.tables\nWHERE table_schema = 'public' AND table_type = 'BASE TABLE';\n-- run the output; useful when only some tables should be granted"},{"sql":"GRANT SELECT ON mydb.* TO 'analyst'@'%';\n-- database-wide, so it also covers tables created later;\n-- per table: GRANT SELECT ON mydb.users TO 'analyst'@'%';\n-- no FLUSH PRIVILEGES needed after GRANT"},{"sql":"GRANT SELECT ON SCHEMA::dbo TO analyst;\n-- covers every current and future table and view in dbo;\n-- for a single table instead:\n-- GRANT SELECT ON OBJECT::dbo.Users TO analyst;"}],"see_also":["default-privileges-future-tables","list-user-privileges","revoke-all-privileges"],"faqs":[{"question":"Why can my analyst see the tables but get errors on SELECT?","answer":"On PostgreSQL, 'permission denied for schema' means USAGE is missing, and 'permission denied for table' on a table created after the GRANT means it needs a fresh grant or default privileges. If queries succeed but return no rows, the table has row-level security enabled and no policy admits the analyst. Also check that the grant went to the schema the queries actually resolve to through search_path."},{"question":"Does the schema-wide grant include views?","answer":"Yes on each engine here: SQL Server's SELECT ON SCHEMA::dbo covers tables and views in that schema, and PostgreSQL's ON ALL TABLES covers views and materialized views despite the name. MySQL's ON mydb.* covers everything in the database, views included."}]},"source_url":"https://sqlly.app/sql-snippets/grant-select-all-tables","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/hash-values-md5-sha","corpus":"sql-snippets","engine":"mysql","language":"en","title":"Compute MD5 or SHA-256 hashes of values in SQL","description":"Produce hex digests like dedupe keys or fingerprint tokens with each engine's hash functions.","body":{"slug":"hash-values-md5-sha","name":"Hash values (MD5 / SHA-256)","h1":"Compute MD5 or SHA-256 hashes of values in SQL","category":"text","lede":"You need a stable fingerprint of an email or a row payload for dedupe keys and change detection.","engine_slug":"mysql","problem":"A hash gives you a short, stable, non-reversible fingerprint. MySQL's MD5 and SHA2 are the simplest one-call options.","sql":"SELECT\n    MD5(email) AS email_md5,\n    SHA2(CONCAT(customer_id, ':', email), 256) AS row_sha256\nFROM users;","how_it_works":"MD5 returns a 32-character lowercase hex digest; SHA2(value, 256) returns 64 characters. Concatenating the primary key with the value fingerprints the row, and the separator stops 'ab'+'c' colliding with 'a'+'bc'. MD5 is fine for dedupe keys but must not be treated as security. Hashes only match across engines when the input bytes match: on SQL Server, HASHBYTES of an NVARCHAR value hashes UTF-16 bytes and gives a different digest from the same text as VARCHAR.","variants":[{"sql":"SELECT\n    MD5(email) AS email_md5,\n    encode(sha256(convert_to(CONCAT(customer_id, ':', email), 'UTF8')), 'hex') AS row_sha256\nFROM users;"},{"sql":"SELECT\n    LOWER(CONVERT(VARCHAR(32), HASHBYTES('MD5', email), 2)) AS email_md5,\n    LOWER(CONVERT(VARCHAR(64), HASHBYTES('SHA2_256', CONCAT(customer_id, ':', email)), 2)) AS row_sha256\nFROM users;"},{"sql":"SELECT\n    LOWER(RAWTOHEX(STANDARD_HASH(email, 'MD5'))) AS email_md5,\n    LOWER(RAWTOHEX(STANDARD_HASH(customer_id || ':' || email, 'SHA256'))) AS row_sha256\nFROM users;"}],"see_also":["mask-card-numbers"],"faqs":[{"question":"SQLite has no hash functions?","answer":"The SQLite library itself has none. The sqlite3 command-line shell bundles a sha3() function and the sha1/sha3 extensions ship in the source tree, but an application linking plain SQLite will not have them; compute the hash in application code or store it in a column."}]},"source_url":"https://sqlly.app/sql-snippets/hash-values-md5-sha","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/high-logical-reads-queries","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Find queries with high logical reads in SQL Server","description":"Ranks the plan cache by total logical reads: the queries touching the most pages, which is where missing indexes and bad joins show up first.","body":{"slug":"high-logical-reads-queries","name":"High logical reads","h1":"Find queries with high logical reads in SQL Server","category":"monitoring","lede":"Logical reads, pages touched in memory, are the most stable cost measure SQL Server keeps per query. This ranks the plan cache by them.","engine_slug":"sql-server","problem":"A logical read is one 8 KB page read from the buffer pool. If the page is not in memory, SQL Server first does a physical read from disk, but the logical read is counted either way, so the number does not depend on what happened to be cached. That makes it a stable measure of how much data a query touches. Statements at the top of sys.dm_exec_query_stats by total_logical_reads are usually scanning where they could seek, doing key lookups row by row, or running a nested loop over far more rows than estimated.","sql":"SELECT TOP 20\n    qs.execution_count,\n    qs.total_logical_reads,\n    CAST(qs.total_logical_reads * 8 / 1024.0 AS DECIMAL(18,1)) AS total_read_mb,\n    CAST(qs.total_logical_reads / NULLIF(qs.execution_count, 0) * 8 / 1024.0 AS DECIMAL(18,2)) AS read_mb_per_call,\n    CAST(qs.total_elapsed_time / 1000.0 / NULLIF(qs.execution_count, 0) AS DECIMAL(18,2)) AS mean_ms,\n    LEFT(SUBSTRING(st.text, qs.statement_start_offset / 2 + 1,\n         (CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(st.text)\n               ELSE qs.statement_end_offset END - qs.statement_start_offset) / 2 + 1), 140) AS statement_text\nFROM sys.dm_exec_query_stats qs\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st\nORDER BY qs.total_logical_reads DESC;","how_it_works":"sys.dm_exec_query_stats has one row per statement per cached plan, with totals accumulated since SQL Server cached the plan. sql_handle points at the whole batch or procedure text, so the SUBSTRING with statement_start_offset and statement_end_offset (byte offsets into Unicode text, hence the division by 2) cuts out the one statement the row describes. total_logical_reads times 8 KB is the data volume the query touches, counting a page again each time the engine reads it back. Dividing by execution_count separates one huge report from a hot loop doing a little too much per call. A point lookup that reads more than a few MB per call is almost always a scan that an index or a rewrite can remove. The query needs VIEW SERVER STATE, or VIEW SERVER PERFORMANCE STATE on SQL Server 2022 and later.","variants":[{"sql":"SELECT TOP 20\n    qs.execution_count,\n    qs.total_physical_reads,\n    qs.total_logical_reads,\n    LEFT(SUBSTRING(st.text, qs.statement_start_offset / 2 + 1,\n         (CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(st.text)\n               ELSE qs.statement_end_offset END - qs.statement_start_offset) / 2 + 1), 140) AS statement_text\nFROM sys.dm_exec_query_stats qs\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st\nORDER BY qs.total_physical_reads DESC;"}],"see_also":["top-queries-by-total-time","non-sargable-detector","buffer-cache-contents"],"faqs":[{"question":"Why logical reads instead of duration?","answer":"Duration depends on cache warmth, blocking and concurrent load, so the same query ranks differently at 9am and 2am. Logical reads for the same plan and the same data are nearly identical every run, which makes them the number to compare before and after an index or rewrite. SET STATISTICS IO ON shows them per table for a single run."},{"question":"Do plan cache stats survive a restart?","answer":"No. The whole cache is emptied on restart and individual plans evict under memory pressure. For long-term tracking, persist snapshots or use Query Store, which keeps per-query runtime stats in the database itself."}]},"source_url":"https://sqlly.app/sql-snippets/high-logical-reads-queries","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/high-read-tables","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find the most-read tables in PostgreSQL","description":"Ranks tables by total rows read via both index and sequential access, plus write volume, so you can target caching and tuning at the hot ones.","body":{"slug":"high-read-tables","name":"High-read tables","h1":"Find the most-read tables in PostgreSQL","category":"indexes","lede":"Find out which tables actually dominate read traffic before you spend effort optimizing anywhere else.","engine_slug":"postgresql","problem":"Tuning effort should follow traffic. pg_stat_user_tables exposes both read paths: seq_tup_read for full scans and idx_tup_fetch for rows retrieved through indexes. Summing them gives total rows read per table; the write counters (n_tup_ins, n_tup_upd, n_tup_del) sit beside them so a table that is read-heavy AND write-heavy can be flagged for special care.","sql":"SELECT schemaname, relname AS table_name,\n       seq_tup_read + COALESCE(idx_tup_fetch, 0) AS total_rows_read,\n       seq_tup_read, idx_tup_fetch,\n       n_tup_ins, n_tup_upd, n_tup_del,\n       n_tup_hot_upd,\n       pg_size_pretty(pg_total_relation_size(relid)) AS total_size\nFROM pg_stat_user_tables\nORDER BY total_rows_read DESC\nLIMIT 25;","how_it_works":"The counters in pg_stat_user_tables accumulate since the last stats reset. idx_tup_fetch counts live rows fetched by index scans and seq_tup_read counts live rows returned by sequential scans. idx_tup_fetch is NULL for a table with no indexes, so COALESCE keeps those tables from sorting to the top with a NULL total. n_tup_hot_upd matters because a HOT (heap-only tuple) update writes no new index entries: when it is a small fraction of n_tup_upd on a busy table, every update is also writing to every index on it.","variants":[{"sql":"SELECT TOP 25\n    OBJECT_SCHEMA_NAME(ios.object_id) AS schema_name,\n    OBJECT_NAME(ios.object_id) AS table_name,\n    SUM(ios.range_scan_count) AS range_scans,\n    SUM(ios.singleton_lookup_count) AS singleton_lookups,\n    SUM(ios.leaf_insert_count + ios.leaf_update_count + ios.leaf_delete_count) AS leaf_writes\nFROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) ios\nWHERE OBJECTPROPERTY(ios.object_id, 'IsUserTable') = 1\nGROUP BY ios.object_id\nORDER BY SUM(ios.range_scan_count + ios.singleton_lookup_count) DESC;"}],"see_also":["table-scan-detector","cache-hit-ratio","top-queries-by-total-time"],"faqs":[{"question":"What is a good HOT update ratio?","answer":"It depends on the table. A HOT update needs two things: the update changes no indexed column, and the new row version fits on the same heap page. If the hot path updates an indexed column, such as an indexed updated_at, HOT is impossible for it. If no indexed column changes but the ratio is still low, the pages are full; a lower fillfactor on the table (for example 90) leaves room for new versions."},{"question":"Do these counters survive restarts?","answer":"A clean shutdown and restart keeps them, because the server writes them to disk at shutdown. Crash recovery, failover to a standby and pg_stat_reset() clear them. Copy them into a table on a schedule if you want trend lines."}]},"source_url":"https://sqlly.app/sql-snippets/high-read-tables","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/hourly-buckets","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Group rows into hourly buckets","description":"Truncate order timestamps to the hour and count or sum per bucket for time-of-day analysis.","body":{"slug":"hourly-buckets","name":"Hourly buckets","h1":"Group rows into hourly buckets","category":"querying","lede":"DATE_TRUNC rounds every timestamp down to the hour; GROUP BY the truncated value.","engine_slug":"postgresql","problem":"You want orders per hour of the day to staff your support desk properly.","sql":"SELECT DATE_TRUNC('hour', order_date) AS hour_bucket,\n       COUNT(*) AS orders,\n       SUM(amount) AS revenue\nFROM orders\nGROUP BY 1\nORDER BY 1;","how_it_works":"DATE_TRUNC('hour', ...) zeroes out the minutes and seconds, so every timestamp in an hour maps to the same value and GROUP BY counts it once. GROUP BY 1 refers to the first output column, avoiding a repeated expression. Each engine has its own truncation function: MySQL uses DATE_FORMAT, SQL Server 2022+ DATETRUNC(hour, ...) (older versions the DATEADD/DATEDIFF trick), SQLite strftime, Oracle TRUNC(order_date, 'HH24').","variants":[{"sql":"SELECT DATE_FORMAT(order_date, '%Y-%m-%d %H:00:00') AS hour_bucket,\n       COUNT(*) AS orders\nFROM orders\nGROUP BY 1\nORDER BY 1;"},{"sql":"SELECT DATEADD(hour, DATEDIFF(hour, 0, order_date), 0) AS hour_bucket,\n       COUNT(*) AS orders\nFROM orders\nGROUP BY DATEADD(hour, DATEDIFF(hour, 0, order_date), 0)\nORDER BY hour_bucket;"},{"sql":"SELECT strftime('%Y-%m-%d %H:00:00', order_date) AS hour_bucket,\n       COUNT(*) AS orders\nFROM orders\nGROUP BY 1\nORDER BY 1;"}],"see_also":["fill-gaps-calendar-spine","weekly-buckets-ending-sunday"],"faqs":[{"question":"Can I bucket by time-of-day across all days?","answer":"Yes: group by the hour part only, such as EXTRACT(hour FROM order_date) in PostgreSQL or DATEPART(hour, order_date) in SQL Server, to get one row per hour of the day summed across every date."}]},"source_url":"https://sqlly.app/sql-snippets/hourly-buckets","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/id-remap-preview","corpus":"sql-snippets","engine":"all","language":"en","title":"Preview an id remap before running it","description":"Join a staging old-to-new id map against the child table and list every foreign key the remap would rewrite.","body":{"slug":"id-remap-preview","name":"ID remap preview","h1":"Preview an id remap before running it","category":"data-quality","lede":"Join the mapping table to the child's foreign key; the matched rows are exactly the UPDATE's targets, and unmatched map entries are remaps that would do nothing.","engine_slug":"all","problem":"Merging two customer databases requires renumbering ids: a mapping table old_order_id -> new_order_id exists, and you want to verify what it touches before the UPDATE runs, including map rows that point at children no longer present.","sql":"SELECT oi.id AS order_item_id,\n       oi.order_id AS current_order_id,\n       m.new_order_id AS will_become\nFROM order_items oi\nJOIN order_id_map m ON m.old_order_id = oi.order_id\nORDER BY oi.order_id, oi.id;","how_it_works":"The join between the child table and the mapping table is the UPDATE's WHERE clause in preview form: every matched row is one the remap would rewrite, and the two value columns show the before and after id. Rows in the map that match nothing can be listed with a LEFT JOIN from the map side. They are either stale map entries or children that were already cleaned up.","variants":[{"sql":"SELECT m.old_order_id, m.new_order_id\nFROM order_id_map m\nWHERE NOT EXISTS (\n  SELECT 1 FROM order_items oi WHERE oi.order_id = m.old_order_id\n);"},{"sql":"SELECT m.old_order_id, m.new_order_id, COUNT(*) AS conflicting_rows\nFROM order_id_map m\nJOIN order_items oi ON oi.order_id = m.new_order_id\nGROUP BY m.old_order_id, m.new_order_id\nORDER BY conflicting_rows DESC;"}],"see_also":["migration-diff-preview","re-parent-children-merge-duplicates","cascade-impact-preview"],"faqs":[{"question":"Why preview instead of just running the UPDATE?","answer":"Because a wrong id remap fails silently: as long as the wrong target id exists in orders, the foreign key is satisfied and the line simply belongs to someone else's order. Only a target that does not exist, or a unique constraint on the child, makes the UPDATE fail. The preview shows the exact row set and the before/after pairs; check them, then run the UPDATE in a transaction and compare its row count with the preview."}]},"source_url":"https://sqlly.app/sql-snippets/id-remap-preview","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/idle-in-transaction","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find idle-in-transaction sessions in PostgreSQL","description":"Lists sessions holding an open transaction while executing nothing, with how long they have been idle and what they last ran.","body":{"slug":"idle-in-transaction","name":"Idle in transaction","h1":"Find idle-in-transaction sessions in PostgreSQL","category":"monitoring","lede":"A session idle in transaction is doing nothing and still holding its locks and its snapshot. Here is how to find them.","engine_slug":"postgresql","problem":"A session in state idle in transaction has begun a transaction and issued no statement since state_change. Typically it is an application that opened a transaction, did part of its work, and then paused (waiting on a user, a webhook, a crashed worker). It holds every lock it took, pins the vacuum horizon with its snapshot, and can silently wedge other sessions behind lock queues.","sql":"SELECT pid, usename, datname, application_name, client_addr,\n       now() - xact_start AS xact_age,\n       now() - state_change AS idle_for,\n       LEFT(query, 120) AS last_query,\n       backend_xid IS NOT NULL AS has_write_transaction\nFROM pg_stat_activity\nWHERE state = 'idle in transaction'\nORDER BY state_change\nLIMIT 25;","how_it_works":"state = 'idle in transaction' isolates sessions between statements inside an open transaction; idle in transaction (aborted) means an error occurred and the transaction still awaits a rollback. Ordering by state_change puts the longest-idle first. backend_xid is assigned only when a transaction first writes, so has_write_transaction = true means it holds row locks on what it changed and terminating it rolls that work back. A false value means a read-only transaction, which still holds a snapshot and any table locks its SELECTs took. The standing fix is idle_in_transaction_session_timeout, which ends these sessions automatically.","variants":[{"sql":"SELECT pid, usename, now() - state_change AS idle_for,\n       pg_terminate_backend(pid) AS terminated\nFROM pg_stat_activity\nWHERE state = 'idle in transaction'\n  AND now() - state_change > interval '30 minutes';"}],"see_also":["long-transactions","terminate-backend","blocking-queries"],"faqs":[{"question":"Is it safe to kill idle-in-transaction sessions?","answer":"Usually. Terminating rolls back whatever the transaction changed and not yet committed, which is work the application believed was in progress. The application gets a connection error on its next statement and has to handle it. That is usually the better failure: an error in one request instead of a stuck transaction blocking everyone else."},{"question":"What timeout value should I set?","answer":"Start generous, such as 5 to 15 minutes, well above any legitimate gap in your application's transactions, and tighten it once you know the real shapes. Set it per role (ALTER ROLE app SET idle_in_transaction_session_timeout = '10min') so the DBA role used for manual work in psql, where a person typing inside BEGIN is normal, can keep a longer limit."}]},"source_url":"https://sqlly.app/sql-snippets/idle-in-transaction","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/impossible-dates","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Validate impossible dates","description":"Catch future dates, pre-epoch junk, and impossible orderings such as shipping before ordering.","body":{"slug":"impossible-dates","name":"Impossible dates","h1":"Validate impossible dates","category":"data-quality","lede":"Combine range checks and ordering rules to find date values that cannot be true.","engine_slug":"postgresql","problem":"Date bugs arrive as future order dates, 1970-style zero values from broken imports, and shipments timestamped before the order itself. Each is a small predicate away from detection.","sql":"SELECT id, order_date, shipped_date, status\nFROM orders\nWHERE order_date > CURRENT_DATE\n   OR order_date < DATE '1900-01-01'\n   OR shipped_date < order_date;","how_it_works":"Three predicates cover the classic defects: dates in the future, dates before the system could plausibly have data, and logical impossibilities like shipped_date preceding order_date. Each row returned breaks at least one rule; the first variant labels which. DATE '1900-01-01' is the standard date literal, which MySQL and Oracle also accept. SQL Server and SQLite reject it, so the second variant uses a plain string there. Do not reach for CAST('1900-01-01' AS DATE) to stay portable: Oracle parses it with NLS_DATE_FORMAT and fails, and SQLite turns it into the integer 1900, so the comparison is silently never true. If your bad imports used 1970-01-01 or 0001-01-01 as a placeholder, raise the floor to whatever date your data cannot predate.","variants":[{"sql":"SELECT o.id,\n       CASE WHEN o.order_date > CURRENT_DATE THEN 'future order date' END AS defect_a,\n       CASE WHEN o.order_date < DATE '1900-01-01' THEN 'implausibly old date' END AS defect_b,\n       CASE WHEN o.shipped_date < o.order_date THEN 'shipped before ordered' END AS defect_c\nFROM orders o\nWHERE o.order_date > CURRENT_DATE\n   OR o.order_date < DATE '1900-01-01'\n   OR o.shipped_date < o.order_date;"},{"sql":"SELECT id, order_date, shipped_date\nFROM orders\nWHERE order_date IS NULL\n   OR order_date > CURRENT_DATE  -- CURRENT_DATE needs SQL Server 2025; 2022 and older: CAST(GETDATE() AS date)\n   OR order_date < '1900-01-01'\n   OR shipped_date < order_date;"}],"see_also":["rows-violating-business-rule","check-constraint-violation-preview"],"faqs":[{"question":"Does a DATE column even need range validation?","answer":"The type rules out 'February 30th' on most engines, but not business impossibilities: future events, placeholder dates from bad imports and reversed orderings all fit in a legal DATE. SQLite has no date type at all, so there a column can even hold '2026-02-30' or 'n/a'; add date(order_date) IS NOT order_date to the WHERE, which catches both unparseable text and impossible days (SQLite rolls '2026-02-30' over to 2026-03-02). Once the table is clean, the floor and ordering rules can become CHECK constraints; the future-date rule cannot everywhere, because Oracle rejects CURRENT_DATE in a CHECK (ORA-02436)."},{"question":"If I turn these rules into CHECK constraints, does every engine enforce them?","answer":"No: MySQL parsed but ignored CHECK bodies before 8.0.16, and Oracle refuses CURRENT_DATE inside a CHECK outright (ORA-02436); PostgreSQL, SQL Server and SQLite enforce them. Clean the table with this query first, then add only the constraints your engines actually honor."}]},"source_url":"https://sqlly.app/sql-snippets/impossible-dates","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/index-bloat-estimate","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Estimate index bloat in PostgreSQL","description":"Uses pgstatindex to read the real leaf-page density of a B-tree index, lists the big busy indexes worth checking, and rebuilds with REINDEX CONCURRENTLY.","body":{"slug":"index-bloat-estimate","name":"Index bloat estimate","h1":"Estimate index bloat in PostgreSQL","category":"indexes","lede":"A bloated index wastes cache and disk without any error to tell you. pgstatindex reads the actual leaf-page fill so you can decide which indexes need a rebuild.","engine_slug":"postgresql","problem":"B-tree indexes bloat after heavy update and delete activity: page splits and removed entries leave leaf pages partly empty, and a PostgreSQL B-tree gives a page back only once it is completely empty; half-full pages stay half full. The index ends up larger than its live entries need. pgstatindex, from the pgstattuple extension, reads every page of one B-tree index and reports avg_leaf_density. A freshly built index sits near 90 percent (the default fillfactor); 50 percent means half of every leaf page is empty.","sql":"CREATE EXTENSION IF NOT EXISTS pgstattuple;\n\nSELECT pg_size_pretty(index_size) AS index_size,\n       leaf_pages, empty_pages, deleted_pages,\n       avg_leaf_density, leaf_fragmentation\nFROM pgstatindex('public.orders_created_at_idx');","how_it_works":"pgstatindex reads the whole index, so on a 50 GB index it does 50 GB of I/O; run it on candidates, not on everything. avg_leaf_density is the average fill of leaf pages, and a value well below 90 percent means the index would shrink if rebuilt, roughly in proportion (an index at 45 percent comes back at about half the size). leaf_fragmentation is the share of leaf pages out of physical order, which matters for range scans on spinning disks and much less on SSDs. The workflow: list the largest indexes that are actually used (the variant), check the suspicious ones, then rebuild the genuinely bloated ones with REINDEX INDEX CONCURRENTLY. CREATE EXTENSION needs a role allowed to create extensions in the database; calling pgstatindex needs superuser or membership in pg_stat_scan_tables.","variants":[{"sql":"SELECT s.schemaname || '.' || s.indexrelname AS index_name,\n       pg_size_pretty(pg_relation_size(s.indexrelid)) AS size, s.idx_scan\nFROM pg_stat_user_indexes s\nWHERE s.idx_scan > 0\n  AND pg_relation_size(s.indexrelid) > 1024 * 1024 * 1024\nORDER BY pg_relation_size(s.indexrelid) DESC\nLIMIT 20;"},{"sql":"REINDEX INDEX CONCURRENTLY public.orders_created_at_idx;"}],"see_also":["largest-indexes","unused-indexes","table-index-sizes-topn"],"faqs":[{"question":"What causes bloat besides deletes?","answer":"Page splits from random-order inserts (random UUID keys), updates that change indexed columns (each one adds a new index entry and leaves a dead one), and long-running transactions, which stop vacuum from removing dead index entries until they finish. All three show up as a falling avg_leaf_density."},{"question":"Is REINDEX CONCURRENTLY safe to run in production?","answer":"Yes, with three costs to plan for. It builds a new copy without blocking reads or writes and then swaps it in, so it needs free disk for a second copy of the index. It takes longer than a plain REINDEX because it scans the table twice and waits for running transactions. If it fails, it leaves an invalid index with a _ccnew suffix that you should drop."}]},"source_url":"https://sqlly.app/sql-snippets/index-bloat-estimate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/index-usage-ratio-per-table","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Compute index usage ratio per table in PostgreSQL","description":"Shows for each table what percentage of accesses went through an index versus a full scan, to catch tables drifting toward unindexed access.","body":{"slug":"index-usage-ratio-per-table","name":"Index vs scan ratio","h1":"Compute index usage ratio per table in PostgreSQL","category":"indexes","lede":"One number per table: what share of reads used an index. Low ratios on big tables are your next index project.","engine_slug":"postgresql","problem":"A table-level index percentage makes drift visible. If a large table served 90 percent of reads through indexes last month and only 60 percent this month, new queries or new data distribution are pushing work into full scans. The absolute access counts sit next to the ratio so tiny tables do not produce misleading percentages.","sql":"SELECT relname AS table_name,\n       seq_scan, idx_scan,\n       seq_tup_read, idx_tup_fetch,\n       ROUND(100.0 * COALESCE(idx_scan, 0) / NULLIF(COALESCE(idx_scan, 0) + seq_scan, 0), 1) AS index_pct\nFROM pg_stat_user_tables\nWHERE COALESCE(idx_scan, 0) + seq_scan > 100\nORDER BY COALESCE(idx_scan, 0) + seq_scan DESC;","how_it_works":"The ratio divides idx_scan by all scans (index plus sequential) recorded in pg_stat_user_tables. idx_scan is NULL on a table with no indexes at all, and COALESCE turns that into 0 so those tables show 0 percent instead of disappearing from the list. The WHERE clause drops tables with too few scans for a percentage to mean anything. Read the ratio next to the row counts: a table at 99 percent index scans can still spend most of its time in the 1 percent if each of those sequential scans reads millions of rows.","variants":[{"sql":"SELECT relname AS table_name,\n       seq_scan, idx_scan,\n       ROUND(100.0 * COALESCE(idx_scan, 0) / NULLIF(COALESCE(idx_scan, 0) + seq_scan, 0), 1) AS index_pct,\n       pg_size_pretty(pg_relation_size(relid)) AS table_size\nFROM pg_stat_user_tables\nWHERE COALESCE(idx_scan, 0) + seq_scan > 100\n  AND pg_relation_size(relid) > 100 * 1024 * 1024\n  AND COALESCE(idx_scan, 0) < seq_scan\nORDER BY pg_relation_size(relid) DESC;"}],"see_also":["table-scan-detector","high-read-tables","statistics-staleness"],"faqs":[{"question":"What ratio should a big OLTP table have?","answer":"A large table serving point lookups usually sits well above 95 percent. Tables whose queries read most of their rows (reporting tables, ETL staging) will scan and should. Compare each table against its own history rather than a universal target; a drop from 99 to 80 percent after a release is the signal."},{"question":"The planner picks seq scans even though an index exists. Why?","answer":"Often the planner is right: when a query matches a large fraction of the rows, one sequential pass is cheaper than many random index probes. It can also be stale statistics (run ANALYZE and check again), a predicate that wraps the column in a function, or a type mismatch between the column and the parameter. EXPLAIN (ANALYZE, BUFFERS) on the query shows the estimated versus actual row counts, which tells you which case it is."}]},"source_url":"https://sqlly.app/sql-snippets/index-usage-ratio-per-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/intersect-common-rows","corpus":"sql-snippets","engine":"all","language":"en","title":"Rows common to two queries (INTERSECT)","description":"Find the values both result sets share with INTERSECT, which deduplicates automatically.","body":{"slug":"intersect-common-rows","name":"Rows common to two queries","h1":"Rows common to two queries (INTERSECT)","category":"querying","lede":"Two queries, one INTERSECT, and the overlap comes out deduplicated without a self-join.","engine_slug":"all","problem":"You want the customers who placed at least one order over 500 dollars and also had at least one order returned. Two conditions on different rows, two queries, one overlap.","sql":"SELECT customer_id\nFROM orders\nWHERE amount > 500\nINTERSECT\nSELECT customer_id\nFROM orders\nWHERE status = 'returned'\nORDER BY customer_id;","how_it_works":"INTERSECT returns the customer ids produced by both branches, deduplicated, so each id appears once no matter how many matching orders it has. The two queries must return the same number of columns with compatible types. INTERSECT runs on all five engines (MySQL only from 8.0.31); older MySQL can emulate it with the self-join plus DISTINCT below.","variants":[{"sql":"SELECT DISTINCT a.customer_id\nFROM orders a\nJOIN orders b ON b.customer_id = a.customer_id\nWHERE a.amount > 500\n  AND b.status = 'returned';"}],"see_also":["except-differences","full-outer-join-compare","deduplicate-query-output"],"faqs":[{"question":"Does INTERSECT keep duplicates?","answer":"No. It is a set operator: duplicates are removed from both inputs and the result. INTERSECT ALL keeps multiplicity on PostgreSQL, MySQL 8.0.31+ and Oracle 21c+. SQL Server and SQLite reject INTERSECT ALL, so use a join there."},{"question":"Does every engine ship INTERSECT?","answer":"No: MySQL gained it at 8.0.31, so older MySQL needs the INNER JOIN emulation; PostgreSQL, SQL Server, SQLite and Oracle have supported it for years. The join on the key with DISTINCT returns the same deduplicated set."}]},"source_url":"https://sqlly.app/sql-snippets/intersect-common-rows","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/iso-week-number","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Get the ISO week number of a date in SQL","description":"Number the weeks of the year per ISO 8601 (weeks start Monday; week 1 holds the first Thursday).","body":{"slug":"iso-week-number","name":"ISO week number","h1":"Get the ISO week number of a date in SQL","category":"text","lede":"Weekly KPIs need week numbers, and the wrong week definition silently splits or merges weeks around New Year.","engine_slug":"sql-server","problem":"DATEPART(ISO_WEEK, d) implements ISO 8601 week numbering, independent of DATEFIRST.","sql":"SELECT DATEPART(ISO_WEEK, d) AS iso_week,\n       YEAR(DATEADD(DAY, 26 - DATEPART(ISO_WEEK, d), d)) AS iso_year\nFROM (SELECT CAST('2027-01-01' AS DATE) AS d) x;","how_it_works":"ISO_WEEK numbers weeks per ISO 8601: weeks begin on Monday and week 1 is the week containing the year's first Thursday. Plain DATEPART(WEEK) instead depends on DATEFIRST and can disagree. SQL Server has no ISO-year function, and YEAR(d) is wrong around New Year: 2027-01-01 is in ISO week 53 of 2026, and 2024-12-30 in week 1 of 2025. Shifting the date by 26 minus the week number moves it into the middle of its ISO year, so YEAR() of the shifted date is the ISO year.","variants":[{"sql":"SELECT EXTRACT(WEEK FROM d) AS iso_week,\n       EXTRACT(ISOYEAR FROM d) AS iso_year\nFROM (SELECT DATE '2027-01-01' AS d) x;"},{"sql":"SELECT WEEKOFYEAR(d) AS iso_week,\n       YEARWEEK(d, 3) AS iso_yearweek\nFROM (SELECT CURDATE() AS d) x;"},{"sql":"SELECT TO_CHAR(d, 'IW') AS iso_week,\n       TO_CHAR(d, 'IYYY') AS iso_year\nFROM (SELECT DATE '2027-01-01' AS d FROM dual);"}],"see_also":["first-and-last-day-of-week","fiscal-year-mapping"],"faqs":[{"question":"Why does Jan 1 sometimes show week 52 or 53?","answer":"Under ISO rules, Jan 1 belongs to the previous year's last week when it falls on a Friday, Saturday or Sunday; 2027-01-01 is a Friday, so it is week 53 of 2026. That is why the ISO year (ISOYEAR, IYYY, YEARWEEK mode 3, or the shifted YEAR() on SQL Server) should be grouped with the week number, never the calendar year."},{"question":"Is SQLite's %W the ISO week number?","answer":"No: strftime('%W') counts Monday-based weeks from 00 and ignores the first-Thursday rule, so it disagrees with ISO around New Year. SQLite ships no ISO week function, so derive the week from the computed Monday (see first-and-last-day-of-week) or do it in application code."}]},"source_url":"https://sqlly.app/sql-snippets/iso-week-number","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/join-child-rows-comma-list","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Join child rows into a comma-separated list in SQL","description":"Aggregate many child rows into one 'ORD-1, ORD-2, ORD-3' string per parent with STRING_AGG and its cousins.","body":{"slug":"join-child-rows-comma-list","name":"Join child rows into a comma list","h1":"Join child rows into a comma-separated list in SQL","category":"text","lede":"Show each customer with their order references in a single cell instead of one row per order.","engine_slug":"postgresql","problem":"A customer overview reads better with all order references in one cell. STRING_AGG concatenates the child rows in a defined order.","sql":"SELECT c.customer_id,\n       STRING_AGG(o.order_ref, ', ' ORDER BY o.order_ref) AS order_list\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nGROUP BY c.customer_id;","how_it_works":"The JOIN produces one row per order, and STRING_AGG with an ORDER BY inside the call folds them back to one row per customer, comma-separated in a stable order. Without the ORDER BY the order of values is not guaranteed. Use LEFT JOIN plus COALESCE if customers without orders must still appear.","variants":[{"sql":"SELECT c.customer_id,\n       STRING_AGG(o.order_ref, ', ') WITHIN GROUP (ORDER BY o.order_ref) AS order_list\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nGROUP BY c.customer_id;"},{"sql":"SELECT c.customer_id,\n       GROUP_CONCAT(o.order_ref ORDER BY o.order_ref SEPARATOR ', ') AS order_list\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nGROUP BY c.customer_id;"},{"sql":"SELECT c.customer_id,\n       LISTAGG(o.order_ref, ', ') WITHIN GROUP (ORDER BY o.order_ref) AS order_list\nFROM customers c\nJOIN orders o ON o.customer_id = c.customer_id\nGROUP BY c.customer_id;"}],"see_also":["split-csv-into-rows"],"faqs":[{"question":"What if the list can exceed the string limit?","answer":"MySQL's GROUP_CONCAT stops at group_concat_max_len (default 1024 bytes) and silently truncates; SQL Server's STRING_AGG raises an error past 8000 bytes unless you CAST the value to VARCHAR(MAX) or NVARCHAR(MAX). Oracle's LISTAGG errors past its VARCHAR2 limit (4000 bytes by default) unless you add ON OVERFLOW TRUNCATE (12.2+). Test against your worst-case parent."}]},"source_url":"https://sqlly.app/sql-snippets/join-child-rows-comma-list","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/keep-newest-per-key","corpus":"sql-snippets","engine":"all","language":"en","title":"Keep the newest row per key","description":"ROW_NUMBER ordered by updated_at DESC keeps the latest row per key: the latest-state view.","body":{"slug":"keep-newest-per-key","name":"Keep newest per key","h1":"Keep the newest row per key","category":"data-quality","lede":"Partition by the key, order by recency descending, and keep rank 1: one row per key, the most recent one.","engine_slug":"all","problem":"addresses accumulates a row per change, so a customer has many. Reports want the current address: exactly one row per customer, the one with the latest updated_at.","sql":"WITH ranked AS (\n  SELECT id, customer_id, city, updated_at,\n         ROW_NUMBER() OVER (\n           PARTITION BY customer_id\n           ORDER BY updated_at DESC, id DESC\n         ) AS rn\n  FROM addresses\n)\nSELECT id, customer_id, city, updated_at\nFROM ranked\nWHERE rn = 1;","how_it_works":"Each customer_id partition is ordered newest-first, so rn = 1 is the latest address; the id DESC tiebreaker makes the winner deterministic when two rows share a timestamp. The WHERE keeps only the winners, one row per customer. History stays in the table; this is a view over it, not a delete. keep-oldest-per-key runs this DELETE with the ORDER BY flipped to ASC, keeping the first-stored copy instead.","variants":[{"sql":"DELETE FROM addresses\nWHERE id IN (\n  SELECT id\n  FROM (\n    SELECT id,\n           ROW_NUMBER() OVER (\n             PARTITION BY customer_id\n             ORDER BY updated_at DESC, id DESC\n           ) AS rn\n    FROM addresses\n  ) ranked\n  WHERE rn > 1\n);"}],"see_also":["dedupe-with-window-functions","keep-oldest-per-key","find-duplicates-on-a-key"],"faqs":[{"question":"Latest by updated_at or by id?","answer":"By a real timestamp when you have one you trust; by id when you do not, because auto-increment ids reflect insert order. Ordering by both (timestamp first, id as tiebreaker) handles equal timestamps deterministically. Never trust a timestamp that application code forgets to set; check the rows-changed-since-yesterday recipe for that audit."},{"question":"Can a row change while the delete is running?","answer":"The ranking reads a snapshot, so a row updated mid-run can survive with an updated_at newer than the keeper's. Repeat the preview until it returns nothing, or open the transaction before ranking so the rows you ranked are the rows you delete."}]},"source_url":"https://sqlly.app/sql-snippets/keep-newest-per-key","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/keep-oldest-per-key","corpus":"sql-snippets","engine":"all","language":"en","title":"Keep the oldest row per key","description":"ROW_NUMBER ordered by created_at ASC keeps the original row per key: the first-ever-state view.","body":{"slug":"keep-oldest-per-key","name":"Keep oldest per key","h1":"Keep the oldest row per key","category":"data-quality","lede":"Partition by the key, order by creation ascending, and keep rank 1: one row per key, the one that was created first.","engine_slug":"all","problem":"Merge tooling often wants the original record to survive: the account that was created first, with every later duplicate retired toward it. Ranking ascending picks the originals.","sql":"WITH ranked AS (\n  SELECT id, customer_id, city, created_at,\n         ROW_NUMBER() OVER (\n           PARTITION BY customer_id\n           ORDER BY created_at ASC, id ASC\n         ) AS rn\n  FROM addresses\n)\nSELECT id, customer_id, city, created_at\nFROM ranked\nWHERE rn = 1;","how_it_works":"Ordering each partition by created_at ASC puts the original first, so rn = 1 is the oldest row per customer; id ASC breaks creation-time ties deterministically. WHERE rn = 1 keeps exactly one row per key. This is the mirror image of keep-newest-per-key: same shape, opposite sort. keep-newest-per-key is this delete with DESC ordering, for the teams that keep the latest revision instead of the original.","variants":[{"sql":"DELETE FROM addresses\nWHERE id IN (\n  SELECT id\n  FROM (\n    SELECT id,\n           ROW_NUMBER() OVER (\n             PARTITION BY customer_id\n             ORDER BY created_at ASC, id ASC\n           ) AS rn\n    FROM addresses\n  ) ranked\n  WHERE rn > 1\n);"},{"sql":"SELECT a.*\nFROM addresses a\nJOIN (\n  SELECT customer_id, MIN(created_at) AS first_created\n  FROM addresses\n  GROUP BY customer_id\n) f ON f.customer_id = a.customer_id\n   AND f.first_created = a.created_at\nORDER BY a.customer_id;"}],"see_also":["dedupe-with-window-functions","keep-newest-per-key","delete-duplicates-keep-one"],"faqs":[{"question":"Why prefer the window version over MIN + join?","answer":"Both find the oldest row, but the window version returns exactly one row per key even when several share the same created_at, while MIN + join returns all tied rows. When 'exactly one survivor per key' matters (merges, deletes, unique indexes), ROW_NUMBER with an id tiebreaker is the safer shape."}]},"source_url":"https://sqlly.app/sql-snippets/keep-oldest-per-key","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/keyset-pagination","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Keyset (seek) pagination","description":"Fetch the next page by remembering the last row seen, with a WHERE clause instead of OFFSET.","body":{"slug":"keyset-pagination","name":"Keyset pagination","h1":"Keyset (seek) pagination","category":"querying","lede":"Seek past the rows you already have. Page 1000 costs the same as page 1.","engine_slug":"postgresql","problem":"You are paging through millions of orders newest-first and need every page to be fast and stable.","sql":"SELECT id, customer_id, order_date, amount\nFROM orders\nWHERE order_date < '2026-06-01 12:00:00'\n   OR (order_date = '2026-06-01 12:00:00' AND id < 1000)\nORDER BY order_date DESC, id DESC\nLIMIT 20;","how_it_works":"The WHERE clause expresses 'strictly after the last row I saw' using the same composite key the ORDER BY sorts by. The engine seeks straight into the index on (order_date DESC, id DESC) instead of counting out skipped rows. The client passes the last row's order_date and id as the cursor; the tie on order_date is broken by id so no row is skipped or repeated. The offset-pagination-pitfalls recipe reuses this query to show the cure for deep pages.","variants":[{"sql":"SELECT id, customer_id, order_date, amount\nFROM orders\nWHERE (order_date, id) < ('2026-06-01 12:00:00', 1000)\nORDER BY order_date DESC, id DESC\nLIMIT 20;"},{"sql":"SELECT id, customer_id, order_date, amount\nFROM orders\nWHERE order_date < '2026-06-01 12:00:00'\n   OR (order_date = '2026-06-01 12:00:00' AND id < 1000)\nORDER BY order_date DESC, id DESC\nOFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY;"},{"sql":"SELECT id, customer_id, order_date, amount\nFROM orders\nWHERE order_date < TIMESTAMP '2026-06-01 12:00:00'\n   OR (order_date = TIMESTAMP '2026-06-01 12:00:00' AND id < 1000)\nORDER BY order_date DESC, id DESC\nFETCH FIRST 20 ROWS ONLY;"}],"see_also":["offset-pagination-pitfalls","tiebreak-ordering"],"faqs":[{"question":"What does the cursor need to contain?","answer":"The values of the last row for every column in the ORDER BY, in order. That is why a unique tiebreaker column belongs in the sort: without it two rows can tie and the cursor cannot say which one came last."},{"question":"Can users jump to page 37?","answer":"Not directly, which is the trade-off. Keyset pagination gives you next/previous; a numbered page index needs OFFSET or a precomputed page table. Most APIs are fine with next/previous."}]},"source_url":"https://sqlly.app/sql-snippets/keyset-pagination","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/kill-query-safely","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Cancel a long-running query in PostgreSQL","description":"Finds statements running over five minutes and cancels them with pg_cancel_backend, which stops the statement but keeps the connection, plus the checks first.","body":{"slug":"kill-query-safely","name":"Kill a query safely","h1":"Cancel a long-running query in PostgreSQL","category":"monitoring","lede":"pg_cancel_backend stops the running statement and leaves the connection up. Here is how to pick the target and what happens to its transaction.","engine_slug":"postgresql","problem":"PostgreSQL has two ways to stop someone else's work. pg_cancel_backend(pid) aborts the running statement and leaves the connection open. pg_terminate_backend(pid) ends the connection and rolls back its transaction. Cancel first: it is usually enough, and the application gets an ordinary query error instead of a dropped connection. Cancelling still throws away what the statement did, because the statement's changes roll back.","sql":"SELECT pid, usename, datname, state,\n       now() - query_start AS runtime,\n       LEFT(query, 120) AS query,\n       wait_event_type, wait_event,\n       pg_cancel_backend(pid) AS cancel_requested\nFROM pg_stat_activity\nWHERE state = 'active'\n  AND backend_type = 'client backend'\n  AND now() - query_start > interval '5 minutes'\n  AND pid <> pg_backend_pid()\nORDER BY query_start;","how_it_works":"As written, this cancels every client statement that has run for more than five minutes, so run it without the pg_cancel_backend column first and look at the list. The checks: leave out your own session (pid <> pg_backend_pid()); look at wait_event_type, because a query waiting on a Lock is a victim and cancelling it frees nothing; ask the owner before cancelling a batch job or import; and expect the effect on the transaction. Outside an explicit transaction the statement simply rolls back. Inside BEGIN ... COMMIT, the whole transaction is now aborted: the session shows idle in transaction (aborted), keeps its locks, and rejects every statement until the client sends ROLLBACK. A cancel can also be ignored for a while by code that does not check for interrupts. In either case pg_terminate_backend is the next step. terminate-backend shows the harder stop when the cancel is ignored.","variants":[{"sql":"SELECT pg_cancel_backend(12345);"},{"sql":"-- SQL Server has no cancel-statement-only command for another session;\n-- KILL disconnects it and rolls back its open transaction.\nKILL 53;"}],"see_also":["terminate-backend","longest-running-queries-now","statement-timeout-session"],"faqs":[{"question":"I cancelled the query but the session still holds locks. Why?","answer":"Because the statement ran inside an explicit transaction. Cancelling aborted that transaction but did not end it: the session is idle in transaction (aborted) and keeps its locks until the application issues ROLLBACK. If the application never does, pg_terminate_backend ends the connection, which rolls the transaction back and releases the locks."},{"question":"How do I stop spending every incident hand-killing queries?","answer":"Set statement_timeout per role, with a short limit for the application role and a longer one for reporting and batch roles, and set lock_timeout in migration sessions. The statement-timeout recipe shows both. A timeout also leaves a clear trace: the client gets ERROR: canceling statement due to statement timeout, and the same line goes to the server log."}]},"source_url":"https://sqlly.app/sql-snippets/kill-query-safely","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/lag-compare-within-group","corpus":"sql-snippets","engine":"all","language":"en","title":"Lag compare within a group","description":"Show each order next to the previous one for the same customer, plus the change since the customer's first order.","body":{"slug":"lag-compare-within-group","name":"Compare to the previous row in a group","h1":"Lag compare within a group","category":"querying","lede":"LAG and FIRST_VALUE with a shared PARTITION BY: row-over-row deltas without self-joins.","engine_slug":"all","problem":"You want, per order, how much bigger or smaller it is than the customer's previous order.","sql":"SELECT customer_id, order_date, amount,\n       LAG(amount) OVER (PARTITION BY customer_id\n                         ORDER BY order_date, id) AS prev_amount,\n       amount - LAG(amount) OVER (PARTITION BY customer_id\n                                  ORDER BY order_date, id) AS change_vs_prev\nFROM orders\nORDER BY customer_id, order_date;","how_it_works":"LAG reads the previous row's amount inside the same customer partition; the first row per customer gets NULL because nothing precedes it. PARTITION BY resets the ordering per customer, so a customer's rows never compare against another customer's. LEAD is the mirror image, reading the next row, and both take an offset argument to look further back or ahead.","variants":[{"sql":"SELECT customer_id, order_date, amount,\n       amount - LAG(amount) OVER (PARTITION BY customer_id\n                                  ORDER BY order_date, id) AS change_vs_prev,\n       amount - FIRST_VALUE(amount) OVER (PARTITION BY customer_id\n                                          ORDER BY order_date, id) AS change_vs_first\nFROM orders\nORDER BY customer_id, order_date;"}],"see_also":["month-over-month-delta","first-last-value-in-partition"],"faqs":[{"question":"Can LAG return a default instead of NULL?","answer":"Yes: LAG(amount, 1, 0) looks back one row and returns 0 when there is none. Use it when downstream arithmetic would rather have a zero than a NULL, but keep in mind the first row then reports a fake change."}]},"source_url":"https://sqlly.app/sql-snippets/lag-compare-within-group","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/largest-indexes","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find the largest indexes in PostgreSQL","description":"Ranks every index by its on-disk size so you can spot bloated or oversized ones and target maintenance where the bytes actually are.","body":{"slug":"largest-indexes","name":"Largest indexes","h1":"Find the largest indexes in PostgreSQL","category":"indexes","lede":"Before you tune an index, find out how big it is. This ranks every index on a user table by the space it takes on disk.","engine_slug":"postgresql","problem":"A large index competes with table data for shared_buffers, makes every index scan touch more pages and adds to base backup size. Some of the biggest are accidental: a multi-column index on a wide text column, or an index that bloated after years of updates. Ranking by size tells you where REINDEX or a redesign would pay off.","sql":"SELECT schemaname, relname AS table_name, indexrelname AS index_name,\n       pg_relation_size(indexrelid) AS size_bytes,\n       pg_size_pretty(pg_relation_size(indexrelid)) AS size,\n       idx_scan\nFROM pg_stat_user_indexes\nORDER BY pg_relation_size(indexrelid) DESC\nLIMIT 25;","how_it_works":"pg_stat_user_indexes carries the index OID (indexrelid), so pg_relation_size returns each index's on-disk size, empty and half-empty pages included. Note the column names: this view uses relname and indexrelname, while the pg_indexes view uses tablename and indexname. The ORDER BY uses the byte count, not the pg_size_pretty text. idx_scan sits beside the size so a large index with few scans stands out. table-index-sizes-topn ranks per table instead of instance-wide and pairs the size with scan counts.","variants":[{"sql":"SELECT TOP 25\n    OBJECT_SCHEMA_NAME(i.object_id) AS schema_name,\n    OBJECT_NAME(i.object_id) AS table_name,\n    i.name AS index_name,\n    CAST(SUM(ps.used_page_count) * 8 / 1024.0 AS DECIMAL(12,1)) AS size_mb,\n    ISNULL(us.user_seeks + us.user_scans + us.user_lookups, 0) AS total_reads\nFROM sys.indexes i\nJOIN sys.dm_db_partition_stats ps\n  ON ps.object_id = i.object_id AND ps.index_id = i.index_id\nLEFT JOIN sys.dm_db_index_usage_stats us\n  ON us.object_id = i.object_id AND us.index_id = i.index_id AND us.database_id = DB_ID()\nWHERE i.index_id > 1\n  AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1\nGROUP BY i.object_id, i.name, us.user_seeks, us.user_scans, us.user_lookups\nORDER BY size_mb DESC;"},{"sql":"CREATE EXTENSION IF NOT EXISTS pgstattuple;\nSELECT index_size, avg_leaf_density, leaf_fragmentation\nFROM pgstatindex('public.orders_created_at_idx');"}],"see_also":["index-bloat-estimate","unused-indexes","table-index-sizes-topn"],"faqs":[{"question":"An index is huge but has high idx_scan. Should I drop it?","answer":"No. A high idx_scan means queries depend on it. Check whether it is bloated instead: pgstatindex reports avg_leaf_density, which sits near 90 percent for a freshly built B-tree (the default fillfactor). If it is far below that, REINDEX INDEX CONCURRENTLY rebuilds it without blocking writes."},{"question":"Why does my index have half-empty pages after a bulk load?","answer":"Inserting keys in random order (random UUIDs, shuffled ids) splits full leaf pages in half, and the halves fill back up slowly. Loading in key order, or creating the index after the load instead of before, gives densely packed leaf pages."}]},"source_url":"https://sqlly.app/sql-snippets/largest-indexes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/last-analyze-per-table","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find the last ANALYZE time per table in PostgreSQL","description":"Lists every table ordered by how long ago its statistics were last collected, never-analyzed tables first.","body":{"slug":"last-analyze-per-table","name":"Last ANALYZE per table","h1":"Find the last ANALYZE time per table in PostgreSQL","category":"monitoring","lede":"Every table, ordered by how long ago its planner statistics were collected, with never-analyzed tables at the top.","engine_slug":"postgresql","problem":"A quick staleness sweep answers one question per table: when were its planner statistics last collected, by anyone? Tables at the top have gone longest without fresh statistics, or have never had any. Those are worth checking first when a plan is bad in production but fine on a freshly loaded copy, where ANALYZE has just run.","sql":"SELECT relname AS table_name,\n       n_live_tup,\n       last_analyze, last_autoanalyze,\n       GREATEST(last_analyze, last_autoanalyze) AS last_stats,\n       now() - GREATEST(last_analyze, last_autoanalyze) AS stats_age\nFROM pg_stat_user_tables\nORDER BY COALESCE(GREATEST(last_analyze, last_autoanalyze), '1900-01-01'::timestamptz);","how_it_works":"last_analyze and last_autoanalyze are independent timestamps (manual ANALYZE versus autovacuum's analyze phase), so GREATEST picks whichever happened last; COALESCE with a sentinel puts never-analyzed tables first without a separate NULL branch. stats_age makes the ordering readable at a glance. Fresh on this list does not mean healthy on its own; pair it with n_mod_since_analyze from the statistics-staleness recipe to catch a table analyzed yesterday but rewritten a million rows since.","variants":[{"sql":"SELECT format('ANALYZE %I.%I;', schemaname, relname) AS analyze_statement,\n       GREATEST(last_analyze, last_autoanalyze) AS last_stats\nFROM pg_stat_user_tables\nWHERE GREATEST(last_analyze, last_autoanalyze) < now() - interval '7 days'\n   OR (last_analyze IS NULL AND last_autoanalyze IS NULL)\nORDER BY n_live_tup DESC;"}],"see_also":["statistics-staleness","autovacuum-status","index-usage-ratio-per-table"],"faqs":[{"question":"ANALYZE vs VACUUM: which one do I need for slow plans?","answer":"ANALYZE refreshes planner statistics, so it is the one for bad plan choices. VACUUM reclaims dead tuples, so it is the one for bloat. Autovacuum does both, but on different schedules and thresholds, so a table can be well-vacuumed yet poorly analyzed or the reverse."},{"question":"Does ANALYZE block queries?","answer":"No. ANALYZE takes a SHARE UPDATE EXCLUSIVE lock, which lets reads and writes continue; it conflicts only with VACUUM, another ANALYZE, CREATE INDEX CONCURRENTLY and most ALTER TABLE forms on the same table. It reads a random sample of about 30,000 rows rather than the whole table, so it is normally fine during business hours even on large tables. New plans pick up the statistics as soon as it commits."}]},"source_url":"https://sqlly.app/sql-snippets/last-analyze-per-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/last-modified-staleness","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Report on last-modified staleness","description":"Bucket rows by how long ago they were touched: never updated, over a year, over 90 days, recent.","body":{"slug":"last-modified-staleness","name":"Staleness report","h1":"Report on last-modified staleness","category":"data-quality","lede":"Group rows into freshness buckets built from updated_at and created_at to see how stale a table is overall.","engine_slug":"postgresql","problem":"A CRM table where most rows have not moved in years is a candidate for archiving, and stale updated_at values also hint at dead imports. One query buckets the whole table by freshness.","sql":"SELECT CASE\n         WHEN updated_at IS NULL THEN 'never tracked'\n         WHEN updated_at = created_at THEN 'never updated'\n         WHEN updated_at < CURRENT_TIMESTAMP - INTERVAL '1 year' THEN 'over a year'\n         WHEN updated_at < CURRENT_TIMESTAMP - INTERVAL '90 days' THEN '90+ days'\n         ELSE 'recent'\n       END AS freshness,\n       COUNT(*) AS row_count\nFROM customers\nGROUP BY 1\nORDER BY row_count DESC;","how_it_works":"The CASE expression maps each row to a freshness label, evaluated top to bottom: never-tracked and never-updated are caught first, then the aging thresholds. The IS NULL branch has to come first, because a NULL updated_at fails every comparison and would otherwise fall through to 'recent'. GROUP BY 1 groups by the first select-list column, which PostgreSQL, MySQL and SQLite allow. Rows marked 'never updated' still equal their creation timestamp, a soft signal that the row was written once and left alone.","variants":[{"sql":"SELECT id, email, updated_at\nFROM customers\nWHERE updated_at IS NOT NULL\n  AND updated_at < CURRENT_TIMESTAMP - INTERVAL '1 year'\nORDER BY updated_at\nLIMIT 100;"},{"sql":"SELECT CASE\n         WHEN updated_at IS NULL THEN 'never tracked'\n         WHEN updated_at = created_at THEN 'never updated'\n         WHEN updated_at < NOW() - INTERVAL 1 YEAR THEN 'over a year'\n         WHEN updated_at < NOW() - INTERVAL 90 DAY THEN '90+ days'\n         ELSE 'recent'\n       END AS freshness,\n       COUNT(*) AS row_count\nFROM customers\nGROUP BY 1\nORDER BY row_count DESC;"}],"see_also":["rows-changed-since-yesterday","soft-delete-audit"],"faqs":[{"question":"Is 'never updated' bad?","answer":"Not on its own. Reference data and stable customers legitimately never change. It becomes a data-quality signal when the share is large and unexpected, or when the rows also look wrong (missing fields, old formats). Pair the bucket counts with the row lists to judge whether staleness means archive, refresh or leave alone."}]},"source_url":"https://sqlly.app/sql-snippets/last-modified-staleness","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/latest-row-per-customer","corpus":"sql-snippets","engine":"all","language":"en","title":"Latest row per customer","description":"Fetch each customer's most recent order with all its columns, using ROW_NUMBER or DISTINCT ON.","body":{"slug":"latest-row-per-customer","name":"Latest row per customer","h1":"Latest row per customer","category":"querying","lede":"Newest row per group with ROW_NUMBER, plus PostgreSQL's DISTINCT ON shortcut.","engine_slug":"all","problem":"You want each customer's most recent order, whole row, not just the date. MAX(order_date) in a GROUP BY loses the rest of the row.","sql":"WITH ranked AS (\n  SELECT o.*,\n         ROW_NUMBER() OVER (PARTITION BY customer_id\n                            ORDER BY order_date DESC, id DESC) AS rn\n  FROM orders o\n)\nSELECT id, customer_id, order_date, amount, status\nFROM ranked\nWHERE rn = 1;","how_it_works":"ROW_NUMBER numbers each customer's orders newest-first and the filter keeps the first one. The id DESC tiebreaker makes the choice deterministic when two orders share the same order_date, which otherwise lets the engine pick arbitrarily. This scales fine with an index on (customer_id, order_date DESC, id DESC). The same ranking shape drives earliest-row-per-key (the ORDER BY flipped) and deduplicate-query-output (the partition on the duplicate key instead of the parent).","variants":[{"sql":"SELECT DISTINCT ON (customer_id)\n       id, customer_id, order_date, amount, status\nFROM orders\nORDER BY customer_id, order_date DESC, id DESC;"}],"see_also":["top-n-per-group","earliest-row-per-key","fill-gaps-calendar-spine"],"faqs":[{"question":"Why not MAX(order_date) with GROUP BY?","answer":"Because the other columns would have to come from somewhere. Adding them to GROUP BY splits rows further, and joining back on MAX(order_date) returns every order tied at the latest date, not one row per customer."},{"question":"What does DISTINCT ON demand from the ORDER BY?","answer":"PostgreSQL requires the ORDER BY to lead with the DISTINCT ON expressions, so ORDER BY customer_id, order_date DESC, id DESC is the required shape. MySQL and SQLite have no DISTINCT ON at all and always need the ROW_NUMBER form."}]},"source_url":"https://sqlly.app/sql-snippets/latest-row-per-customer","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-all-tables-sizes","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List all tables with sizes","description":"Every user table in a schema with its total on-disk size, largest first. The base query uses pg_class; variants for MySQL, SQL Server and SQLite.","body":{"slug":"list-all-tables-sizes","name":"List all tables with sizes","h1":"List all tables with sizes","category":"schema","lede":"Before you reclaim space or archive data, you need to know which tables are actually big. This recipe lists every table in a schema with its total size, biggest first.","engine_slug":"postgresql","problem":"The disk holding the database keeps filling and no one can say which table is responsible. Start with a ranked size list.","sql":"SELECT c.relname AS table_name,\n       pg_total_relation_size(c.oid) AS total_bytes,\n       pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size\nFROM pg_class c\nJOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE c.relkind = 'r'\n  AND n.nspname = 'public'\nORDER BY pg_total_relation_size(c.oid) DESC;","how_it_works":"pg_total_relation_size counts the table plus its indexes, TOAST data and free-space map, which is the number that shows up in disk usage. The join to pg_namespace filters to one schema and relkind 'r' keeps ordinary tables while leaving views and partitioned parents out. Ordering by the raw byte count sorts biggest-first; the pretty column is only for display.","variants":[{"sql":"-- reserved pages across heap/clustered index, nonclustered\n-- indexes and LOB data; rows counted from index 0 or 1 only\nSELECT SCHEMA_NAME(t.schema_id) AS schema_name,\n       t.name AS table_name,\n       SUM(CASE WHEN ps.index_id IN (0, 1) THEN ps.row_count END) AS row_count,\n       CAST(SUM(ps.reserved_page_count) * 8 / 1024.0 AS decimal(12,1)) AS size_mb\nFROM sys.dm_db_partition_stats ps\nJOIN sys.tables t ON t.object_id = ps.object_id\nGROUP BY t.schema_id, t.name\nORDER BY SUM(ps.reserved_page_count) DESC;"},{"sql":"SELECT table_name,\n       ROUND((data_length + index_length) / 1024 / 1024, 1) AS size_mb,\n       table_rows AS row_estimate\nFROM information_schema.tables\nWHERE table_schema = 'mydb' AND table_type = 'BASE TABLE'\nORDER BY data_length + index_length DESC;"},{"sql":"-- needs a build with the dbstat virtual table (the sqlite3\n-- shell has it); index b-trees are folded into their table\nSELECT m.tbl_name AS table_name,\n       SUM(s.pgsize) AS total_bytes\nFROM dbstat s\nJOIN sqlite_master m ON m.name = s.name\nWHERE m.tbl_name NOT LIKE 'sqlite_%'\nGROUP BY m.tbl_name\nORDER BY total_bytes DESC;"}],"see_also":["database-size-summary","table-bloat-estimate","row-counts-every-table"],"faqs":[{"question":"Why doesn't the total match the data directory size?","answer":"Per-table sizes leave out WAL, system catalogs, temp files and other databases in the cluster. They do include dead rows: plain VACUUM marks that space reusable but rarely returns it to the OS, so a table that once held many more rows keeps its size until VACUUM FULL or pg_repack rewrites it."}]},"source_url":"https://sqlly.app/sql-snippets/list-all-tables-sizes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-check-constraints","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"List check constraints","description":"Every check constraint with the expression it enforces, so the business rules baked into the schema are visible and reviewable.","body":{"slug":"list-check-constraints","name":"List check constraints","h1":"List check constraints","category":"schema","lede":"Check constraints encode business rules directly in the schema: price > 0, status IN (...), start < end. This recipe lists every one with the expression it enforces.","engine_slug":"sql-server","problem":"An insert is rejected with a check-constraint error, or you are documenting which business rules the database enforces on its own. Either way you need the expressions.","sql":"SELECT t.name AS table_name,\n       cc.name AS constraint_name,\n       cc.definition\nFROM sys.check_constraints cc\nJOIN sys.tables t ON t.object_id = cc.parent_object_id\nORDER BY t.name, cc.name;","how_it_works":"sys.check_constraints stores each constraint's expression in definition, normalized by SQL Server (qty > 0 comes back as ([qty]>(0))). Joining to sys.tables attaches the table name. A constraint added or re-enabled WITH NOCHECK has is_not_trusted = 1: existing rows were never checked, and the optimizer will not use it to skip work in query plans.","variants":[{"sql":"SELECT n.nspname AS schema_name,\n       c.relname AS table_name,\n       con.conname AS constraint_name,\n       pg_get_constraintdef(con.oid) AS definition,\n       con.convalidated AS validated\nFROM pg_constraint con\nJOIN pg_class c ON c.oid = con.conrelid\nJOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE con.contype = 'c' AND n.nspname = 'public'\nORDER BY c.relname;"},{"sql":"-- check_constraints has no table column; get it from\n-- table_constraints. CHECK is enforced from MySQL 8.0.16.\nSELECT tc.table_name, cc.constraint_name, cc.check_clause,\n       tc.enforced\nFROM information_schema.check_constraints cc\nJOIN information_schema.table_constraints tc\n  ON tc.constraint_schema = cc.constraint_schema\n AND tc.constraint_name = cc.constraint_name\n AND tc.constraint_type = 'CHECK'\nWHERE cc.constraint_schema = 'mydb'\nORDER BY tc.table_name, cc.constraint_name;"}],"see_also":["list-enum-domains","make-column-not-null-safely","list-triggers-on-table"],"faqs":[{"question":"What does convalidated = false mean on PostgreSQL?","answer":"The constraint was added with NOT VALID, so existing rows were never checked and only new writes are enforced. ALTER TABLE ... VALIDATE CONSTRAINT scans the existing rows under a SHARE UPDATE EXCLUSIVE lock, which lets reads and writes continue, and flips convalidated to true if every row passes."}]},"source_url":"https://sqlly.app/sql-snippets/list-check-constraints","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-enum-domains","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List enum types and their values","description":"All enum types in a schema with the values they allow, the columns that use them, and PostgreSQL domains with their CHECK rules.","body":{"slug":"list-enum-domains","name":"List enum types and domains","h1":"List enum types and their values","category":"schema","lede":"Postgres enum types carry their allowed values in the catalog, and MySQL enums carry them inline on each column. This recipe lists every enum with its values.","engine_slug":"postgresql","problem":"The application and the schema disagree about which status values are legal, so list what each enum actually permits before adding the next one.","sql":"SELECT t.typname AS enum_name,\n       string_agg(e.enumlabel, ', ' ORDER BY e.enumsortorder) AS allowed_values\nFROM pg_type t\nJOIN pg_enum e ON e.enumtypid = t.oid\nJOIN pg_namespace n ON n.oid = t.typnamespace\nWHERE n.nspname = 'public'\nGROUP BY t.typname\nORDER BY t.typname;","how_it_works":"pg_enum stores one row per allowed value of each enum type. enumsortorder is the position in the type, which is also its sort order: ORDER BY status sorts by that position, not alphabetically, and ALTER TYPE ... ADD VALUE ... BEFORE can slot a new value into the middle. To find the columns that use an enum, match its name against udt_name in information_schema.columns, as the second variant does.","variants":[{"sql":"SELECT table_name, column_name, column_type\nFROM information_schema.columns\nWHERE table_schema = 'mydb' AND data_type = 'enum'\nORDER BY table_name, column_name;\n-- column_type holds the full enum('a','b','c') list"},{"sql":"SELECT table_name, column_name\nFROM information_schema.columns\nWHERE table_schema = 'public'\n  AND udt_name = 'order_status'\nORDER BY table_name;"},{"sql":"SELECT t.typname AS domain_name,\n       format_type(t.typbasetype, t.typtypmod) AS base_type,\n       t.typnotnull AS not_null,\n       pg_get_constraintdef(c.oid) AS rule\nFROM pg_type t\nJOIN pg_namespace n ON n.oid = t.typnamespace\nLEFT JOIN pg_constraint c ON c.contypid = t.oid\nWHERE t.typtype = 'd' AND n.nspname = 'public'\nORDER BY t.typname;"}],"see_also":["list-check-constraints","list-table-columns","find-columns-by-type"],"faqs":[{"question":"Can I remove a value from an enum?","answer":"Not in place on PostgreSQL: there is no ALTER TYPE ... DROP VALUE, so you create a new type without the value, move the columns to it with ALTER COLUMN ... TYPE ... USING, and drop the old type. MySQL takes a MODIFY COLUMN with the shorter list, which rebuilds the table and fails in strict mode if any row still holds the removed value. For value sets that change often, a lookup table with a foreign key is easier to maintain."},{"question":"Why is my freshly added enum value rejected in the same migration?","answer":"PostgreSQL accepts ALTER TYPE ... ADD VALUE inside a transaction since 12, but rows in that same transaction cannot use the value until it commits (the 'unsafe use of new value' error). Split the migration: commit the ADD VALUE, then write rows carrying it."}]},"source_url":"https://sqlly.app/sql-snippets/list-enum-domains","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-foreign-keys-targets","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List foreign keys and the tables/columns they point at","description":"Every foreign key with its source table/column and the referenced table/column, so you can map the dependency graph or plan load order.","body":{"slug":"list-foreign-keys-targets","name":"List foreign keys and their targets","h1":"List foreign keys and the tables/columns they point at","category":"schema","lede":"To understand a schema or plan a data load, you need every foreign key and where it points. This recipe lists each FK with its source column and the referenced target.","engine_slug":"postgresql","problem":"A delete fails with a foreign-key violation and nothing in the application code says which relationship caused it. You need both ends of every FK relationship named.","sql":"SELECT con.conname AS constraint_name,\n       src.relname AS table_name,\n       src_col.attname AS column_name,\n       tgt.relname AS referenced_table,\n       tgt_col.attname AS referenced_column\nFROM pg_constraint con\nJOIN pg_class src ON src.oid = con.conrelid\nJOIN pg_class tgt ON tgt.oid = con.confrelid\nJOIN unnest(con.conkey) WITH ORDINALITY AS sk(attnum, ord) ON true\nJOIN unnest(con.confkey) WITH ORDINALITY AS tk(attnum, ord) ON tk.ord = sk.ord\nJOIN pg_attribute src_col\n  ON src_col.attrelid = src.oid AND src_col.attnum = sk.attnum\nJOIN pg_attribute tgt_col\n  ON tgt_col.attrelid = tgt.oid AND tgt_col.attnum = tk.attnum\nWHERE con.contype = 'f'\nORDER BY src.relname, con.conname, sk.ord;","how_it_works":"pg_constraint stores a foreign key as two matching arrays of column numbers: conkey on the referencing side and confkey on the referenced side. Unnesting both with ordinality pairs them up positionally, which handles composite foreign keys correctly. contype 'f' selects foreign keys only; 'p', 'u', 'c' and 'x' are primary key, unique, check and exclusion constraints. Add a filter on src.relnamespace to limit the list to one schema.","variants":[{"sql":"SELECT kcu.constraint_name, kcu.table_name, kcu.column_name,\n       kcu.referenced_table_name, kcu.referenced_column_name,\n       rc.delete_rule, rc.update_rule\nFROM information_schema.key_column_usage kcu\nJOIN information_schema.referential_constraints rc\n  ON rc.constraint_schema = kcu.constraint_schema\n AND rc.constraint_name = kcu.constraint_name\nWHERE kcu.table_schema = 'mydb'\n  AND kcu.referenced_table_name IS NOT NULL\nORDER BY kcu.table_name;"},{"sql":"PRAGMA foreign_key_list(orders);\n-- one row per FK column: id, seq, table, from, to,\n-- on_update, on_delete, match"}],"see_also":["list-primary-keys","table-dependency-order","add-foreign-key-if-missing"],"faqs":[{"question":"How do I plan table load order from this output?","answer":"Load referenced tables first: any table that appears in referenced_table must be populated before the table in table_name. The table-dependency-order recipe turns this into an ordered list."},{"question":"Can this list be wrong about a foreign key?","answer":"Only if the key is untrusted: a foreign key added NOT VALID on PostgreSQL is still listed here but has never checked the existing rows, and SQL Server's NOCHECK reads the same way. Re-validate with ALTER TABLE ... VALIDATE CONSTRAINT before you trust the relationship for load ordering."}]},"source_url":"https://sqlly.app/sql-snippets/list-foreign-keys-targets","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-materialized-views-refresh","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List materialized views and refresh times","description":"Every PostgreSQL materialized view with its populated flag and size, plus a refresh-log table, since PostgreSQL keeps no last-refresh time.","body":{"slug":"list-materialized-views-refresh","name":"List materialized views","h1":"List materialized views and refresh times","category":"schema","lede":"Materialized views serve stale data by design, so the two things you want to know are which ones exist and when each was last refreshed. One of those the catalog answers.","engine_slug":"postgresql","problem":"A dashboard fed by a materialized view shows numbers nobody trusts, so the first step is seeing which matviews exist, how large they are and whether they are populated.","sql":"SELECT schemaname, matviewname, matviewowner,\n       ispopulated,\n       pg_size_pretty(pg_total_relation_size(\n         format('%I.%I', schemaname, matviewname)::regclass)) AS total_size\nFROM pg_matviews\nORDER BY matviewname;","how_it_works":"pg_matviews lists every materialized view with its owner and ispopulated, which is false only for a view created or refreshed WITH NO DATA; selecting from such a view raises an error. A failed REFRESH rolls back and leaves the previous contents in place. PostgreSQL records no last-refresh time, so stamp a log table from the job that runs REFRESH, in the same transaction, as the first variant does.","variants":[{"sql":"CREATE TABLE IF NOT EXISTS matview_refresh_log (\n    matview      text PRIMARY KEY,\n    refreshed_at timestamptz NOT NULL\n);\n\nBEGIN;\nREFRESH MATERIALIZED VIEW CONCURRENTLY public.daily_sales;\nINSERT INTO matview_refresh_log (matview, refreshed_at)\nVALUES ('public.daily_sales', now())\nON CONFLICT (matview) DO UPDATE\n  SET refreshed_at = excluded.refreshed_at;\nCOMMIT;"},{"sql":"-- SQL Server's materialized views are indexed views; every\n-- write to a base table updates them, so there is nothing\n-- to refresh\nSELECT s.name AS schema_name, v.name AS view_name,\n       i.name AS clustered_index\nFROM sys.views v\nJOIN sys.schemas s ON s.schema_id = v.schema_id\nJOIN sys.indexes i ON i.object_id = v.object_id AND i.index_id = 1;"}],"see_also":["list-views-definitions","row-counts-every-table","schema-version-table-recipe"],"faqs":[{"question":"Why is REFRESH MATERIALIZED VIEW CONCURRENTLY failing?","answer":"CONCURRENTLY needs at least one unique index on the materialized view that uses only column names (no expressions or WHERE clause), and the view must already be populated. Unlike CREATE INDEX CONCURRENTLY it can run inside a transaction block. Without such an index you are left with the plain REFRESH, which holds an ACCESS EXCLUSIVE lock so readers wait until it finishes."}]},"source_url":"https://sqlly.app/sql-snippets/list-materialized-views-refresh","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-primary-keys","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List primary keys and their columns","description":"Every primary key in a schema with the column or columns that make it up, read from information_schema, with composite keys listed in key order.","body":{"slug":"list-primary-keys","name":"List primary keys","h1":"List primary keys and their columns","category":"schema","lede":"Primary keys drive joins, replication and ORM assumptions. This recipe lists every primary key in a schema together with the column or columns that form it.","engine_slug":"postgresql","problem":"You are mapping an unfamiliar schema or checking that every key matches what the application expects, and you need the key columns for all tables in one result.","sql":"SELECT tc.table_schema, tc.table_name, tc.constraint_name,\n       kcu.column_name, kcu.ordinal_position\nFROM information_schema.table_constraints tc\nJOIN information_schema.key_column_usage kcu\n  ON kcu.constraint_schema = tc.constraint_schema\n AND kcu.constraint_name = tc.constraint_name\n AND kcu.table_name = tc.table_name\nWHERE tc.constraint_type = 'PRIMARY KEY'\n  AND tc.table_schema = 'public'\nORDER BY tc.table_name, kcu.ordinal_position;","how_it_works":"table_constraints tells you which tables have a primary key; key_column_usage names the columns inside it. A composite key appears as one row per column, ordered by ordinal_position, so table_name plus ordinal_position reconstructs the key exactly. The join matches on schema, constraint name and table name. The table name looks redundant on PostgreSQL, but MySQL names every primary key PRIMARY, and without it each key would pair with the columns of every other table's key.","variants":[{"sql":"SELECT t.name AS table_name,\n       kc.name AS constraint_name,\n       c.name AS column_name,\n       ic.key_ordinal\nFROM sys.key_constraints kc\nJOIN sys.tables t ON t.object_id = kc.parent_object_id\nJOIN sys.index_columns ic ON ic.object_id = t.object_id AND ic.index_id = kc.unique_index_id\nJOIN sys.columns c ON c.object_id = t.object_id AND c.column_id = ic.column_id\nWHERE kc.type = 'PK'\nORDER BY t.name, ic.key_ordinal;"},{"sql":"PRAGMA table_info(users);\n-- pk column: 0 = not in the key, otherwise 1-based position in the key"}],"see_also":["tables-without-primary-key","list-foreign-keys-targets","describe-table-columns"],"faqs":[{"question":"How do I spot composite primary keys in the output?","answer":"A composite key is the same constraint_name appearing more than once for one table. Sort by table and ordinal_position and the columns read in key order."}]},"source_url":"https://sqlly.app/sql-snippets/list-primary-keys","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-schemas","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List schemas","description":"All schemas in the current database and the role that owns each one, the first thing to check in a multi-tenant layout or a permission audit.","body":{"slug":"list-schemas","name":"List schemas","h1":"List schemas","category":"schema","lede":"Schemas are the namespace layer of a database, and in multi-tenant designs one tenant can equal one schema. This query lists all of them with their owners.","engine_slug":"postgresql","problem":"You are on an unfamiliar database and need to see how it is partitioned into namespaces and who owns each one, before creating or granting anything.","sql":"SELECT schema_name, schema_owner\nFROM information_schema.schemata\nORDER BY schema_name;","how_it_works":"information_schema.schemata lists the namespaces of the current database, including pg_catalog, information_schema and pg_toast; filter those out for user schemas only. On PostgreSQL it shows only schemas the current user owns or holds a privilege on, so a superuser and an application role can get different lists. pg_namespace has every schema regardless, plus the nspacl column with its access list.","variants":[{"sql":"SELECT s.name AS schema_name,\n       dp.name AS owner_name\nFROM sys.schemas s\nJOIN sys.database_principals dp ON dp.principal_id = s.principal_id\nORDER BY s.name;"},{"sql":"SELECT schema_name, default_character_set_name\nFROM information_schema.schemata;\n-- a schema and a database are the same thing in MySQL;\n-- SHOW DATABASES gives the same list. There is no owner."},{"sql":"SELECT n.nspname AS schema_name,\n       pg_size_pretty(sum(pg_total_relation_size(c.oid))) AS total_size\nFROM pg_namespace n\nJOIN pg_class c ON c.relnamespace = n.oid AND c.relkind = 'r'\nWHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\nGROUP BY n.nspname\nORDER BY sum(pg_total_relation_size(c.oid)) DESC;"}],"see_also":["move-table-between-schemas","list-views-definitions","grant-select-all-tables"],"faqs":[{"question":"What is the search_path doing to my queries?","answer":"On PostgreSQL, unqualified table names resolve through the search_path setting, which defaults to \"$user\", public. If you get 'relation does not exist' for a table you can list here, it lives in a schema outside the session's search_path. Check with SHOW search_path."}]},"source_url":"https://sqlly.app/sql-snippets/list-schemas","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-sequences-current-values","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List sequences and their current values","description":"All sequences in a database with their last value, increment and limit, so you can spot integer keys that are running out of room.","body":{"slug":"list-sequences-current-values","name":"List sequences and current values","h1":"List sequences and their current values","category":"schema","lede":"Integer keys have a ceiling, and a sequence racing toward it is an outage you can see coming. This recipe lists every sequence with its last value and increment.","engine_slug":"postgresql","problem":"An int key is partway to 2.1 billion and you need to know how much runway every sequence has left before planning a migration to bigint.","sql":"SELECT schemaname, sequencename,\n       last_value, start_value, increment_by, max_value\nFROM pg_sequences\nORDER BY sequencename;","how_it_works":"pg_sequences reports each sequence's last value without calling nextval. last_value is NULL for a sequence that has never been used, and with a CACHE setting above 1 it runs ahead of the ids actually stored, because each session reserves a block of values up front. Comparing last_value with max_value shows how much room is left; serial and integer identity columns get a max_value of 2147483647.","variants":[{"sql":"-- auto_increment is the NEXT value. MySQL 8 caches these stats\n-- for information_schema_stats_expiry (24h by default), so run\n-- ANALYZE TABLE first or SET information_schema_stats_expiry = 0\nSELECT table_name, auto_increment\nFROM information_schema.tables\nWHERE table_schema = 'mydb' AND auto_increment IS NOT NULL\nORDER BY auto_increment DESC;"},{"sql":"-- sequence objects only; IDENTITY columns are tracked in\n-- sys.identity_columns (see find-identity-columns)\nSELECT name, current_value, start_value, increment, maximum_value\nFROM sys.sequences\nORDER BY name;"},{"sql":"-- exists once any table is declared with AUTOINCREMENT;\n-- one row per such table: name, seq (largest id used)\nSELECT name, seq FROM sqlite_sequence;"}],"see_also":["find-identity-columns","database-size-summary","list-all-tables-sizes"],"faqs":[{"question":"How close is my table to overflowing int ids?","answer":"Divide last_value (or auto_increment) by 2147483647 for a signed 32-bit int column. Past roughly half, plan the move to bigint: changing the type of a key column rewrites the table and every index that contains it, and foreign key columns in other tables have to change with it."}]},"source_url":"https://sqlly.app/sql-snippets/list-sequences-current-values","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-table-columns","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"List columns of a table from system catalogs","description":"List one table's columns from the engine's own catalogs (sys.columns on SQL Server, pg_attribute on PostgreSQL) instead of INFORMATION_SCHEMA.","body":{"slug":"list-table-columns","name":"List columns of a table","h1":"List columns of a table from system catalogs","category":"schema","lede":"INFORMATION_SCHEMA is fine for portable work, but the native catalogs expose extra detail such as identity flags, computed columns and collation. This recipe lists one table's columns from the engine's native views.","engine_slug":"sql-server","problem":"The portable views give you names, types and nullability but stop there; when the answer depends on whether a column is an identity or a computed column, you have to ask the native catalogs.","sql":"SELECT c.name AS column_name,\n       t.name AS data_type,\n       c.max_length, c.precision, c.scale,\n       c.is_nullable, c.is_identity, c.is_computed\nFROM sys.columns c\nJOIN sys.types t ON t.user_type_id = c.user_type_id\nWHERE c.object_id = OBJECT_ID('dbo.Orders')\nORDER BY c.column_id;","how_it_works":"sys.columns carries one row per column of a table-valued object, with column_id giving declaration order. max_length is in bytes, so nvarchar(50) shows 100 and any (max) type shows -1. Joining sys.types on user_type_id returns the declared type name, which is the alias type's own name for a user-defined type; join on system_type_id as well if you need the underlying base type.","variants":[{"sql":"SELECT a.attname AS column_name,\n       format_type(a.atttypid, a.atttypmod) AS data_type,\n       NOT a.attnotnull AS is_nullable,\n       pg_get_expr(ad.adbin, ad.adrelid) AS column_default\nFROM pg_attribute a\nJOIN pg_class c ON c.oid = a.attrelid\nJOIN pg_namespace n ON n.oid = c.relnamespace\nLEFT JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum\nWHERE c.relname = 'orders' AND n.nspname = 'public'\n  AND a.attnum > 0 AND NOT a.attisdropped\nORDER BY a.attnum;"},{"sql":"SHOW COLUMNS FROM orders;"}],"see_also":["describe-table-columns","list-primary-keys","find-identity-columns"],"faqs":[{"question":"Why do I see dropped columns in the pg_attribute version?","answer":"Postgres implements DROP COLUMN by marking the pg_attribute row attisdropped instead of rewriting the table, so the row stays and attnum values of the other columns do not shift. The NOT a.attisdropped filter hides those rows. The space is only reclaimed when the table is rewritten, for example by VACUUM FULL."}]},"source_url":"https://sqlly.app/sql-snippets/list-table-columns","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-table-indexes-columns","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List indexes of a table with their columns","description":"All indexes on one table with the columns they cover and their definitions, across the four engines' native index catalogs.","body":{"slug":"list-table-indexes-columns","name":"List indexes of a table","h1":"List indexes of a table with their columns","category":"schema","lede":"Before adding an index, check what is already there; a second index on the same columns doubles the write cost and buys nothing. This recipe lists every index on one table with the columns it covers.","engine_slug":"postgresql","problem":"A query is slow and you are tempted to add an index, or writes are slow and you suspect too many. Either way, start by seeing exactly which indexes exist and what they cover.","sql":"SELECT indexname AS index_name,\n       indexdef AS definition\nFROM pg_indexes\nWHERE schemaname = 'public' AND tablename = 'users'\nORDER BY indexname;","how_it_works":"pg_indexes is a convenience view over pg_index that renders each index through pg_get_indexdef, so the definition column already includes column list, uniqueness, partial predicates and operator classes. It is the fastest way to eyeball a table's indexing. For column-level detail, join pg_index and unnest indkey the way the foreign-key recipe does.","variants":[{"sql":"SHOW INDEX FROM users;\n-- Seq_in_index gives column position; Column_name the column"},{"sql":"PRAGMA index_list(users);\nPRAGMA index_info(idx_users_email);\n-- run index_info once per index from index_list"},{"sql":"SELECT i.name AS index_name,\n       c.name AS column_name,\n       ic.key_ordinal, ic.is_included_column\nFROM sys.indexes i\nJOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id\nJOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id\nWHERE i.object_id = OBJECT_ID('dbo.Users')\nORDER BY i.name, ic.key_ordinal;"}],"see_also":["duplicate-index-candidates","unused-index-candidates","tables-without-any-index"],"faqs":[{"question":"Why does an index show up that I never created?","answer":"Primary-key and unique constraints are enforced through indexes that the engine creates for you, usually named after the constraint (users_pkey on PostgreSQL, PRIMARY on MySQL, sqlite_autoindex_users_1 on SQLite). MySQL also creates an index on the referencing column of a foreign key if none exists. PostgreSQL never does that, though ORM migrations often add one."},{"question":"Do broken indexes show up in this list?","answer":"Yes: pg_indexes also lists indexes left INVALID by a failed CREATE INDEX CONCURRENTLY, so a name here is not proof of usability. Join pg_index and check indisvalid before trusting the list, and drop and rebuild the invalid ones rather than working around them."}]},"source_url":"https://sqlly.app/sql-snippets/list-table-indexes-columns","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-triggers-on-table","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List triggers on a table","description":"All triggers attached to one table with their firing conditions and source, so mysterious row changes stop being mysterious.","body":{"slug":"list-triggers-on-table","name":"List triggers on a table","h1":"List triggers on a table","category":"schema","lede":"When rows change with no application code to blame, a trigger is usually the culprit. This recipe lists every trigger on one table with its full definition.","engine_slug":"postgresql","problem":"Values in a table change although the codebase issues no matching INSERT or UPDATE. The next thing to inspect is the trigger list on that table.","sql":"SELECT t.tgname AS trigger_name,\n       p.proname AS function_name,\n       pg_get_triggerdef(t.oid) AS definition\nFROM pg_trigger t\nJOIN pg_proc p ON p.oid = t.tgfoid\nWHERE t.tgrelid = 'public.users'::regclass\n  AND NOT t.tgisinternal\nORDER BY t.tgname;","how_it_works":"pg_trigger holds one row per trigger; tgisinternal filters out the system-managed ones such as the internal triggers that enforce foreign keys. pg_get_triggerdef renders the whole CREATE TRIGGER statement, including WHEN and transition-table clauses, and the joined pg_proc gives you the function to inspect next.","variants":[{"sql":"SELECT trigger_name, event_manipulation, action_timing,\n       action_statement\nFROM information_schema.triggers\nWHERE event_object_schema = 'mydb'\n  AND event_object_table = 'users';"},{"sql":"SELECT name, sql\nFROM sqlite_master\nWHERE type = 'trigger' AND tbl_name = 'users';"},{"sql":"SELECT t.name AS trigger_name,\n       OBJECT_NAME(t.parent_id) AS table_name,\n       te.type_desc AS firing_event,\n       sm.definition\nFROM sys.triggers t\nJOIN sys.trigger_events te ON te.object_id = t.object_id\nJOIN sys.sql_modules sm ON sm.object_id = t.object_id\nWHERE t.parent_id = OBJECT_ID('dbo.Users');"}],"see_also":["list-check-constraints","list-table-indexes-columns","describe-table-columns"],"faqs":[{"question":"Why do rows update when no trigger seems to exist?","answer":"Look for foreign keys with ON DELETE CASCADE or ON UPDATE SET NULL pointing at the table, generated columns, rules (PostgreSQL's pg_rules), and triggers on other tables that write into this one. The query above only shows triggers attached to the named table."}]},"source_url":"https://sqlly.app/sql-snippets/list-triggers-on-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-user-privileges","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List a user's privileges","description":"See what a role has been granted: table privileges from information_schema, SHOW GRANTS on MySQL, sys.database_permissions on SQL Server.","body":{"slug":"list-user-privileges","name":"List user privileges","h1":"List a user's privileges","category":"schema","lede":"Access reviews and 'why can't this user read X' questions both start the same way: list what the role can actually do. Each engine has its own view of that.","engine_slug":"postgresql","problem":"Permission denied on a table that should be reachable, or a security questionnaire asking what a service account may do, both need the actual grant list before anything else.","sql":"SELECT table_schema, table_name, privilege_type, is_grantable\nFROM information_schema.table_privileges\nWHERE grantee = 'analyst'\nORDER BY table_schema, table_name, privilege_type;","how_it_works":"information_schema.table_privileges lists grants made directly to the role, and on PostgreSQL only rows the current user is allowed to see. Rights inherited through role membership or PUBLIC do not appear; has_table_privilege('analyst', 'public.orders', 'SELECT') answers the effective question for one table. is_grantable shows whether the role can pass the privilege on. Column-level grants are in information_schema.column_privileges.","variants":[{"sql":"SHOW GRANTS FOR 'analyst'@'%';\n-- also show what the session user has:\nSHOW GRANTS FOR CURRENT_USER();"},{"sql":"SELECT dp.class_desc, dp.state_desc, dp.permission_name,\n       CASE dp.class\n         WHEN 0 THEN DB_NAME()\n         WHEN 1 THEN OBJECT_SCHEMA_NAME(dp.major_id) + '.'\n                     + OBJECT_NAME(dp.major_id)\n         WHEN 3 THEN SCHEMA_NAME(dp.major_id)\n       END AS securable\nFROM sys.database_permissions dp\nWHERE dp.grantee_principal_id = DATABASE_PRINCIPAL_ID('analyst')\nORDER BY dp.class, securable;"},{"sql":"-- SQLite has no users or GRANT; whoever can open the file\n-- can read it, so access is controlled by file permissions"}],"see_also":["grant-select-all-tables","revoke-all-privileges","default-privileges-future-tables"],"faqs":[{"question":"The user can read a table but no grant shows up. Why?","answer":"The access is inherited. On PostgreSQL the role may be a member of another role that holds the grant, or the grant went to PUBLIC; on SQL Server it may come through a database role, a Windows or Entra group, or the dbo user. Check pg_auth_members or sys.database_role_members, and on SQL Server run SELECT * FROM fn_my_permissions('dbo.Orders', 'OBJECT') while impersonating the user with EXECUTE AS USER."}]},"source_url":"https://sqlly.app/sql-snippets/list-user-privileges","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/list-views-definitions","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List views and their definitions","description":"Every view in a schema with the SQL that defines it, so you can see which business logic lives in the database layer.","body":{"slug":"list-views-definitions","name":"List views and definitions","h1":"List views and their definitions","category":"schema","lede":"Views accumulate quietly and hide logic nobody remembers writing. This recipe lists every view in a schema with the full SQL that defines it.","engine_slug":"postgresql","problem":"A report returns numbers nobody can trace to a base table, or a column change is planned and you must know which views reference it. Read the definitions.","sql":"SELECT schemaname, viewname, viewowner, definition\nFROM pg_views\nWHERE schemaname = 'public'\nORDER BY viewname;","how_it_works":"pg_views renders each view's stored SELECT through pg_get_viewdef, so definition is the actual query text you could re-run. viewowner matters for permission debugging because a view reads its base tables with the owner's privileges unless it was created WITH (security_invoker = true), available since PostgreSQL 15. Materialized views are not in pg_views; they are listed in pg_matviews.","variants":[{"sql":"SELECT s.name AS schema_name, v.name AS view_name,\n       sm.definition\nFROM sys.views v\nJOIN sys.schemas s ON s.schema_id = v.schema_id\nJOIN sys.sql_modules sm ON sm.object_id = v.object_id\nORDER BY v.name;"},{"sql":"SHOW FULL TABLES IN mydb WHERE table_type = 'VIEW';\n-- then per view:\nSHOW CREATE VIEW myview;"},{"sql":"SELECT name, sql\nFROM sqlite_master\nWHERE type = 'view'\nORDER BY name;"}],"see_also":["list-materialized-views-refresh","list-table-columns","list-check-constraints"],"faqs":[{"question":"Why is the view definition cut off?","answer":"Usually the client is clipping a long column, so export the result to a file or call pg_get_viewdef('myview'::regclass, true) on its own. In SQL Server, sys.sql_modules.definition is nvarchar(max) and holds the full text; INFORMATION_SCHEMA.VIEWS.VIEW_DEFINITION stops at 4000 characters, and SSMS grid output is also truncated by default."}]},"source_url":"https://sqlly.app/sql-snippets/list-views-definitions","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/lock-waits-summary","corpus":"sql-snippets","engine":"mysql","language":"en","title":"Summarize current lock waits in MySQL","description":"Uses sys.innodb_lock_waits to show every InnoDB lock wait with the waiting and blocking statements, lock modes, ages and the KILL statements to end the blocker.","body":{"slug":"lock-waits-summary","name":"Lock waits summary","h1":"Summarize current lock waits in MySQL","category":"monitoring","lede":"Who is waiting, on which table and index, blocked by whom and for how long: one sys schema view answers all of it.","engine_slug":"mysql","problem":"In MySQL 8.0 and later, sys.innodb_lock_waits joins performance_schema.data_lock_waits and data_locks with information_schema.INNODB_TRX into one report: each waiting InnoDB transaction, the table and index it is stuck on, the lock modes on both sides, the blocking transaction, both statements, and the processlist ids you would pass to KILL.","sql":"SELECT wait_age_secs,\n       locked_table, locked_index, locked_type,\n       waiting_pid, waiting_lock_mode, waiting_query,\n       blocking_pid, blocking_lock_mode, blocking_query, blocking_trx_started,\n       sql_kill_blocking_query, sql_kill_blocking_connection\nFROM sys.innodb_lock_waits\nORDER BY wait_age_secs DESC;","how_it_works":"Each row is one waiting lock request paired with a lock that blocks it. wait_age_secs is how long it has waited. locked_table and locked_index say where the contention is; locked_index = PRIMARY means rows of the clustered index. The lock modes show the conflict, for example X,REC_NOT_GAP waiting on X,REC_NOT_GAP for two updates of the same row, or a GAP lock where an insert hits another transaction's range lock. blocking_trx_started shows whether the blocker is an old transaction. The last two columns are ready-made KILL QUERY and KILL statements; KILL QUERY only stops the current statement, while KILL ends the connection and rolls back its whole transaction. innodb_lock_wait_timeout (50 seconds by default) ends the waiter with an error if nobody acts.","variants":[{"sql":"SELECT w.REQUESTING_ENGINE_TRANSACTION_ID AS waiting_trx,\n       w.BLOCKING_ENGINE_TRANSACTION_ID AS blocking_trx,\n       wt.PROCESSLIST_ID AS waiting_pid, bt.PROCESSLIST_ID AS blocking_pid,\n       r.OBJECT_SCHEMA, r.OBJECT_NAME AS locked_table, r.INDEX_NAME AS locked_index,\n       r.LOCK_MODE AS waiting_mode, b.LOCK_MODE AS blocking_mode\nFROM performance_schema.data_lock_waits w\nJOIN performance_schema.data_locks r ON r.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID\nJOIN performance_schema.data_locks b ON b.ENGINE_LOCK_ID = w.BLOCKING_ENGINE_LOCK_ID\nJOIN performance_schema.threads wt ON wt.THREAD_ID = w.REQUESTING_THREAD_ID\nJOIN performance_schema.threads bt ON bt.THREAD_ID = w.BLOCKING_THREAD_ID\nORDER BY waiting_trx;"}],"see_also":["who-blocks-whom","blocking-queries","long-transactions"],"faqs":[{"question":"A blocker shows no query. What does that mean?","answer":"blocking_query is NULL when the blocking connection is idle: its transaction is open but it is not running a statement. That is usually an application that did some writes and never committed, or a person who ran BEGIN in a client and walked away. blocking_trx_started gives its age. To see what it ran, look up its thread in performance_schema.events_statements_history, which keeps the last few statements per thread by default."},{"question":"How do I reduce lock waits overall?","answer":"Commit sooner, and never wait on a user or a remote call inside a transaction. Update rows in a consistent order, such as by primary key, so transactions queue instead of deadlocking. Index the columns in UPDATE and DELETE WHERE clauses: InnoDB locks every index record it scans, so an unindexed UPDATE can lock most of the table. Under REPEATABLE READ (the default), range conditions also take gap locks that block inserts; READ COMMITTED takes far fewer of them, if the application can live with its semantics."}]},"source_url":"https://sqlly.app/sql-snippets/lock-waits-summary","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/long-transactions","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find long-running transactions in PostgreSQL","description":"Lists every session inside a transaction, oldest first, to catch the open transactions that hold locks and stop vacuum from cleaning up dead rows.","body":{"slug":"long-transactions","name":"Long transactions","h1":"Find long-running transactions in PostgreSQL","category":"monitoring","lede":"A transaction open for hours never shows up in a query plan, but it holds its locks and stops vacuum cleaning up. Find them in one query.","engine_slug":"postgresql","problem":"The damage from a long transaction is indirect. While it stays open, VACUUM cannot remove row versions that its snapshot might still need, so dead rows pile up and tables bloat. It keeps every lock it has taken, so other sessions queue behind it. On a standby with hot_standby_feedback = on, a long query there holds back cleanup on the primary in the same way. pg_stat_activity shows when each transaction started in xact_start, and backend_xmin shows how far back its snapshot reaches.","sql":"SELECT pid, usename, datname, application_name, state,\n       now() - xact_start AS xact_age,\n       now() - state_change AS state_age,\n       age(backend_xmin) AS xmin_age_xids,\n       LEFT(query, 120) AS last_or_current_query\nFROM pg_stat_activity\nWHERE xact_start IS NOT NULL\n  AND pid <> pg_backend_pid()\nORDER BY xact_start\nLIMIT 25;","how_it_works":"Every session inside a transaction, active or idle, has a non-null xact_start; state_change tells you how long it has sat in its current state, which separates an actively working long transaction from an idle one that forgot to commit. xmin_age_xids is how many transaction ids old the session's snapshot is; the session with the largest value is the one holding back vacuum. state = 'idle in transaction' rows with a large xact_age are the ones to raise with the application team. An application that opens a transaction, runs a fast query, and then waits for a user or a remote API before committing looks exactly like this.","variants":[{"sql":"SELECT relname, n_dead_tup,\n       pg_size_pretty(pg_total_relation_size(relid)) AS table_size\nFROM pg_stat_user_tables\nWHERE n_dead_tup > 10000\nORDER BY n_dead_tup DESC\nLIMIT 10;"},{"sql":"SELECT trx_id, trx_state, trx_started,\n       TIMESTAMPDIFF(SECOND, trx_started, NOW()) AS age_seconds,\n       trx_rows_locked, trx_rows_modified,\n       trx_mysql_thread_id AS processlist_id\nFROM information_schema.INNODB_TRX\nORDER BY trx_started\nLIMIT 25;"}],"see_also":["idle-in-transaction","autovacuum-status","who-blocks-whom"],"faqs":[{"question":"How long is too long for a transaction?","answer":"For OLTP work, transactions should take milliseconds to seconds. Anything open for more than a few minutes deserves a look, and anything over an hour is costing you: for that whole time vacuum cannot remove dead rows newer than its snapshot in any table it could see. Long read-only reports belong on a replica, or should be split into shorter transactions."},{"question":"How do I set a hard cap on idle transactions?","answer":"Set idle_in_transaction_session_timeout (per role or globally), which terminates sessions sitting idle inside a transaction past the limit. statement_timeout does not cover this case: it only bounds statement execution, not the gaps between statements inside a transaction."}]},"source_url":"https://sqlly.app/sql-snippets/long-transactions","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/longest-running-queries-now","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find the longest-running queries right now in PostgreSQL","description":"Shows every active query ordered by how long it has been running, with its wait event and transaction age, for the first look during a slowdown.","body":{"slug":"longest-running-queries-now","name":"Longest running queries","h1":"Find the longest-running queries right now in PostgreSQL","category":"monitoring","lede":"What is running right now, ranked by duration, with the exact text and wait state. The snapshot you need mid-incident.","engine_slug":"postgresql","problem":"During a slowdown you need to know what is executing at this instant. pg_stat_activity reports one row per server session with its current or last query, when it started, and what it is waiting on. wait_event_type and wait_event name the lock, I/O or IPC wait; both are NULL when the backend is running on CPU.","sql":"SELECT pid,\n       usename, datname, application_name, client_addr,\n       state,\n       wait_event_type, wait_event,\n       now() - query_start AS running_for,\n       now() - xact_start AS xact_age,\n       LEFT(query, 140) AS query\nFROM pg_stat_activity\nWHERE state = 'active'\n  AND pid <> pg_backend_pid()\nORDER BY query_start\nLIMIT 25;","how_it_works":"Each pg_stat_activity row carries the session's state (active, idle, idle in transaction), the query text, and two clocks: query_start for when the current statement began and xact_start for when its transaction began. A transaction can hold locks far longer than any single statement runs. When xact_age is much larger than running_for, the session has run earlier statements in the same transaction and may be holding their locks. wait_event_type = 'Lock' means the query is blocked by another session, and the who-blocks-whom recipe names the blocker. The pg_backend_pid() exclusion keeps this query out of its own results.","variants":[{"sql":"SELECT pid, usename, datname, state,\n       now() - xact_start AS xact_age,\n       now() - state_change AS idle_for,\n       LEFT(query, 100) AS last_query\nFROM pg_stat_activity\nWHERE state IN ('active', 'idle in transaction', 'idle in transaction (aborted)')\n  AND pid <> pg_backend_pid()\nORDER BY COALESCE(xact_start, state_change);"},{"sql":"SELECT r.session_id, r.blocking_session_id, r.wait_type, r.wait_time,\n       r.start_time, r.status,\n       LEFT(t.text, 140) AS query\nFROM sys.dm_exec_requests r\nJOIN sys.dm_exec_sessions s ON s.session_id = r.session_id\nCROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t\nWHERE s.is_user_process = 1\n  AND r.session_id <> @@SPID\nORDER BY r.start_time;"}],"see_also":["idle-in-transaction","who-blocks-whom","kill-query-safely"],"faqs":[{"question":"A query has been running for hours. Should I kill it?","answer":"Check what it is doing first. If wait_event_type is Lock, it is waiting on someone else's lock and cancelling it frees nothing; find the blocker instead. If it is doing real work, find out who owns it, because cancelling a four-hour batch at hour three throws the work away. pg_cancel_backend(pid) stops the statement and keeps the connection; the kill-a-query recipe has the checklist."},{"question":"Why does idle in transaction show up here but state is not active?","answer":"The main query only shows state = 'active'. A session can be inside an open transaction without running anything: the application ran BEGIN and a few statements and then went quiet. Those sessions hold their locks and their snapshot, which is why the variant lists them alongside active queries."}]},"source_url":"https://sqlly.app/sql-snippets/longest-running-queries-now","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/make-column-not-null-safely","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Make a column NOT NULL safely","description":"Check for NULLs, backfill them, then enforce NOT NULL, plus the CHECK-constraint route that avoids a long exclusive lock on big PostgreSQL tables.","body":{"slug":"make-column-not-null-safely","name":"Make a column NOT NULL safely","h1":"Make a column NOT NULL safely","category":"schema","lede":"Adding NOT NULL to a column that still holds NULLs fails immediately, and adding it while some code path still writes NULLs breaks those inserts later. Check, backfill, then enforce.","engine_slug":"postgresql","problem":"The column should always carry a value, but switching the constraint on in one step either trips over the rows that lack one or locks a big table for the scan. Work up to it in stages.","sql":"-- 1. find offending rows\nSELECT id FROM users WHERE last_name IS NULL;\n\n-- 2. backfill them (choose the right value for your data)\nUPDATE users SET last_name = '' WHERE last_name IS NULL;\n\n-- 3. enforce\nALTER TABLE users\n  ALTER COLUMN last_name SET NOT NULL;","how_it_works":"Step 1 shows how many rows are affected before anything changes; step 2 decides what a missing value means (empty string, a sentinel, or deleting the rows). Step 3 fails if any NULL is left, and on PostgreSQL it scans the whole table while holding an ACCESS EXCLUSIVE lock, so reads and writes wait for the scan. On PostgreSQL 12+ the big-table path is a CHECK (col IS NOT NULL) added NOT VALID and validated under a weaker lock; SET NOT NULL then sees the valid constraint and skips its own scan.","variants":[{"sql":"ALTER TABLE users\n  ADD CONSTRAINT users_last_name_required\n  CHECK (last_name IS NOT NULL) NOT VALID;\nALTER TABLE users VALIDATE CONSTRAINT users_last_name_required;\n-- SET NOT NULL now skips the table scan (PostgreSQL 12+)\nALTER TABLE users ALTER COLUMN last_name SET NOT NULL;\nALTER TABLE users DROP CONSTRAINT users_last_name_required;"},{"sql":"-- fails if NULLs exist; backfill first\nALTER TABLE dbo.Users\n    ALTER COLUMN LastName NVARCHAR(100) NOT NULL;\n-- note: ALTER COLUMN restates the full type"},{"sql":"UPDATE users SET last_name = '' WHERE last_name IS NULL;\nALTER TABLE users\n  MODIFY COLUMN last_name VARCHAR(100) NOT NULL;\n-- MODIFY restates the type. Strict mode makes the ALTER fail\n-- on leftover NULLs; without it they silently become empty strings"}],"see_also":["change-column-nullable","set-column-default","add-foreign-key-if-missing"],"faqs":[{"question":"Why did my NOT NULL change time out on a busy table?","answer":"ALTER COLUMN ... SET NOT NULL needs an ACCESS EXCLUSIVE lock. It first waits for every running query on the table, and every new query queues behind it, then it holds the lock for the full scan. Set lock_timeout so the attempt gives up instead of stalling traffic, and use the CHECK-constraint route so the scan happens under a lock that does not block reads or writes."}]},"source_url":"https://sqlly.app/sql-snippets/make-column-not-null-safely","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/mask-card-numbers","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Mask payment card numbers in SQL (show last 4)","description":"Display '************4242' by hiding everything except the last four digits of a card or account number.","body":{"slug":"mask-card-numbers","name":"Mask card numbers","h1":"Mask payment card numbers in SQL (show last 4)","category":"text","lede":"Support screens and exports must never show a full card number. Keep the last four for identification.","engine_slug":"postgresql","problem":"Show agents enough of the card to identify it. Everything before the last four digits becomes asterisks.","sql":"SELECT repeat('*', GREATEST(length(card_no) - 4, 0)) || right(card_no, 4) AS card_masked\nFROM payment_methods;","how_it_works":"right(card_no, 4) keeps the final four characters, repeat('*') pads the remainder to the original length, and GREATEST guards very short values from a negative repeat count. The result is a string, so the masked column is for display only and never round-trips.","variants":[{"sql":"SELECT REPLICATE('*', IIF(LEN(card_no) > 4, LEN(card_no) - 4, 0)) + RIGHT(card_no, 4) AS card_masked\nFROM payment_methods;"},{"sql":"SELECT CASE WHEN LENGTH(card_no) > 4\n            THEN LPAD(SUBSTR(card_no, -4), LENGTH(card_no), '*')\n            ELSE card_no END AS card_masked\nFROM payment_methods;"},{"sql":"SELECT CONCAT(REPEAT('*', GREATEST(LENGTH(card_no) - 4, 0)), RIGHT(card_no, 4)) AS card_masked\nFROM payment_methods;"}],"see_also":["mask-email-address","hash-values-md5-sha"],"faqs":[{"question":"Is masking enough to make data safe?","answer":"No. Masking is display-only. If the underlying column should not be readable at all, store only a hash or a token, or encrypt and control keys. Masking in the query does nothing when someone can read the table directly."}]},"source_url":"https://sqlly.app/sql-snippets/mask-card-numbers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/mask-email-address","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Mask an email address in SQL for display","description":"Turn 'jane.doe@example.com' into 'j***@example.com' so support staff see the shape without the address.","body":{"slug":"mask-email-address","name":"Mask an email address","h1":"Mask an email address in SQL for display","category":"text","lede":"Privacy rules often let you show the first letter and domain but not the full local part.","engine_slug":"postgresql","problem":"Show the first letter and the domain, hide the rest of the local part with asterisks.","sql":"SELECT left(email, 1) || '***@' || split_part(email, '@', 2) AS email_masked\nFROM users;","how_it_works":"left(email, 1) keeps the first character of the local part, and split_part recovers the domain after the @. Concatenating the fixed '***@' between them yields a display form that cannot be reversed to the original address, as long as the local part had more than one character.","variants":[{"sql":"SELECT LEFT(email, 1) + '***@' + RIGHT(email, CHARINDEX('@', REVERSE(email) + '@') - 1) AS email_masked\nFROM users;"},{"sql":"SELECT CONCAT(LEFT(email, 1), '***@', SUBSTRING_INDEX(email, '@', -1)) AS email_masked\nFROM users;"}],"see_also":["extract-domain-from-email","mask-card-numbers"],"faqs":[{"question":"Should the mask length match the real local part?","answer":"Some policies prefer a fixed-width mask so the mask itself leaks nothing about length. If that matters to you, emit a constant '***' (as here) rather than one star per hidden character."}]},"source_url":"https://sqlly.app/sql-snippets/mask-email-address","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/mask-names","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Mask names in query results","description":"Keep the first letter and asterisk out the rest at SELECT time, masking without touching stored data.","body":{"slug":"mask-names","name":"Mask names","h1":"Mask names in query results","category":"data-quality","lede":"Build the masked value in the SELECT list with string functions: first letter kept, the remainder replaced by asterisks.","engine_slug":"postgresql","problem":"Support staff need to see who a record is without reading full names. Masking in the query means the stored data stays intact and only the exposed view changes.","sql":"SELECT id,\n       LEFT(TRIM(name), 1) || REPEAT('*', GREATEST(LENGTH(TRIM(name)) - 1, 0)) AS masked_name\nFROM customers\nWHERE name IS NOT NULL\nORDER BY id;","how_it_works":"LEFT(name, 1) keeps the initial; REPEAT('*', length - 1) builds a mask for the rest, and GREATEST(..., 0) stops an empty name from asking for a negative repeat count. The same expression works on MySQL with CONCAT in place of || and CHAR_LENGTH in place of LENGTH, because MySQL's LENGTH counts bytes and would over-mask accented names. In the SQL Server variant, REPLICATE with a negative count returns NULL, so an empty name comes back as NULL rather than an empty mask. Because the mask is built at read time, nothing is destroyed; run the same query without the expression to see real names when you have the rights to.","variants":[{"sql":"SELECT id,\n       LEFT(TRIM(name), 1) + REPLICATE('*', LEN(TRIM(name)) - 1) AS masked_name\nFROM customers\nWHERE name IS NOT NULL;"},{"sql":"SELECT id,\n       REPEAT('*', GREATEST(LENGTH(TRIM(name)) - 2, 0))\n         || RIGHT(TRIM(name), 2) AS masked_name\nFROM customers\nWHERE name IS NOT NULL;"}],"see_also":["anonymize-emails","find-control-characters"],"faqs":[{"question":"Is SELECT-time masking enough for privacy?","answer":"It is exactly the right tool when viewers may see presence but not content, because the source of truth never changes and no cleanup job can leak. It is not enough for copies that leave the database: exports, logs and backups still carry the real values, and those need true anonymization (the anonymize-emails recipe) or access control at the copy step."}]},"source_url":"https://sqlly.app/sql-snippets/mask-names","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/median-per-group","corpus":"sql-snippets","engine":"all","language":"en","title":"Median per group","description":"Compute the median order amount per customer portably with ROW_NUMBER and COUNT, no PERCENTILE_CONT needed.","body":{"slug":"median-per-group","name":"Median per group","h1":"Median per group","category":"querying","lede":"Average the middle row (or two) per group: the median that runs on every engine.","engine_slug":"all","problem":"Averages lie when one whale order skews the mean. You want the median amount per customer, and PERCENTILE_CONT is not available on your engine.","sql":"WITH ordered AS (\n  SELECT customer_id, amount,\n         ROW_NUMBER() OVER (PARTITION BY customer_id\n                            ORDER BY amount) AS rn,\n         COUNT(*)    OVER (PARTITION BY customer_id) AS n\n  FROM orders\n)\nSELECT customer_id,\n       AVG(amount) AS median_amount\nFROM ordered\nWHERE 2 * rn IN (n, n + 1, n + 2)\nGROUP BY customer_id\nORDER BY customer_id;","how_it_works":"Each row learns its position (rn) and its group size (n). The test 2 * rn IN (n, n + 1, n + 2) keeps the single middle row when n is odd (2 * rn = n + 1) and the two middle rows when n is even (2 * rn = n and n + 2), and the outer AVG averages them. It avoids dividing, because MySQL and Oracle return 2.5 for 5 / 2 where the other engines return 2, which makes the usual (n + 1) / 2 formula pick the wrong rows on even groups. On SQL Server, AVG of an integer column returns an integer and would round 2.5 down to 2, so write AVG(amount * 1.0) there if amount is an integer.","variants":[{"sql":"SELECT customer_id,\n       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) AS median_amount\nFROM orders\nGROUP BY customer_id;"}],"see_also":["percentile-buckets","ntile-deciles","rank-within-category"],"faqs":[{"question":"Median of an even-sized group: middle two or lower?","answer":"Convention here is the mean of the two middle values, which matches PERCENTILE_CONT(0.5). For the lower middle (PERCENTILE_DISC(0.5) behaviour) change the filter to 2 * rn IN (n, n + 1). SQL Server only has PERCENTILE_CONT as a window function, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) OVER (PARTITION BY customer_id), and Oracle also offers MEDIAN(amount)."}]},"source_url":"https://sqlly.app/sql-snippets/median-per-group","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/migration-diff-preview","corpus":"sql-snippets","engine":"all","language":"en","title":"Preview a migration diff between tables","description":"Before cutover, list rows present in only one of old and new, plus rows whose values changed.","body":{"slug":"migration-diff-preview","name":"Migration diff","h1":"Preview a migration diff between tables","category":"data-quality","lede":"A symmetric difference shows rows added or dropped by the migration; a per-key join shows rows the migration rewrote.","engine_slug":"all","problem":"The migration copied orders into orders_new with a schema change. Before switching reads over, you need the diff: rows that did not make it, rows that appeared from nowhere, and rows whose values were transformed.","sql":"SELECT MIN(source) AS present_in, id, status, total\nFROM (\n  SELECT id, status, total, 'old' AS source FROM orders_old\n  UNION ALL\n  SELECT id, status, total, 'new' AS source FROM orders_new\n) combined\nGROUP BY id, status, total\nHAVING COUNT(*) = 1\nORDER BY id, present_in;","how_it_works":"Union both tables with a source tag, group by every column, and keep groups of 1: rows found on one side only. present_in names the side. Rows that the migration legitimately changed (a type conversion, a default applied) show up here too. The per-key join variant tells the two cases apart. The opening GROUP BY here is the symmetric-difference-two-tables query aimed at a migration pair.","variants":[{"sql":"SELECT o.id,\n       o.status AS old_status, n.status AS new_status,\n       o.total AS old_total, n.total AS new_total\nFROM orders_old o\nJOIN orders_new n ON n.id = o.id\nWHERE o.status <> n.status OR o.total <> n.total\nORDER BY o.id;"},{"sql":"SELECT o.id\nFROM orders_old o\nWHERE NOT EXISTS (\n  SELECT 1 FROM orders_new n WHERE n.id = o.id\n)\nORDER BY o.id;"}],"see_also":["symmetric-difference-two-tables","compare-table-counts","id-remap-preview"],"faqs":[{"question":"The diff is non-empty. Is the migration wrong?","answer":"Not necessarily: transformations are the point of many migrations. What matters is that every diff row is expected. Group the findings into explained (documented transformation) and unexplained (bug), and gate the cutover on an empty unexplained set, not on an empty diff."},{"question":"Why does every row holding an empty string show as changed after moving to Oracle?","answer":"Oracle stores an empty string as NULL, so a value that moved from '' to NULL is a genuine difference to the GROUP BY even though nothing visible changed. Normalize empties to NULL on the source side before comparing, or expect and accept that diff line."}]},"source_url":"https://sqlly.app/sql-snippets/migration-diff-preview","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/migration-lock-row-recipe","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Migration lock row recipe","description":"A lock table that lets only one runner migrate at a time: claim a row with ON CONFLICT DO NOTHING, keep it while you work, delete it to release.","body":{"slug":"migration-lock-row-recipe","name":"Migration lock row","h1":"Migration lock row recipe","category":"schema","lede":"Two deploy pipelines migrating the same database at once is how schemas half-apply. A lock row in the database makes runners serialize, with no external infrastructure.","engine_slug":"postgresql","problem":"Two deploy jobs started together and both began altering the same schema. The runners need a mutual lock that lives in the database rather than in a separate coordinator.","sql":"CREATE TABLE IF NOT EXISTS migration_lock (\n    lock_name   text PRIMARY KEY,\n    acquired_at timestamptz NOT NULL DEFAULT now(),\n    owner       text NOT NULL\n);\n\n-- try to claim the lock: a row back means we got it,\n-- no row means someone else holds it\nINSERT INTO migration_lock (lock_name, owner)\nVALUES ('default', 'runner-7')\nON CONFLICT (lock_name) DO NOTHING\nRETURNING owner, acquired_at;\n\n-- see who holds it and since when\nSELECT owner, acquired_at FROM migration_lock WHERE lock_name = 'default';\n\n-- release when done\nDELETE FROM migration_lock WHERE lock_name = 'default' AND owner = 'runner-7';","how_it_works":"The INSERT is the lock: the primary key lets exactly one runner's row in, and for everyone else ON CONFLICT DO NOTHING inserts nothing, so RETURNING comes back empty. Run the INSERT in its own committed transaction so other runners can see the row. Releasing is the DELETE, guarded by owner so a runner cannot remove someone else's claim. A crashed runner never deletes its row, so treat claims older than a timeout as abandoned. Run each migration in a transaction where the engine allows it; MySQL commits DDL implicitly, so a failed migration there can stop halfway.","variants":[{"sql":"INSERT IGNORE INTO migration_lock (lock_name, owner)\nVALUES ('default', 'runner-7');\nSELECT ROW_COUNT();  -- 1 = claimed, 0 = already held\n-- release:\nDELETE FROM migration_lock\nWHERE lock_name = 'default' AND owner = 'runner-7';"},{"sql":"-- UPDLOCK, HOLDLOCK stops two runners passing the NOT EXISTS\n-- check at the same moment; the PK on LockName backs it up\nINSERT INTO dbo.MigrationLock (LockName, Owner)\nSELECT 'default', 'runner-7'\nWHERE NOT EXISTS (\n    SELECT 1 FROM dbo.MigrationLock WITH (UPDLOCK, HOLDLOCK)\n    WHERE LockName = 'default');\nSELECT @@ROWCOUNT AS claimed;  -- 1 = claimed, 0 = held elsewhere"}],"see_also":["schema-version-table-recipe","create-table-if-not-exists","make-column-not-null-safely"],"faqs":[{"question":"Why not use GET_LOCK or sp_getapplock instead?","answer":"Often you should. GET_LOCK, sp_getapplock and PostgreSQL's pg_advisory_lock are released automatically when the session ends, so a crashed runner can never leave a stale lock. They only last as long as one connection, though, and tell you little about the holder beyond a session id. A lock row records who took it and when, and survives across connections, at the cost of cleaning up after crashed runners yourself."}]},"source_url":"https://sqlly.app/sql-snippets/migration-lock-row-recipe","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/missing-fk-index-candidates","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find foreign keys without a supporting index in PostgreSQL","description":"Finds FK constraints whose referencing column has no index with that column as its leading key, the setup that turns parent deletes into full scans.","body":{"slug":"missing-fk-index-candidates","name":"Missing FK index candidates","h1":"Find foreign keys without a supporting index in PostgreSQL","category":"indexes","lede":"PostgreSQL does not index foreign keys for you. Every unindexed FK means every parent delete or update scans the child table.","engine_slug":"postgresql","problem":"When you delete a parent row, PostgreSQL must verify no child rows reference it. With an index on the child FK column this is a cheap index probe; without one it is a sequential scan of the entire child table, run inside your delete transaction while it holds locks. Small child tables hide the problem for months until the data grows.","sql":"SELECT c.conrelid::regclass AS child_table,\n       c.conname AS fk_name,\n       (SELECT string_agg(quote_ident(a.attname), ', ' ORDER BY k.ord)\n        FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord)\n        JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum) AS fk_columns,\n       pg_size_pretty(pg_total_relation_size(c.conrelid)) AS child_table_size\nFROM pg_constraint c\nWHERE c.contype = 'f'\n  AND NOT EXISTS (\n    SELECT 1 FROM pg_index i\n    WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1]\n  )\nORDER BY pg_total_relation_size(c.conrelid) DESC;","how_it_works":"pg_constraint holds every FK, and conkey is the array of referencing-column numbers in constraint order. The NOT EXISTS looks for any index on the child table whose first column (indkey[0]) is the FK's first column (conkey[1]); note that indkey counts from 0 and conkey, a normal array, from 1. An index that leads with the FK's first column lets the check seek. The subquery turns conkey back into a quoted column list, and sorting by child table size puts the potentially painful ones first. The missing-fk-index-ddl page is the SQL Server twin and names each PostgreSQL index explicitly in its generated statements.","variants":[{"sql":"SELECT format('CREATE INDEX CONCURRENTLY ON %s (%s);',\n              c.conrelid::regclass,\n              (SELECT string_agg(quote_ident(a.attname), ', ' ORDER BY k.ord)\n               FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord)\n               JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum)) AS create_statement\nFROM pg_constraint c\nWHERE c.contype = 'f'\n  AND NOT EXISTS (\n    SELECT 1 FROM pg_index i\n    WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1]\n  )\nORDER BY 1;"},{"sql":"SELECT OBJECT_NAME(fk.parent_object_id) AS child_table, fk.name AS fk_name\nFROM sys.foreign_keys fk\nJOIN sys.foreign_key_columns fkc\n  ON fkc.constraint_object_id = fk.object_id AND fkc.constraint_column_id = 1\nWHERE NOT EXISTS (\n    SELECT 1 FROM sys.index_columns ic\n    WHERE ic.object_id = fkc.parent_object_id AND ic.column_id = fkc.parent_column_id AND ic.key_ordinal = 1\n)\nORDER BY child_table, fk_name;"}],"see_also":["missing-fk-index-ddl","table-scan-detector","unused-indexes"],"faqs":[{"question":"Multi-column foreign keys: does this catch them?","answer":"Yes. It tests whether some index leads with the FK's first column, which is what lets the check seek; for an FK on (order_id, line_no), an index starting with order_id passes. The generated CREATE INDEX lists every FK column in constraint order, so a flagged two-column FK gets a two-column index."},{"question":"Why CREATE INDEX CONCURRENTLY?","answer":"A plain CREATE INDEX takes a SHARE lock that blocks inserts, updates and deletes on the child table until the build finishes. CONCURRENTLY lets writes continue, takes longer, and cannot run inside a transaction block. If it fails partway it leaves an INVALID index behind, which you drop and retry."}]},"source_url":"https://sqlly.app/sql-snippets/missing-fk-index-candidates","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/missing-fk-index-ddl","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Generate DDL for missing foreign-key indexes in SQL Server","description":"Finds foreign keys whose leading column starts no index and prints a CREATE INDEX statement for each one, ready to review and run.","body":{"slug":"missing-fk-index-ddl","name":"Missing FK index DDL","h1":"Generate DDL for missing foreign-key indexes in SQL Server","category":"indexes","lede":"SQL Server does not index foreign-key columns for you. This walks the catalog views and prints a CREATE INDEX for every foreign key that no index leads with.","engine_slug":"sql-server","problem":"Deleting a parent row (or changing its key) makes SQL Server check every child table that references it. With an index on the child's FK column that check is a seek; without one it is a scan of the child table, run inside the delete and holding locks while it runs. Joins on the FK column pay the same price. Creating a FOREIGN KEY constraint does not create an index, so after a few years of migrations nobody knows which FK columns have one.","sql":"SELECT 'CREATE INDEX ' + QUOTENAME('ix_' + tb.name + '_' + COL_NAME(lead_col.parent_object_id, lead_col.parent_column_id)) + ' ON '\n       + QUOTENAME(SCHEMA_NAME(tb.schema_id)) + '.' + QUOTENAME(tb.name)\n       + ' (' + cols.list + ');' AS create_statement,\n       tb.name AS child_table,\n       fk.name AS fk_name,\n       cols.list AS fk_columns,\n       OBJECT_NAME(fk.referenced_object_id) AS parent_table\nFROM sys.foreign_keys fk\nJOIN sys.tables tb ON tb.object_id = fk.parent_object_id\nJOIN sys.foreign_key_columns lead_col\n  ON lead_col.constraint_object_id = fk.object_id AND lead_col.constraint_column_id = 1\nCROSS APPLY (\n    SELECT STRING_AGG(QUOTENAME(c.name), ', ') WITHIN GROUP (ORDER BY fkc.constraint_column_id) AS list\n    FROM sys.foreign_key_columns fkc\n    JOIN sys.columns c ON c.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_column_id\n    WHERE fkc.constraint_object_id = fk.object_id\n) cols\nWHERE NOT EXISTS (\n    SELECT 1\n    FROM sys.index_columns ic\n    WHERE ic.object_id = fk.parent_object_id\n      AND ic.column_id = lead_col.parent_column_id\n      AND ic.key_ordinal = 1\n)\nORDER BY child_table, fk_name;","how_it_works":"In sys.foreign_keys the referencing (child) table is parent_object_id and the referenced table is referenced_object_id, which reads backwards but is how the catalog names them. sys.foreign_key_columns lists each FK's child columns in order, and constraint_column_id = 1 picks the leading one. The NOT EXISTS looks for any index whose first key column (key_ordinal = 1) is that column: an index on (other_col, fk_col) cannot seek on fk_col. Included columns have key_ordinal 0, so they correctly do not count. STRING_AGG (SQL Server 2017 and later) builds the full column list so a two-column FK gets a two-column index, and QUOTENAME keeps the statements valid for names with spaces or brackets. Review the list before running it; every new index adds write cost. The missing-fk-index-candidates recipe is the PostgreSQL-native twin: it lists the same candidates with table sizes and generates the DDL from there.","variants":[{"sql":"SELECT format('CREATE INDEX CONCURRENTLY %I ON %s (%s);',\n       c.conname || '_fkidx',\n       c.conrelid::regclass,\n       (SELECT string_agg(quote_ident(a.attname), ', ' ORDER BY k.ord)\n        FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord)\n        JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum)) AS create_statement\nFROM pg_constraint c\nWHERE c.contype = 'f'\n  AND NOT EXISTS (\n    SELECT 1 FROM pg_index i\n    WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1]\n  )\nORDER BY pg_total_relation_size(c.conrelid) DESC;"}],"see_also":["missing-fk-index-candidates","missing-index-suggestions","unused-indexes"],"faqs":[{"question":"Why is the first key column the only one that matters?","answer":"The check that runs when you delete a parent row looks up child rows by the FK columns. An index whose first key column is one of them can seek; an index that starts with some other column can only be scanned for that lookup. key_ordinal = 1 in sys.index_columns is the leading-column test. For a multi-column FK an index leading with the first FK column is usually enough, and the generated statement covers all of them."},{"question":"Should I index every FK the query flags?","answer":"No. Index the FK when parent rows get deleted or re-keyed, or when queries join or filter on the column. If the parent table is append-only and nothing joins through that column, the index costs writes and buys nothing. MySQL is different: InnoDB requires an index on foreign-key columns and creates one automatically if none exists, so this check is not needed there."}]},"source_url":"https://sqlly.app/sql-snippets/missing-fk-index-ddl","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/missing-index-suggestions","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Generate CREATE INDEX statements from SQL Server's missing index DMVs","description":"Ranks the optimizer's missing index suggestions by estimated benefit and builds a CREATE INDEX for each: equality columns, then inequality, then INCLUDE.","body":{"slug":"missing-index-suggestions","name":"Missing index suggestions","h1":"Generate CREATE INDEX statements from SQL Server's missing index DMVs","category":"indexes","lede":"Every time the optimizer compiles a plan it wishes had an index, it writes the index down. This reads those notes back as ranked CREATE INDEX statements.","engine_slug":"sql-server","problem":"When SQL Server fully optimizes a query and decides an index that does not exist would have made it cheaper, it records the wish in the missing index DMVs: which columns the query compared with = (equality), which with a range or <> (inequality), which it only selected (included), how many times a plan wanted it and how much cheaper the optimizer thinks the query would be. Reading them is the fastest way to a list of index candidates on a server you do not know. They are raw optimizer notes, though, not advice: they overlap, they ignore the indexes you already have, and following them blindly fills a table with near-duplicate indexes.","sql":"SELECT TOP 25\n    CAST(gs.avg_total_user_cost * gs.avg_user_impact / 100.0 * (gs.user_seeks + gs.user_scans) AS DECIMAL(18,1)) AS improvement_measure,\n    gs.user_seeks + gs.user_scans AS uses,\n    CAST(gs.avg_user_impact AS DECIMAL(5,1)) AS avg_impact_pct,\n    gs.last_user_seek,\n    d.statement AS table_name,\n    d.equality_columns, d.inequality_columns, d.included_columns,\n    'CREATE INDEX ' + QUOTENAME('ix_' + OBJECT_NAME(d.object_id, d.database_id) + '_missing_' + CAST(d.index_handle AS VARCHAR(10)))\n      + ' ON ' + d.statement\n      + ' (' + CONCAT_WS(', ', d.equality_columns, d.inequality_columns) + ')'\n      + ISNULL(' INCLUDE (' + d.included_columns + ')', '') + ';' AS create_statement\nFROM sys.dm_db_missing_index_details d\nJOIN sys.dm_db_missing_index_groups g ON g.index_handle = d.index_handle\nJOIN sys.dm_db_missing_index_group_stats gs ON gs.group_handle = g.index_group_handle\nWHERE d.database_id = DB_ID()\nORDER BY improvement_measure DESC;","how_it_works":"sys.dm_db_missing_index_details has one row per suggested index, with the columns already bracket-quoted and statement holding the three-part table name, which CREATE INDEX accepts for the current database. sys.dm_db_missing_index_groups links each suggestion to its statistics in sys.dm_db_missing_index_group_stats: user_seeks and user_scans count the compilations and executions that would have used it, avg_total_user_cost is the average plan cost of those queries and avg_user_impact the percentage the optimizer expects to save. Their product is the usual ranking figure; it is an estimate in optimizer cost units, useful for ordering, not a time. CONCAT_WS (SQL Server 2017 and later) joins the equality and inequality lists and skips whichever is NULL. The suggestions are kept in memory only: a restart, taking the database offline, or any metadata change on the table, including creating one of the suggested indexes, clears the table's entries. On the instance used to test this page, creating one index removed all four suggestions for that table. Reading the DMVs needs VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE on SQL Server 2022 and later).","variants":[{"sql":"SELECT TOP 20\n    CAST(gsq.avg_total_user_cost * gsq.avg_user_impact / 100.0 * (gsq.user_seeks + gsq.user_scans) AS DECIMAL(18,1)) AS improvement_measure,\n    gsq.user_seeks + gsq.user_scans AS uses,\n    d.statement AS table_name,\n    d.equality_columns, d.inequality_columns, d.included_columns,\n    LEFT(SUBSTRING(st.text, gsq.last_statement_start_offset / 2 + 1,\n         (CASE gsq.last_statement_end_offset WHEN -1 THEN DATALENGTH(st.text)\n               ELSE gsq.last_statement_end_offset END - gsq.last_statement_start_offset) / 2 + 1), 200) AS query_text\nFROM sys.dm_db_missing_index_group_stats_query gsq\nJOIN sys.dm_db_missing_index_groups g ON g.index_group_handle = gsq.group_handle\nJOIN sys.dm_db_missing_index_details d ON d.index_handle = g.index_handle\nCROSS APPLY sys.dm_exec_sql_text(gsq.last_sql_handle) st\nWHERE d.database_id = DB_ID()\nORDER BY improvement_measure DESC;"},{"sql":"SELECT schemaname, relname AS table_name,\n       seq_scan, seq_tup_read,\n       seq_tup_read / NULLIF(seq_scan, 0) AS avg_rows_per_seq_scan,\n       COALESCE(idx_scan, 0) AS idx_scan,\n       n_live_tup\nFROM pg_stat_user_tables\nWHERE seq_scan > 0\n  AND n_live_tup > 10000\nORDER BY seq_tup_read DESC\nLIMIT 20;"},{"sql":"SELECT db, exec_count, no_index_used_count, no_good_index_used_count,\n       rows_examined_avg, rows_sent_avg, total_latency,\n       LEFT(query, 120) AS query\nFROM sys.statements_with_full_table_scans\nWHERE db IS NOT NULL\nORDER BY no_index_used_count DESC\nLIMIT 20;"}],"see_also":["missing-fk-index-ddl","duplicate-indexes","never-scanned-indexes"],"faqs":[{"question":"Can I run the generated statements as they are?","answer":"Not without reading them first. One query often produces several overlapping suggestions: in testing, one query produced both (customer_id, status, created_at) and the same key with INCLUDE (total), and a second query wanted (customer_id, created_at) INCLUDE (total). One index, (customer_id, status, created_at) INCLUDE (total), serves the first query; whether it is worth also building the second depends on how often that query runs. The suggestions also ignore your existing indexes, so check whether widening one of those does the job. The column order inside the equality list is not a recommendation, so put the column that narrows the rows most first, and the optimizer never suggests filtered indexes. Create the merged index, rerun the queries and compare their logical reads."},{"question":"What do PostgreSQL and MySQL offer instead?","answer":"Neither records missing index wishes. In PostgreSQL, the variant finds the tables read mostly by full scans, and pg_stat_statements finds the queries behind them; two optional extensions go further: pg_qualstats records which columns WHERE clauses filter on, and hypopg creates hypothetical indexes that EXPLAIN takes into account without building anything. In MySQL, sys.statements_with_full_table_scans lists the statement digests that used no index (its query column is shortened for display; x$statements_with_full_table_scans has the full digest text), and sys.schema_tables_with_full_table_scans ranks tables by rows read in full scans. In both, EXPLAIN on the candidate query shows whether a new index is used."}]},"source_url":"https://sqlly.app/sql-snippets/missing-index-suggestions","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/missing-parent-references","corpus":"sql-snippets","engine":"all","language":"en","title":"Find missing parent references, both ways","description":"One query that lists children with no usable parent and parents that nothing points at, labeled per side.","body":{"slug":"missing-parent-references","name":"Missing parent refs","h1":"Find missing parent references, both ways","category":"data-quality","lede":"Check a parent-child pair in both directions at once: children whose parent id is NULL or dangling, and parents that no child references.","engine_slug":"all","problem":"You inherited a schema where orders.customer_id is optional and suspect both problems at once: orders with a broken or missing customer link, and customers nobody ever ordered from. One labeled result set beats running two queries.","sql":"SELECT 'child: order with no customer' AS issue,\n       o.id AS row_id, o.customer_id AS related_id\nFROM orders o\nLEFT JOIN customers c ON c.id = o.customer_id\nWHERE c.id IS NULL\nUNION ALL\nSELECT 'parent: customer without orders',\n       c.id, NULL\nFROM customers c\nWHERE NOT EXISTS (\n  SELECT 1 FROM orders o WHERE o.customer_id = c.id\n)\nORDER BY issue, row_id;","how_it_works":"The first branch catches orders where the join to customers found nothing, which includes both NULL customer_ids and dangling ids, since neither can match a parent. The second branch uses NOT EXISTS to find parents that no child references. The literal label column lets you tell the two directions apart after the UNION ALL merges them.","variants":[{"sql":"SELECT 'order with NULL customer_id' AS issue, o.id AS row_id\nFROM orders o\nWHERE o.customer_id IS NULL\nUNION ALL\nSELECT 'order with dangling customer_id', o.id\nFROM orders o\nLEFT JOIN customers c ON c.id = o.customer_id\nWHERE o.customer_id IS NOT NULL AND c.id IS NULL;"}],"see_also":["find-orphaned-rows","referential-audit-both-directions"],"faqs":[{"question":"Is a parent with no children always a problem?","answer":"Not necessarily. A customer who has not ordered yet is normal in many schemas. Treat the parent branch as a candidate list for cleanup, not a defect list. The child branch, on the other hand, is usually a real integrity violation worth fixing before it grows."}]},"source_url":"https://sqlly.app/sql-snippets/missing-parent-references","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/missing-sequence-values","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List missing values in an id sequence","description":"Generate every id between MIN and MAX and keep the ones the table does not have.","body":{"slug":"missing-sequence-values","name":"Missing sequence values","h1":"List missing values in an id sequence","category":"data-quality","lede":"A recursive CTE walks every integer from the smallest to the largest id; an anti-join keeps only the values with no matching row.","engine_slug":"postgresql","problem":"sequence-gap-detection told you there are 37 missing ids in orders; now you need the actual numbers to check archives or restore them.","sql":"WITH RECURSIVE\n  bounds AS (SELECT MIN(id) AS lo, MAX(id) AS hi FROM orders),\n  seq(id) AS (\n    SELECT lo FROM bounds\n    UNION ALL\n    SELECT s.id + 1 FROM seq s, bounds b WHERE s.id < b.hi\n  )\nSELECT s.id AS missing_id\nFROM seq s\nWHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.id = s.id)\nORDER BY s.id;","how_it_works":"bounds reads MIN and MAX once; the recursive member adds 1 until it reaches the maximum, producing every integer in the range, and the NOT EXISTS anti-join drops the ids that exist. This exact statement also runs on MySQL 8.0+ and SQLite. MySQL stops recursion at 1,000 levels by default (cte_max_recursion_depth), so raise that setting for a wider id range.","variants":[{"sql":"WITH bounds AS (SELECT MIN(id) AS lo, MAX(id) AS hi FROM orders),\nseq(id) AS (\n  SELECT lo FROM bounds\n  UNION ALL\n  SELECT s.id + 1 FROM seq s, bounds b WHERE s.id < b.hi\n)\nSELECT s.id AS missing_id\nFROM seq s\nWHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.id = s.id)\nORDER BY s.id\nOPTION (MAXRECURSION 0); -- lifts the 100-level default; Oracle runs the rest without this line"},{"sql":"SELECT missing_id\nFROM generate_series(\n  (SELECT MIN(id) FROM orders),\n  (SELECT MAX(id) FROM orders)\n) AS g(missing_id)\nWHERE NOT EXISTS (\n  SELECT 1 FROM orders o WHERE o.id = g.missing_id\n);"}],"see_also":["sequence-gap-detection","date-gap-detection"],"faqs":[{"question":"How large can the id range be before this gets slow?","answer":"The CTE materializes one row per integer in the range, so a table spanning ids 1 to 10 million generates 10 million sequence rows even if the table is small. For wide, sparse ranges, run sequence-gap-detection first and only enumerate the ranges it reports, or restrict the sequence with a WHERE inside the recursive member."}]},"source_url":"https://sqlly.app/sql-snippets/missing-sequence-values","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/month-over-month-delta","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Month-over-month delta","description":"Compare each month's revenue to the previous month with LAG, including a percentage change.","body":{"slug":"month-over-month-delta","name":"Month-over-month delta","h1":"Month-over-month delta","category":"querying","lede":"LAG walks the previous row of the monthly series; the delta is a subtraction away.","engine_slug":"postgresql","problem":"You want each month's revenue next to the previous month's, the difference, and the percent change, ready for a dashboard.","sql":"WITH monthly AS (\n  SELECT DATE_TRUNC('month', order_date)::date AS month,\n         SUM(amount) AS month_total\n  FROM orders\n  GROUP BY 1\n)\nSELECT month, month_total,\n       month_total - LAG(month_total) OVER (ORDER BY month) AS delta,\n       ROUND(100.0 * (month_total - LAG(month_total) OVER (ORDER BY month))\n             / NULLIF(LAG(month_total) OVER (ORDER BY month), 0), 1) AS pct_change\nFROM monthly\nORDER BY month;","how_it_works":"LAG(month_total) looks one row back in the month-ordered series and returns NULL for the first row, so the delta starts as NULL rather than zero. NULLIF turns a zero previous month into NULL, which avoids a division-by-zero error in the percentage. If a month can be missing entirely, fill it from a calendar spine first or LAG will compare across the gap. The monthly CTE here is the cumulative-total-by-month opening; only the window call after it differs.","variants":[{"sql":"WITH monthly AS (\n  SELECT DATE_TRUNC('month', order_date)::date AS month,\n         SUM(amount) AS month_total\n  FROM orders\n  GROUP BY 1\n)\nSELECT month, month_total,\n       month_total - LAG(month_total, 12) OVER (ORDER BY month) AS delta_vs_last_year\nFROM monthly\nORDER BY month;"}],"see_also":["cumulative-total-by-month","year-over-year-same-day","lag-compare-within-group"],"faqs":[{"question":"Why is the first row's delta NULL?","answer":"LAG has no previous row to read, so it returns NULL by default. You can pass a default as the third argument (LAG(month_total, 1, 0)) but treating the first month as 'no change yet' is usually more honest than showing a fake delta."},{"question":"How do I turn the delta into a percentage?","answer":"Divide the delta by the previous month and multiply by 100, with NULLIF(prev_month_total, 0) as the denominator so a zero month yields NULL; MySQL returns NULL on its own there, while SQL Server raises divide-by-zero (error 8134)."}]},"source_url":"https://sqlly.app/sql-snippets/month-over-month-delta","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/move-table-between-schemas","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Move a table between schemas","description":"Relocate a table to another schema in one statement (SET SCHEMA on PostgreSQL, ALTER SCHEMA ... TRANSFER on SQL Server), and what moves with it.","body":{"slug":"move-table-between-schemas","name":"Move a table between schemas","h1":"Move a table between schemas","category":"schema","lede":"Archiving old tables or splitting a database into modules means moving tables between schemas. It is one statement; the follow-up work is permissions and name resolution.","engine_slug":"postgresql","problem":"Ownership of a table is moving to another team or the table is being filed away, and the namespace should reflect that without a data copy.","sql":"ALTER TABLE public.events SET SCHEMA archive;","how_it_works":"SET SCHEMA is a catalog change: the table keeps its data and grants, and its indexes, constraints and owned sequences (serial or identity) move with it. Views and foreign keys keep working because they reference the table by OID. What breaks is name resolution: code that uses the unqualified name finds nothing unless the new schema is on its search_path. You must own the table and have CREATE on the target schema.","variants":[{"sql":"ALTER SCHEMA archive TRANSFER dbo.Events;\n-- indexes and constraints follow, but every permission\n-- granted on the table is dropped; re-grant afterwards"},{"sql":"-- move every table of a tenant schema at once\nDO $$\nDECLARE t record;\nBEGIN\n  FOR t IN\n    SELECT table_name FROM information_schema.tables\n    WHERE table_schema = 'tenant_42' AND table_type = 'BASE TABLE'\n  LOOP\n    EXECUTE format('ALTER TABLE %I.%I SET SCHEMA archive', 'tenant_42', t.table_name);\n  END LOOP;\nEND $$;"}],"see_also":["list-schemas","create-empty-like-table","grant-select-all-tables"],"faqs":[{"question":"Why do my queries fail after the move?","answer":"Unqualified names resolve through search_path, and the table's new schema is probably not on it. Either qualify names, extend search_path for the affected roles, or create a view with the old name for a transition period."},{"question":"Does the move block queries?","answer":"Yes: SET SCHEMA is an ALTER TABLE form and takes PostgreSQL's strongest table lock, so it waits out running queries and queues everything behind it on a busy table. Set lock_timeout first, exactly as you would before a rename, and run the move off-peak."}]},"source_url":"https://sqlly.app/sql-snippets/move-table-between-schemas","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/moving-average","corpus":"sql-snippets","engine":"all","language":"en","title":"Moving average","description":"Smooth a series with a trailing 7-row average using a window frame, no self-joins.","body":{"slug":"moving-average","name":"Moving average","h1":"Moving average","category":"querying","lede":"AVG over a sliding frame of the last N rows, the usual smoothing line on a trend chart.","engine_slug":"all","problem":"You want a 7-point moving average of order amounts to smooth out daily noise in a chart.","sql":"SELECT order_date, id, amount,\n       AVG(amount) OVER (ORDER BY order_date, id\n                         ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_last_7\nFROM orders\nORDER BY order_date, id;","how_it_works":"The frame 6 PRECEDING AND CURRENT ROW slides a seven-row window over the data; AVG averages whatever falls inside it, including the shorter windows at the start of the series. ROWS counts physical rows, so gaps in the data do not stretch the window back in time. Add PARTITION BY if the average should restart per group, such as per customer.","variants":[{"sql":"SELECT order_date,\n       AVG(amount) OVER (ORDER BY order_date\n                         RANGE BETWEEN INTERVAL '6 days' PRECEDING\n                               AND CURRENT ROW) AS avg_7_days\nFROM orders\nORDER BY order_date;"}],"see_also":["running-total","cumulative-total-by-month"],"faqs":[{"question":"Why do the first rows have a shorter window?","answer":"There are fewer than seven rows before them, so the frame holds only the rows that exist. All five engines average what is in the frame rather than returning NULL; wrap the result in CASE WHEN ROW_NUMBER() OVER (ORDER BY order_date, id) >= 7 THEN ... END if you want to hide the warm-up rows."}]},"source_url":"https://sqlly.app/sql-snippets/moving-average","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/multi-condition-ranking","corpus":"sql-snippets","engine":"all","language":"en","title":"Rank by several conditions","description":"Build a priority from a CASE ladder over status, then order the queue by it in a window function.","body":{"slug":"multi-condition-ranking","name":"Rank by several conditions","h1":"Rank by several conditions","category":"querying","lede":"The CASE maps business severity to numbers; the window sorts by the result.","engine_slug":"all","problem":"You want orders ranked into a handling queue: returned orders first, then pending, then shipped, oldest first within each class.","sql":"SELECT id, status, order_date,\n       ROW_NUMBER() OVER (\n         ORDER BY CASE status\n                    WHEN 'returned' THEN 1\n                    WHEN 'pending'  THEN 2\n                    WHEN 'shipped'  THEN 3\n                    ELSE 4\n                  END,\n                  order_date\n       ) AS handling_priority\nFROM orders\nWHERE status <> 'cancelled'\nORDER BY handling_priority;","how_it_works":"The CASE turns each status into a priority number, and the window ORDER BY sorts first by that number and then by date inside each class. ROW_NUMBER over the combined key hands out queue positions in exactly that order. Ranking by an expression like this is legal anywhere an ORDER BY is, including PARTITION BY for per-region queues.","variants":[{"sql":"SELECT c.region, o.id, o.status,\n       ROW_NUMBER() OVER (\n         PARTITION BY c.region\n         ORDER BY CASE o.status\n                    WHEN 'returned' THEN 1\n                    WHEN 'pending'  THEN 2\n                    ELSE 3\n                  END,\n                  o.order_date\n       ) AS queue_position\nFROM orders o\nJOIN customers c ON c.id = o.customer_id\nORDER BY c.region, queue_position;"}],"see_also":["top-n-per-group","rank-within-category","tiebreak-ordering"],"faqs":[{"question":"How do NULLs sort in the priority ladder?","answer":"The CASE's ELSE catches them, so an unknown status lands last instead of wherever the engine puts NULLs. In the main query a NULL status never gets that far: status <> 'cancelled' is unknown for NULL, so WHERE drops the row; write WHERE status IS NULL OR status <> 'cancelled' to keep it. PostgreSQL, Oracle and SQLite 3.30+ also accept NULLS LAST in ORDER BY; SQL Server and MySQL need the CASE."}]},"source_url":"https://sqlly.app/sql-snippets/multi-condition-ranking","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/multi-parent-orphan-sweep","corpus":"sql-snippets","engine":"all","language":"en","title":"Orphan sweep across multiple parents","description":"Check every foreign key of one child table in a single UNION ALL and list the exact missing values.","body":{"slug":"multi-parent-orphan-sweep","name":"Orphan sweep","h1":"Orphan sweep across multiple parents","category":"data-quality","lede":"One branch per foreign key, each an anti-join; UNION ALL merges them into a labeled list of every dangling reference in the table.","engine_slug":"all","problem":"order_items points at both orders and products. A deleted order orphans lines just as surely as a deleted product, so the sweep checks every foreign key of the table and names which one broke.","sql":"SELECT 'order_items.order_id -> orders.id' AS broken_reference,\n       oi.order_id AS missing_value\nFROM order_items oi\nLEFT JOIN orders o ON o.id = oi.order_id\nWHERE oi.order_id IS NOT NULL AND o.id IS NULL\nUNION ALL\nSELECT 'order_items.product_id -> products.id',\n       pi.product_id\nFROM order_items pi\nLEFT JOIN products p ON p.id = pi.product_id\nWHERE pi.product_id IS NOT NULL AND p.id IS NULL\nORDER BY broken_reference, missing_value;","how_it_works":"Each branch is the standard orphan anti-join for one foreign key, labeled with the relationship it inspects. The IS NOT NULL test matters: a NULL foreign key never matches a parent, so without it every line with no product would be reported as an orphan. The ORDER BY groups the report by relationship, so fixing one FK means working one block. referential-audit-both-directions is this shape stacked for every foreign key in the schema.","variants":[{"sql":"SELECT 'order_items.order_id -> orders.id' AS broken_reference,\n       COUNT(*) AS orphaned_rows\nFROM order_items oi\nLEFT JOIN orders o ON o.id = oi.order_id\nWHERE oi.order_id IS NOT NULL AND o.id IS NULL\nUNION ALL\nSELECT 'order_items.product_id -> products.id', COUNT(*)\nFROM order_items pi\nLEFT JOIN products p ON p.id = pi.product_id\nWHERE pi.product_id IS NOT NULL AND p.id IS NULL;"}],"see_also":["referential-audit-both-directions","find-orphaned-rows","cascade-impact-preview"],"faqs":[{"question":"Sweep or full audit: which one when?","answer":"The sweep inspects one child table against all its parents; the full audit walks every relationship in the schema. Run the audit on schema changes and after imports, the sweep while investigating a specific table. They share the same anti-join shape, so moving between them is copy, relabel and regroup."}]},"source_url":"https://sqlly.app/sql-snippets/multi-parent-orphan-sweep","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/natural-sort-padded-numbers","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Natural sort strings with numbers in SQL","description":"Order file names and codes the way humans expect by sorting the numeric tail numerically, not alphabetically.","body":{"slug":"natural-sort-padded-numbers","name":"Natural sort with padded numbers","h1":"Natural sort strings with numbers in SQL","category":"text","lede":"Alphabetical order puts item10 before item2. Extract the text prefix and numeric suffix to sort properly.","engine_slug":"postgresql","problem":"Rows named file1, file2 ... file10 sort as file1, file10, file2 alphabetically. Sorting by the text prefix plus the number fixes it.","sql":"SELECT file_name\nFROM attachments\nORDER BY regexp_replace(file_name, '[0-9]+$', ''),\n         NULLIF(substring(file_name FROM '[0-9]+$'), '')::int,\n         file_name;","how_it_works":"The first key is the name with its numeric tail removed, so file10 groups with file. The second key casts that tail to an integer so 2 sorts before 10. The final file_name breaks ties deterministically. NULLIF handles names with no digits, which would otherwise fail the cast.","variants":[{"sql":"SELECT file_name\nFROM attachments\nORDER BY LENGTH(file_name), file_name;"}],"see_also":["pad-numbers-zeros","extract-trailing-digits"],"faqs":[{"question":"Why does ORDER BY LENGTH(name), name work?","answer":"When all names share a prefix, a longer string has a bigger number, so sorting by length first and text second approximates numeric order. It breaks on mixed prefixes: 'zz1' sorts before 'a10' because it is shorter. The PostgreSQL key-splitting version handles those; MySQL 8 can copy it with REGEXP_REPLACE and REGEXP_SUBSTR."}]},"source_url":"https://sqlly.app/sql-snippets/natural-sort-padded-numbers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/never-scanned-indexes","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Find indexes never scanned in SQL Server","description":"Lists nonclustered indexes with zero user seeks, scans and lookups but ongoing write maintenance since the instance last started.","body":{"slug":"never-scanned-indexes","name":"Never-scanned indexes","h1":"Find indexes never scanned in SQL Server","category":"indexes","lede":"An index that is written on every insert but never read costs you something and returns nothing. sys.dm_db_index_usage_stats finds them.","engine_slug":"sql-server","problem":"SQL Server counts user seeks, scans and lookups per index in sys.dm_db_index_usage_stats, alongside user_updates, the number of write operations that had to maintain the index. An index with zero reads and thousands of updates is paid for on every INSERT, every DELETE and every UPDATE that touches its columns, and no query has used it since the counters started.","sql":"SELECT OBJECT_SCHEMA_NAME(i.object_id) AS schema_name,\n       OBJECT_NAME(i.object_id) AS table_name,\n       i.name AS index_name, i.type_desc,\n       us.user_seeks, us.user_scans, us.user_lookups,\n       us.user_updates,\n       us.last_user_update\nFROM sys.indexes i\nJOIN sys.dm_db_index_usage_stats us\n  ON us.object_id = i.object_id AND us.index_id = i.index_id AND us.database_id = DB_ID()\nWHERE i.index_id > 1\n  AND i.is_unique = 0\n  AND us.user_seeks = 0 AND us.user_scans = 0 AND us.user_lookups = 0\nORDER BY us.user_updates DESC;","how_it_works":"sys.dm_db_index_usage_stats is instance-wide, so the join filters on database_id = DB_ID() to stay in the current database. SQL Server adds a row only when something touches the index, which is fine here: an index with no row at all has never taken a write either. index_id > 1 skips the heap (0) and the clustered index (1), which hold the table's data and cannot be dropped as a tuning step. is_unique = 0 skips primary keys, unique constraints and unique indexes, because they enforce rules. Ordering by user_updates puts the most expensive dead weight first.","variants":[{"sql":"SELECT OBJECT_SCHEMA_NAME(i.object_id) AS schema_name,\n       OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name,\n       us.user_updates,\n       CAST(SUM(ps.used_page_count) * 8 / 1024.0 AS DECIMAL(12,1)) AS size_mb\nFROM sys.indexes i\nJOIN sys.dm_db_index_usage_stats us\n  ON us.object_id = i.object_id AND us.index_id = i.index_id AND us.database_id = DB_ID()\nJOIN sys.dm_db_partition_stats ps\n  ON ps.object_id = i.object_id AND ps.index_id = i.index_id\nWHERE i.index_id > 1 AND i.is_unique = 0\n  AND us.user_seeks = 0 AND us.user_scans = 0 AND us.user_lookups = 0\nGROUP BY i.object_id, i.name, us.user_updates\nORDER BY us.user_updates DESC;"}],"see_also":["unused-indexes","duplicate-indexes","largest-indexes"],"faqs":[{"question":"When are the counters reset?","answer":"On instance restart, and when the database is detached, taken offline or closed by AUTO_CLOSE. sqlserver_start_time in sys.dm_os_sys_info tells you how long the instance has been counting. On an availability group, each replica keeps its own counters, so an index used only by reports on a readable secondary looks unused on the primary."},{"question":"The query says an index is never used. Can I drop it right away?","answer":"Wait for a window that includes month-end and other rare jobs, and check for queries that name the index in a WITH (INDEX(...)) hint, because those fail once it is gone. ALTER INDEX ... DISABLE is a softer first step: it removes the index's data and its write cost but keeps the definition, and ALTER INDEX ... REBUILD brings it back."}]},"source_url":"https://sqlly.app/sql-snippets/never-scanned-indexes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/next-anniversary","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Find the next anniversary of a date in SQL","description":"Work out each employee's next work anniversary or each customer's next renewal, this year or next.","body":{"slug":"next-anniversary","name":"Next anniversary of a date","h1":"Find the next anniversary of a date in SQL","category":"text","lede":"Renewal emails and anniversary bonuses need the next occurrence of a stored date, which may be this year or next.","engine_slug":"sql-server","problem":"Take the hire month and day, place it in the current year, and push to next year if that date already passed.","sql":"SELECT\n    hire_date,\n    DATEADD(YEAR,\n        DATEDIFF(YEAR, hire_date, GETDATE())\n          + CASE WHEN DATEADD(YEAR, DATEDIFF(YEAR, hire_date, GETDATE()), hire_date) < CAST(GETDATE() AS DATE)\n                 THEN 1 ELSE 0 END,\n        hire_date) AS next_anniversary\nFROM employees;","how_it_works":"DATEDIFF(YEAR, ...) counts calendar-year boundaries, so DATEADD(YEAR, that count, hire_date) is this year's anniversary; the CASE adds one more year when it has already passed. Building the date with DATEADD rather than DATEFROMPARTS(YEAR(GETDATE()), MONTH(hire_date), DAY(hire_date)) matters for Feb 29 hires: DATEADD maps them to Feb 28 in non-leap years, while DATEFROMPARTS raises an error. Today's anniversary counts as the next one, which is what renewal jobs want; a reminder query that must not fire a day early should cast both sides to date, because the raw datetime comparison silently defers an afternoon anniversary to next year.","variants":[{"sql":"SELECT\n    hire_date,\n    hire_date + interval '1 year'\n        * (EXTRACT(YEAR FROM age(CURRENT_DATE, hire_date))::int\n           + CASE WHEN (hire_date + interval '1 year'\n                        * EXTRACT(YEAR FROM age(CURRENT_DATE, hire_date))::int) < CURRENT_DATE\n                  THEN 1 ELSE 0 END) AS next_anniversary\nFROM employees;"}],"see_also":["age-in-years-months-days","first-and-last-day-of-month"],"faqs":[{"question":"Can I order by upcoming anniversaries?","answer":"Yes: ORDER BY next_anniversary works as written since every value is today or later. For a 'next 30 days' list, filter on the computed value (wrap the query in a CTE), not on the raw hire_date."},{"question":"Why does a 15:00 birth time change today's result?","answer":"The CASE compares full datetimes, so on the anniversary morning DATEADD(YEAR, n, hire_date) is still later that day and the query reports next year instead. CAST both sides to date when the time of day must not vote."}]},"source_url":"https://sqlly.app/sql-snippets/next-anniversary","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/next-job-id","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Reserve the next job id","description":"Insert the job and read back its generated id in one statement with RETURNING.","body":{"slug":"next-job-id","name":"Next job id","h1":"Reserve the next job id","category":"querying","lede":"Sequences hand out ids atomically; RETURNING, OUTPUT and friends read them back.","engine_slug":"postgresql","problem":"You need to insert a job and immediately know its id to reference it elsewhere. MAX(id) + 1 is a race waiting to happen.","sql":"INSERT INTO jobs (name, created_at, status)\nVALUES ('daily-report', NOW(), 'pending')\nRETURNING id;","how_it_works":"The database's sequence allocates the id atomically as part of the insert; RETURNING gives the new row's id back in the same statement, so no second query and no race. The same RETURNING clause works on SQLite 3.35+. SQL Server uses OUTPUT INSERTED.id, MySQL reads LAST_INSERT_ID() on the same connection (it is per-connection, so other sessions' inserts do not affect it), and Oracle uses RETURNING id INTO a bind variable or PL/SQL variable.","variants":[{"sql":"INSERT INTO jobs (name, created_at, status)\nOUTPUT inserted.id\nVALUES ('daily-report', SYSDATETIME(), 'pending');"},{"sql":"INSERT INTO jobs (name, created_at, status)\nVALUES ('daily-report', NOW(), 'pending');\n\nSELECT LAST_INSERT_ID() AS id;"}],"see_also":["fifo-queue-consume"],"faqs":[{"question":"Why is MAX(id) + 1 wrong?","answer":"Two sessions can read the same MAX before either inserts, both compute the same next id, and one insert fails or you get duplicates. Sequences (and identity/auto-increment columns) allocate atomically inside the engine, which is the whole point."},{"question":"Why does SQL Server reject OUTPUT INSERTED.id on my table?","answer":"An OUTPUT clause without INTO is not allowed when the target table has enabled triggers (error 334). Catch the value with OUTPUT INSERTED.id INTO @ids and read it from the table variable."}]},"source_url":"https://sqlly.app/sql-snippets/next-job-id","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/non-sargable-detector","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find queries that put functions on indexed columns in PostgreSQL","description":"Scans pg_stat_statements for hot queries whose WHERE clauses wrap columns in functions like UPPER, DATE_TRUNC or CAST, the classic way an index stops being used.","body":{"slug":"non-sargable-detector","name":"Non-sargable detector","h1":"Find queries that put functions on indexed columns in PostgreSQL","category":"indexes","lede":"UPPER(col) in a WHERE clause quietly disables the index on col. This finds the hot queries doing it.","engine_slug":"postgresql","problem":"A sargable predicate lets the planner seek an index directly: col = 'x'. Wrapping the column in a function, as in UPPER(col), DATE_TRUNC('day', col) or CAST(col AS date), makes it non-sargable: a plain B-tree index on col stores col's values, not the function's results, so the planner cannot seek it and falls back to a sequential scan or a full index scan. There are two fixes. Rewrite the predicate so the column stands alone (col >= DATE '2026-01-01' AND col < DATE '2026-01-02'), or create an index on the expression itself.","sql":"SELECT calls,\n       ROUND(mean_exec_time::numeric, 1) AS mean_ms,\n       ROUND(total_exec_time::numeric, 0) AS total_ms,\n       LEFT(query, 140) AS query\nFROM pg_stat_statements\nWHERE query ~* '(WHERE|JOIN|ON)[^(]*(UPPER\\s*\\(|LOWER\\s*\\(|SUBSTRING\\s*\\(|TRIM\\s*\\(|DATE_TRUNC\\s*\\(|CAST\\s*\\()'\n  AND calls > 100\nORDER BY total_exec_time DESC\nLIMIT 20;","how_it_works":"pg_stat_statements stores normalized query text (constants replaced by $1, $2), so a case-insensitive regular expression (~*) over it finds statements where a function call follows WHERE, JOIN or ON with no opening parenthesis in between. It is a text heuristic. It flags harmless calls such as UPPER($1) on a parameter, misses functions used later in a long WHERE clause after another parenthesis, and only sees the outer statement text (statements inside functions appear only when pg_stat_statements.track = all). Ordering by total_exec_time puts the candidates that cost the most first. Confirm each one with EXPLAIN before rewriting: the plan shows whether the index was actually skipped. The view exists only once pg_stat_statements is preloaded and created; the most-expensive-queries recipe has the setup.","variants":[{"sql":"SELECT COUNT_STAR,\n       ROUND(SUM_TIMER_WAIT / 1e12, 3) AS total_sec,\n       LEFT(DIGEST_TEXT, 140) AS digest\nFROM performance_schema.events_statements_summary_by_digest\nWHERE DIGEST_TEXT REGEXP '(WHERE|JOIN|ON)[^()]*((UPPER|LOWER|SUBSTRING|TRIM|CAST|DATE)[[:space:]]*\\\\()'\nORDER BY SUM_TIMER_WAIT DESC\nLIMIT 20;"},{"sql":"SELECT TOP 20\n    qs.execution_count,\n    CAST(qs.total_logical_reads / 1000.0 AS DECIMAL(18,1)) AS reads_k,\n    st.text\nFROM sys.dm_exec_query_stats qs\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st\nCROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp\nWHERE qp.query_plan.exist('declare namespace p=\"http://schemas.microsoft.com/sqlserver/2004/07/showplan\";\n    //p:PlanAffectingConvert') = 1\nORDER BY qs.total_logical_reads DESC;"}],"see_also":["explain-query-plan-workflow","top-queries-by-total-time","high-logical-reads-queries"],"faqs":[{"question":"What is the standard rewrite for a date-range filter?","answer":"Instead of WHERE CAST(updated_at AS date) = '2026-01-01', write WHERE updated_at >= DATE '2026-01-01' AND updated_at < DATE '2026-01-02'. The column stays bare, the index applies, and midnight-to-midnight semantics are exact even with fractional seconds."},{"question":"Can I keep the function and still use an index?","answer":"Yes, by indexing the expression. In PostgreSQL, CREATE INDEX ON users (lower(email)) serves WHERE lower(email) = $1, as long as the query uses exactly the same expression. MySQL 8.0.13 and later support functional key parts: CREATE INDEX ix_email_lower ON users ((LOWER(email))). In SQL Server, add a computed column for the expression and index it; the optimizer can match the expression in the query to the indexed computed column."}]},"source_url":"https://sqlly.app/sql-snippets/non-sargable-detector","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/normalize-stored-utc","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Normalize stored timestamps to UTC in SQL","description":"Tag naive timestamps stored as UTC, then convert them to any zone for display, the two-step AT TIME ZONE way.","body":{"slug":"normalize-stored-utc","name":"Normalize stored timestamps to UTC","h1":"Normalize stored timestamps to UTC in SQL","category":"text","lede":"Columns of timestamp-without-time-zone hold UTC clock values. Every display query must attach the zone before converting.","engine_slug":"postgresql","problem":"The stored value is UTC wall-clock time with no zone. AT TIME ZONE 'UTC' declares it, and a second AT TIME ZONE renders it in the viewer's zone.","sql":"SELECT\n    created_at,\n    created_at AT TIME ZONE 'UTC'\n        AT TIME ZONE 'America/New_York' AS created_eastern\nFROM events;","how_it_works":"On a timestamp without time zone, the first AT TIME ZONE says 'these clock numbers are UTC', producing a timestamptz. The second AT TIME ZONE then renders that instant in New York local time. SQL Server uses the same two-step shape with Windows zone names. Skipping the first step is the usual bug: created_at AT TIME ZONE 'America/New_York' on its own reads the stored value as New York time and converts it to UTC, moving it the wrong way by the offset.","variants":[{"sql":"SELECT\n    created_at,\n    created_at AT TIME ZONE 'UTC'\n        AT TIME ZONE 'Eastern Standard Time' AS created_eastern\nFROM events;"}],"see_also":["convert-local-to-utc","dst-safe-date-arithmetic"],"faqs":[{"question":"Why does the SQL Server zone name say Standard Time?","answer":"Windows zone IDs are historical names like 'Eastern Standard Time', but the conversion still applies daylight saving where the zone observes it. The name is an identifier, not a promise of standard time year-round."}]},"source_url":"https://sqlly.app/sql-snippets/normalize-stored-utc","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/normalize-whitespace","corpus":"sql-snippets","engine":"all","language":"en","title":"Normalize whitespace in SQL","description":"Collapse runs of spaces into one and trim the ends, with a portable triple-REPLACE trick that runs on every engine.","body":{"slug":"normalize-whitespace","name":"Normalize whitespace","h1":"Normalize whitespace in SQL","category":"text","lede":"User-typed text arrives with double spaces, leading and trailing blanks. Normalize it before you store or compare it.","engine_slug":"all","problem":"Notes, addresses and names typed by people collect double spaces and stray leading blanks. Comparing or grouping that text fails until you normalize it.","sql":"SELECT\n    TRIM(REPLACE(REPLACE(REPLACE(note, ' ', '<>'), '><', ''), '<>', ' ')) AS clean_note\nFROM notes;","how_it_works":"The trick replaces every space with a marker (<>), then deletes marker pairs (><), then turns the surviving marker back into one space. Any run of spaces collapses to a single space in three plain REPLACE calls, no regex needed. TRIM then removes what is left at the ends. TRIM needs SQL Server 2017 or later; older versions use LTRIM(RTRIM(...)). Pick a marker that cannot occur in the data.","variants":[{"sql":"SELECT TRIM(REGEXP_REPLACE(note, '\\s+', ' ', 'g')) AS clean_note\nFROM notes;"},{"sql":"SELECT TRIM(REGEXP_REPLACE(note, '[[:space:]]+', ' ')) AS clean_note\nFROM notes;"}],"see_also":["remove-non-printable-characters","remove-all-whitespace"],"faqs":[{"question":"Does this handle tabs and line breaks too?","answer":"No. The portable version only collapses spaces. To fold tabs, carriage returns and line feeds into single spaces first, replace them with a space before the triple-REPLACE, or use a regex variant: \\s and [[:space:]] match tabs and line breaks as well as spaces. SQLite has no built-in REGEXP_REPLACE."}]},"source_url":"https://sqlly.app/sql-snippets/normalize-whitespace","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/ntile-deciles","corpus":"sql-snippets","engine":"all","language":"en","title":"Deciles with NTILE","description":"Split orders into ten equal-size buckets by amount with NTILE, and grab the top decile in one more step.","body":{"slug":"ntile-deciles","name":"Deciles with NTILE","h1":"Deciles with NTILE","category":"querying","lede":"NTILE(10) is a decile: same row count per bucket, regardless of the amounts.","engine_slug":"all","problem":"You want orders split into ten equal-count groups by amount so you can say 'this order is in the top decile'.","sql":"SELECT customer_id, amount,\n       NTILE(10) OVER (ORDER BY amount DESC) AS decile\nFROM orders\nORDER BY decile, amount DESC;","how_it_works":"NTILE(10) numbers the buckets 1 to 10 over the amount ordering, filling each with as close to an equal row count as division allows; the first buckets absorb the remainder. Decile 1 is the most expensive tenth of orders because of the DESC sort. Ties straddle bucket boundaries, since NTILE counts rows, not distinct values.","variants":[{"sql":"WITH banded AS (\n  SELECT id, customer_id, amount,\n         NTILE(10) OVER (ORDER BY amount DESC) AS decile\n  FROM orders\n)\nSELECT id, customer_id, amount\nFROM banded\nWHERE decile = 1\nORDER BY amount DESC;"}],"see_also":["percentile-buckets","rank-within-category","top-n-per-group"],"faqs":[{"question":"How is NTILE different from a percentage rank?","answer":"NTILE assigns bucket numbers by row count, so bucket 1 always holds about 10% of rows no matter how close their values are. PERCENT_RANK and CUME_DIST assign values by position and handle ties, which is what you want when the percentile itself matters more than the bucket size."},{"question":"Which decile do NULL amounts land in?","answer":"SQL Server, MySQL and SQLite sort NULL lowest, so it piles into decile 1 of a DESC ranking, the most expensive bucket; PostgreSQL and Oracle put NULLs last, in decile 10. Filter NULLs before ranking when every bucket should hold real amounts."}]},"source_url":"https://sqlly.app/sql-snippets/ntile-deciles","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/null-counts-per-column","corpus":"sql-snippets","engine":"all","language":"en","title":"Count NULLs per column (NULL skew)","description":"One-row-per-table NULL audit: SUM(CASE WHEN col IS NULL) per column reveals skew at a glance.","body":{"slug":"null-counts-per-column","name":"NULL counts per column","h1":"Count NULLs per column (NULL skew)","category":"data-quality","lede":"Build one summary row that counts NULLs per column, so a quick scan shows which columns carry missing data.","engine_slug":"all","problem":"Before trusting customers for analytics you want to know how much of each column is actually populated, and whether some column is almost entirely NULL, a skew that usually means a broken upstream feed.","sql":"SELECT\n  COUNT(*) AS total_rows,\n  SUM(CASE WHEN name IS NULL THEN 1 ELSE 0 END) AS null_name,\n  SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END) AS null_email,\n  SUM(CASE WHEN phone IS NULL THEN 1 ELSE 0 END) AS null_phone,\n  SUM(CASE WHEN created_at IS NULL THEN 1 ELSE 0 END) AS null_created_at\nFROM customers;","how_it_works":"Each SUM(CASE ...) adds 1 only for rows where that column is NULL, producing a wide one-row report. COUNT(*) is the denominator, so null_email / total_rows is the NULL rate. Add one line per column you care about; wide tables are easier with the unpivoted variant.","variants":[{"sql":"SELECT 'name' AS column_name,\n       SUM(CASE WHEN name IS NULL THEN 1 ELSE 0 END) AS null_count,\n       COUNT(*) AS total_rows\nFROM customers\nUNION ALL\nSELECT 'email',\n       SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END),\n       COUNT(*)\nFROM customers\nUNION ALL\nSELECT 'phone',\n       SUM(CASE WHEN phone IS NULL THEN 1 ELSE 0 END),\n       COUNT(*)\nFROM customers;"}],"see_also":["per-column-fill-rate","blank-strings-vs-nulls","column-profile-min-max-distinct"],"faqs":[{"question":"Why SUM(CASE) instead of COUNT(col)?","answer":"COUNT(col) counts non-NULL values, so COUNT(*) - COUNT(col) is the NULL count: a shorter form of the same answer, and the per-column-fill-rate recipe uses it. The CASE form is spelled out here because the same shape extends to other conditions in the same row, such as counting empty strings with CASE WHEN col = '' THEN 1 END."}]},"source_url":"https://sqlly.app/sql-snippets/null-counts-per-column","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/offset-pagination-pitfalls","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Offset pagination pitfalls","description":"Why LIMIT OFFSET gets slower with every page and can duplicate or skip rows while you browse.","body":{"slug":"offset-pagination-pitfalls","name":"Offset pagination pitfalls","h1":"Offset pagination pitfalls","category":"querying","lede":"OFFSET reads and throws away the skipped rows, and inserts move pages underneath you.","engine_slug":"postgresql","problem":"Page 400 of your ORDER BY date DESC listing takes seconds, and items sometimes appear on two pages or vanish between clicks.","sql":"SELECT id, customer_id, order_date, amount\nFROM orders\nORDER BY order_date DESC, id DESC\nLIMIT 20 OFFSET 7980;","how_it_works":"OFFSET 7980 tells the engine to walk 8000 rows and throw away the first 7980, so deep pages get slower linearly. Any row inserted meanwhile shifts the offset by one, pushing an item from page N to page N+1 (skipped) or pulling one up (duplicated). The sort keys plus a keyset cursor fix both problems; OFFSET stays fine for shallow, mostly-static lists. The variant is the keyset-pagination statement applied to this list, and the two pages share it on purpose.","variants":[{"sql":"SELECT id, customer_id, order_date, amount\nFROM orders\nWHERE (order_date, id) < ('2026-06-01 12:00:00', 1000)\nORDER BY order_date DESC, id DESC\nLIMIT 20;  -- the keyset form: page 1000 costs an index seek, not 8000 skipped rows"}],"see_also":["keyset-pagination","tiebreak-ordering"],"faqs":[{"question":"Is OFFSET always bad?","answer":"No. For the first few pages, admin tables with hundreds of rows, or data that changes rarely, OFFSET is simpler and fast enough. The trouble starts when offsets reach tens of thousands of rows or the list changes while users browse."},{"question":"Why do rows repeat or vanish between pages even with a small offset?","answer":"Without ORDER BY the engine owes you no order at all, so page 2 can repeat a row from page 1 on any of the five engines. Pinning the sort fixes the ordering, and the keyset cursor fixes the shifting-offset duplicates on top of it."}]},"source_url":"https://sqlly.app/sql-snippets/offset-pagination-pitfalls","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/org-chart-walk","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Walk an org chart","description":"List a manager's whole subtree with a recursive CTE, one row per employee with a depth column.","body":{"slug":"org-chart-walk","name":"Walk an org chart","h1":"Walk an org chart","category":"querying","lede":"Seed the manager, then join children onto the frontier until none remain.","engine_slug":"postgresql","problem":"You want everyone reporting, directly or not, to employee 42, with how deep they sit below them.","sql":"WITH RECURSIVE subordinates AS (\n  SELECT id, name, manager_id, 0 AS depth\n  FROM employees\n  WHERE id = 42\n  UNION ALL\n  SELECT e.id, e.name, e.manager_id, s.depth + 1\n  FROM employees e\n  JOIN subordinates s ON e.manager_id = s.id\n)\nSELECT id, name, depth\nFROM subordinates\nORDER BY depth, name;","how_it_works":"The anchor is the manager themself at depth 0; each recursive round joins the current frontier's direct reports one level deeper. Depth makes the output sortable by level and gives you something to cap if the data contains a loop. The statement runs unchanged on PostgreSQL, MySQL 8.0+ and SQLite; MySQL 5.7 has no recursive CTEs at all. SQL Server and Oracle drop the RECURSIVE keyword; Oracle also requires the column list after the CTE name, which SQL Server accepts too. SQL Server stops any recursive CTE after 100 levels by default (OPTION (MAXRECURSION n) changes that).","variants":[{"sql":"WITH RECURSIVE managers AS (\n  SELECT id, name, manager_id\n  FROM employees\n  WHERE id = 42\n  UNION ALL\n  SELECT e.id, e.name, e.manager_id\n  FROM employees e\n  JOIN managers m ON e.id = m.manager_id\n)\nSELECT id, name, manager_id\nFROM managers\nORDER BY id;"},{"sql":"WITH subordinates (id, name, manager_id, depth) AS (\n  SELECT id, name, manager_id, 0\n  FROM employees\n  WHERE id = 42\n  UNION ALL\n  SELECT e.id, e.name, e.manager_id, s.depth + 1\n  FROM employees e\n  JOIN subordinates s ON e.manager_id = s.id\n)\nSELECT id, name, depth\nFROM subordinates\nORDER BY depth, name;"}],"see_also":["transitive-closure-recursive-cte","bill-of-materials-walk","recursive-cte-cycle-guard"],"faqs":[{"question":"What if the data has a manager loop?","answer":"A loop such as A managing B managing A makes the recursion grow without end (SQL Server aborts at its 100-level default; PostgreSQL and SQLite keep going; MySQL stops at cte_max_recursion_depth, 1000 by default). Add a depth cap (WHERE s.depth < 20) or a visited guard as in the cycle-guard recipe, and fix the data."}]},"source_url":"https://sqlly.app/sql-snippets/org-chart-walk","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/overlap-of-two-ranges","corpus":"sql-snippets","engine":"all","language":"en","title":"Check whether two date ranges overlap in SQL","description":"Detect booking conflicts with the two-comparison overlap test, or the && range operator on PostgreSQL.","body":{"slug":"overlap-of-two-ranges","name":"Check if two date ranges overlap","h1":"Check whether two date ranges overlap in SQL","category":"querying","lede":"Scheduling needs to reject a new booking that intersects an existing one, including bookings already in the table that collide with each other.","engine_slug":"all","problem":"Two half-open ranges overlap exactly when each starts before the other ends. A self-join with that test lists every pair of bookings for the same room that collide.","sql":"SELECT a.booking_id, b.booking_id AS conflicts_with\nFROM bookings a\nJOIN bookings b\n  ON a.room_id = b.room_id\n AND a.booking_id < b.booking_id\n AND a.starts_at < b.ends_at\n AND b.starts_at < a.ends_at\nORDER BY a.booking_id, b.booking_id;","how_it_works":"The pair of strict inequalities is the complete overlap test for half-open ranges [start, end): no need to enumerate the contained, left-overlap and right-overlap cases separately. Touching ranges (one ends exactly when the other starts) do not conflict, which is what strict < gives you. a.booking_id < b.booking_id lists each pair once. To check one new booking before inserting it, keep the same test with parameters: starts_at < :new_end AND ends_at > :new_start. A NULL end date makes the comparison unknown, so treat open-ended bookings with COALESCE(ends_at, a far-future date).","variants":[{"sql":"SELECT a.booking_id, b.booking_id AS conflicts_with\nFROM bookings a\nJOIN bookings b\n  ON a.room_id = b.room_id\n AND a.booking_id < b.booking_id\n AND tsrange(a.starts_at, a.ends_at) && tsrange(b.starts_at, b.ends_at);"}],"see_also":["expiring-soon-checks","first-and-last-day-of-month"],"faqs":[{"question":"How do I include boundary-touching ranges?","answer":"Use <= instead of < in both comparisons to treat ranges that merely touch as overlapping. Most scheduling domains want the strict version so back-to-back bookings remain legal. On PostgreSQL an exclusion constraint (EXCLUDE USING gist (room_id WITH =, tsrange(starts_at, ends_at) WITH &&), with btree_gist installed) rejects overlapping inserts outright."}]},"source_url":"https://sqlly.app/sql-snippets/overlap-of-two-ranges","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/overlapping-ranges","corpus":"sql-snippets","engine":"all","language":"en","title":"Detect overlapping date ranges","description":"Self-join a range table on the classic overlap condition to find subscriptions or bookings that collide.","body":{"slug":"overlapping-ranges","name":"Overlapping ranges","h1":"Detect overlapping date ranges","category":"data-quality","lede":"Two half-open ranges overlap when each starts before the other ends; a self-join with that condition pairs every colliding row.","engine_slug":"all","problem":"subscriptions stores start_date and end_date per customer, and business rules say a customer holds at most one active subscription. Imports may have created colliding periods.","sql":"SELECT a.id AS first_id, a.customer_id,\n       a.start_date AS first_start, a.end_date AS first_end,\n       b.id AS colliding_id,\n       b.start_date AS second_start, b.end_date AS second_end\nFROM subscriptions a\nJOIN subscriptions b\n  ON a.id < b.id\n AND a.customer_id = b.customer_id\n AND a.start_date < b.end_date\n AND b.start_date < a.end_date\nORDER BY a.customer_id, a.start_date;","how_it_works":"The a.id < b.id condition pairs each row once (A with B, never B with A) and skips self-pairs. The two range tests are the standard half-open overlap predicate: A starts before B ends AND B starts before A ends. Restricting to equal customer_id scopes the check per customer. An open-ended subscription stored with a NULL end_date never matches; wrap it as COALESCE(end_date, DATE '9999-12-31') (a plain '9999-12-31' string on SQL Server and SQLite) to treat it as running forever.","variants":[{"sql":"SELECT a.id, b.id AS colliding_id, a.customer_id\nFROM subscriptions a\nJOIN subscriptions b\n  ON a.id < b.id\n AND a.customer_id = b.customer_id\n AND a.start_date <= b.end_date\n AND b.start_date <= a.end_date;"},{"sql":"SELECT a.id, b.id AS colliding_id,\n       LEAST(a.end_date, b.end_date) - GREATEST(a.start_date, b.start_date) AS overlap_days\nFROM subscriptions a\nJOIN subscriptions b\n  ON a.id < b.id\n AND a.customer_id = b.customer_id\n AND a.start_date < b.end_date\n AND b.start_date < a.end_date;"}],"see_also":["date-gap-detection","conflicting-facts-across-tables"],"faqs":[{"question":"Why the strict inequality a.start_date < b.end_date?","answer":"Because the ranges are half-open: a subscription ending 2026-03-01 and one starting 2026-03-01 do not truly collide; the second begins the instant the first ends. Strict comparisons treat that handoff as legal. If your end dates are inclusive, switch both comparisons to <= with the first variant."},{"question":"What index keeps this self-join from exploding?","answer":"An index on (room_id, start_date) lets each side of the join seek the comparable rows instead of pairing the whole table against itself; PostgreSQL, MySQL and SQL Server all fall back to a quadratic scan without it. The a.id < b.id predicate then halves the remaining work."}]},"source_url":"https://sqlly.app/sql-snippets/overlapping-ranges","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/pad-numbers-zeros","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Pad numbers with leading zeros in SQL","description":"Render 7 as 00000007 for account numbers, invoice keys and fixed-width exports.","body":{"slug":"pad-numbers-zeros","name":"Pad numbers with zeros","h1":"Pad numbers with leading zeros in SQL","category":"text","lede":"Invoice and account numbers are stored as integers but must print as fixed-width strings with leading zeros.","engine_slug":"postgresql","problem":"Invoice 7 has to appear as INV-00000007. LPAD pads the string form of the number with zeros on the left up to the target width.","sql":"SELECT 'INV-' || LPAD(invoice_no::text, 8, '0') AS invoice_key\nFROM invoices;","how_it_works":"LPAD(text, width, '0') left-pads with zeros until the value is eight characters long. Careful: LPAD also truncates longer values to the width, so 123456789 becomes '12345678' on PostgreSQL, MySQL and Oracle. Cast the number to text first on PostgreSQL, since LPAD works on strings.","variants":[{"sql":"SELECT 'INV-' + FORMAT(invoice_no, 'D8') AS invoice_key\nFROM invoices;"},{"sql":"SELECT CONCAT('INV-', LPAD(invoice_no, 8, '0')) AS invoice_key\nFROM invoices;"},{"sql":"SELECT 'INV-' || printf('%08d', invoice_no) AS invoice_key\nFROM invoices;"}],"see_also":["format-money-string","natural-sort-padded-numbers"],"faqs":[{"question":"What happens to a number wider than the pad width?","answer":"It depends on the function. LPAD cuts the string to the width, so LPAD('123456789', 8, '0') returns '12345678', a wrong invoice number. SQL Server's FORMAT(n, 'D8') and SQLite's printf('%08d', n) treat 8 as a minimum and return all nine digits, while the old RIGHT('00000000' + ..., 8) trick truncates too. Check LENGTH before padding if values can outgrow the width."}]},"source_url":"https://sqlly.app/sql-snippets/pad-numbers-zeros","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/parse-vs-execute-ratio","corpus":"sql-snippets","engine":"oracle","language":"en","title":"Check the parse ratio and prepared statement cache in Oracle","description":"Compares hard parses, total parses and executions in v$sysstat to see whether statements are reusing cursors or re-parsing on every run.","body":{"slug":"parse-vs-execute-ratio","name":"Parse vs execute ratio","h1":"Check the parse ratio and prepared statement cache in Oracle","category":"monitoring","lede":"High parse rates mean Oracle is doing the same optimization work over and over. v$sysstat shows the reuse ratio in one query.","engine_slug":"oracle","problem":"Parsing turns SQL text into an executable cursor. A hard parse (no matching cursor in the shared pool) optimizes the statement from scratch and takes shared pool latches and mutexes while it does. A soft parse finds an existing cursor but still checks syntax, privileges and the session's settings. Executing a cursor the session already holds open costs neither. Applications that paste literal values into SQL instead of using bind variables produce new SQL text for every value, so every execution is a hard parse, and on a busy instance the latch contention slows everyone down.","sql":"SELECT name, value\nFROM v$sysstat\nWHERE name IN ('parse count (total)', 'parse count (hard)', 'execute count')\nORDER BY name;","how_it_works":"v$sysstat holds instance-wide counters since startup. Read them as two ratios. Hard parses as a share of total parses should be small; a high share means statements are not being shared, usually because of literals. Total parses as a share of executions shows whether the application keeps cursors open and re-executes them: near 100 percent means it parses before every execution, and with bind variables plus client-side statement caching it falls well below that. If hard parses dominate, the real fix is bind variables in the application. CURSOR_SHARING = FORCE makes Oracle replace literals with binds itself, a workaround with its own plan-stability risks, and a larger shared pool only helps when reusable cursors are being aged out.","variants":[{"sql":"SELECT ROUND(100.0 * MAX(CASE WHEN name = 'parse count (hard)' THEN value END)\n                 / NULLIF(MAX(CASE WHEN name = 'parse count (total)' THEN value END), 0), 2) AS hard_parse_pct,\n       ROUND(100.0 * MAX(CASE WHEN name = 'parse count (total)' THEN value END)\n                 / NULLIF(MAX(CASE WHEN name = 'execute count' THEN value END), 0), 2) AS parse_per_exec_pct\nFROM v$sysstat\nWHERE name IN ('parse count (total)', 'parse count (hard)', 'execute count');"},{"sql":"SELECT name, value\nFROM v$sysstat\nWHERE name IN ('session cursor cache hits', 'session cursor cache count');"}],"see_also":["top-io-sessions","top-queries-by-total-time"],"faqs":[{"question":"What is a healthy hard parse percentage?","answer":"A common rule of thumb is a few percent of total parses on a steady OLTP instance; compare against your own baseline rather than a fixed number. Jumps usually come from new literal-heavy application code, DDL or statistics gathering on hot tables (which invalidates the cursors that depend on them), or a shared pool too small to hold the working set of cursors."},{"question":"Where do prepared statements fit in PostgreSQL and MySQL?","answer":"Same idea: prepare once, execute many times. PostgreSQL has no shared plan cache; plans are cached per session, and pg_prepared_statements shows the current session's prepared statements with generic_plans and custom_plans counts (PostgreSQL 14 and later). MySQL counts Com_stmt_prepare and Com_stmt_execute in its global status, and performance_schema.prepared_statements_instances lists the live ones. Literal values pasted into SQL defeat reuse on every engine."}]},"source_url":"https://sqlly.app/sql-snippets/parse-vs-execute-ratio","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/per-column-fill-rate","corpus":"sql-snippets","engine":"all","language":"en","title":"Compute per-column fill rate","description":"COUNT(col) over COUNT(*) per column gives the share of populated values, all columns in one row.","body":{"slug":"per-column-fill-rate","name":"Fill rate","h1":"Compute per-column fill rate","category":"data-quality","lede":"COUNT(column) skips NULLs, so dividing it by COUNT(*) yields the fill rate of each column in a single pass.","engine_slug":"all","problem":"Before building a dashboard on customers you want to know, per field, what share of rows actually has a value. One query answers it for every column at once.","sql":"SELECT\n  ROUND(100.0 * COUNT(name) / COUNT(*), 1) AS name_filled_pct,\n  ROUND(100.0 * COUNT(email) / COUNT(*), 1) AS email_filled_pct,\n  ROUND(100.0 * COUNT(phone) / COUNT(*), 1) AS phone_filled_pct\nFROM customers;","how_it_works":"COUNT(name) counts only rows where name is not NULL while COUNT(*) counts everything, so the ratio is exactly the fill rate; multiplying by 100.0 keeps the decimals. One expression per column produces a compact one-row scorecard. Note this counts only NULL; empty strings still 'fill', which the blank-strings recipe handles.","variants":[{"sql":"SELECT 'name' AS column_name,\n       ROUND(100.0 * COUNT(name) / COUNT(*), 1) AS filled_pct\nFROM customers\nUNION ALL\nSELECT 'email', ROUND(100.0 * COUNT(email) / COUNT(*), 1)\nFROM customers\nUNION ALL\nSELECT 'phone', ROUND(100.0 * COUNT(phone) / COUNT(*), 1)\nFROM customers;"},{"sql":"SELECT ROUND(100.0 * COUNT(phone) / COUNT(*), 1) AS phone_filled_pct\nFROM customers\nWHERE created_at >= CURRENT_DATE - 90;"}],"see_also":["null-counts-per-column","blank-strings-vs-nulls","column-profile-min-max-distinct"],"faqs":[{"question":"Fill rate is 100 percent. Is the column trustworthy?","answer":"Only in the NULL sense. Empty strings, whitespace, zero and placeholder values like 'n/a' all count as filled, so a perfect fill rate can hide a column nobody really populates. Follow up with the blank-strings check on any column that matters before you build on it."}]},"source_url":"https://sqlly.app/sql-snippets/per-column-fill-rate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/per-database-file-sizes","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"List data and log file sizes per database in SQL Server","description":"Reads sys.master_files for every data and log file across the instance with sizes in MB, plus the pg_database_size equivalent for PostgreSQL.","body":{"slug":"per-database-file-sizes","name":"Per-database file sizes","h1":"List data and log file sizes per database in SQL Server","category":"monitoring","lede":"Every data and log file of every database on the instance, with its size and growth settings, in one query.","engine_slug":"sql-server","problem":"sys.master_files shows every database file on the instance, each database's data files and transaction log, with allocated size in 8 KB pages. sys.database_files shows the same for the current database only. Summing by volume and comparing with the free space that sys.dm_os_volume_stats reports is the basis for disk capacity planning.","sql":"SELECT DB_NAME(database_id) AS database_name,\n       name AS logical_name,\n       type_desc,\n       CAST(size / 128.0 AS DECIMAL(12,1)) AS size_mb,\n       CASE max_size WHEN -1 THEN NULL ELSE CAST(max_size / 128.0 AS DECIMAL(12,1)) END AS max_size_mb,\n       CASE WHEN is_percent_growth = 1 THEN CONCAT(growth, ' %')\n            ELSE CONCAT(growth / 128, ' MB') END AS growth,\n       is_read_only,\n       physical_name\nFROM sys.master_files\nORDER BY DB_NAME(database_id), type_desc, name;","how_it_works":"size, max_size and fixed growth are all in 8 KB pages, and 128 pages make a MB; dividing rather than multiplying by 8 first avoids an integer overflow on the 2 TB log cap. max_size = -1 means the file may grow until the disk is full, shown here as NULL; log files often show 268435456 pages, the 2 TB cap. growth is a percentage when is_percent_growth = 1, otherwise pages. type_desc separates ROWS (data) from LOG. Log size is not data size: a log much bigger than its data file usually means the full recovery model with log backups that are missing or rare. Small fixed growth steps on a busy database cause frequent growth events, each a pause; percentage growth makes the steps larger and larger as the file grows. The sizes here are what each file reserves on disk; FILEPROPERTY(name, 'SpaceUsed'), run inside each database, shows how much of it holds data.","variants":[{"sql":"SELECT datname,\n       pg_database_size(datname) AS size_bytes,\n       pg_size_pretty(pg_database_size(datname)) AS size\nFROM pg_database\nORDER BY pg_database_size(datname) DESC;"},{"sql":"SELECT FILE_NAME, TABLESPACE_NAME, FILE_TYPE,\n       ROUND(TOTAL_EXTENTS * EXTENT_SIZE / 1024 / 1024, 1) AS size_mb\nFROM information_schema.FILES\nWHERE TABLESPACE_NAME IS NOT NULL\nORDER BY TOTAL_EXTENTS * EXTENT_SIZE DESC;"}],"see_also":["database-growth-by-month","table-index-sizes-topn","wal-redo-size"],"faqs":[{"question":"A log file is 10x the data file. Is that broken?","answer":"Usually a configuration issue, not a fault. In the full or bulk-logged recovery model the log is only truncated by log backups, so missing log backups let it grow forever; log_reuse_wait_desc in sys.databases names what is holding it (LOG_BACKUP, ACTIVE_TRANSACTION, REPLICATION and so on). A single huge transaction or index rebuild also has to fit in the log. Fix the cause first, then shrink once with DBCC SHRINKFILE to a sensible size. Repeated shrink-and-grow cycles leave the log split into many small virtual log files, which slows recovery and log backups."},{"question":"How do I forecast disk run-out from this query?","answer":"Get free space per volume from sys.dm_os_volume_stats(database_id, file_id), which works on Windows and Linux, then divide it by the monthly growth from the database-growth recipe. A database growing 5 GB a month on a volume with 40 GB free has about eight months. Remember that files with a size cap stop at max_size_mb regardless of free disk."}]},"source_url":"https://sqlly.app/sql-snippets/per-database-file-sizes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/percentage-of-total","corpus":"sql-snippets","engine":"all","language":"en","title":"Percentage of total","description":"Show each customer's share of grand total revenue with a window over the grouped sum.","body":{"slug":"percentage-of-total","name":"Percentage of total","h1":"Percentage of total","category":"querying","lede":"SUM(SUM(x)) OVER () is the grand total evaluated after the GROUP BY.","engine_slug":"all","problem":"You want each customer's revenue and what percent of all revenue that represents, in one grouped query.","sql":"SELECT customer_id,\n       SUM(amount) AS total,\n       ROUND(100.0 * SUM(amount)\n             / SUM(SUM(amount)) OVER (), 1) AS pct_of_grand_total\nFROM orders\nGROUP BY customer_id\nORDER BY total DESC;","how_it_works":"Window functions run after GROUP BY, so SUM(SUM(amount)) OVER () sums the already-grouped customer totals across all rows, giving the grand total without a second scan. The outer SUM(amount) stays the per-customer value. Writing 100.0 rather than 100 forces decimal division. With an integer column, SQL Server, PostgreSQL and SQLite divide integers by truncating, so 100 * SUM(qty) / SUM(SUM(qty)) OVER () would drop the decimals.","variants":[{"sql":"SELECT customer_id,\n       SUM(amount) AS total,\n       ROUND(100.0 * SUM(amount) / t.grand, 1) AS pct_of_grand_total\nFROM orders\nCROSS JOIN (SELECT SUM(amount) AS grand FROM orders) t\nGROUP BY customer_id, t.grand\nORDER BY total DESC;"}],"see_also":["share-of-parent","cross-tab-with-totals","sum-if-recipe"],"faqs":[{"question":"Why does my percentage come out as 0 or 100?","answer":"Integer division. On SQL Server, PostgreSQL and SQLite, an integer divided by an integer is truncated: 3 / 10 is 0, so SUM(x) / SUM(SUM(x)) OVER () * 100 is 0 for every row except one that holds the whole total. MySQL and Oracle return 0.3. Multiply by 100.0 first, or CAST one operand to a decimal type."},{"question":"Why SUM(SUM(amount)) instead of one SUM?","answer":"The inner SUM is the GROUP BY aggregate; the outer windowed SUM totals the group results in the same pass. A bare SUM(amount) OVER () cannot parse here because amount is not a GROUP BY column."}]},"source_url":"https://sqlly.app/sql-snippets/percentage-of-total","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/percentile-buckets","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Percentile buckets","description":"Label each order low/medium/high/top by comparing it to the 25th, 50th and 75th percentiles of all amounts.","body":{"slug":"percentile-buckets","name":"Percentile buckets","h1":"Percentile buckets","category":"querying","lede":"Compute the cut points once, then bucket every row with a CASE.","engine_slug":"postgresql","problem":"You want every order tagged with a size band, where the bands come from the data's own quartiles rather than hard-coded thresholds.","sql":"WITH cutoffs AS (\n  SELECT PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY amount) AS p25,\n         PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY amount) AS p50,\n         PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY amount) AS p75\n  FROM orders\n)\nSELECT o.id, o.amount,\n       CASE\n         WHEN o.amount <= c.p25 THEN 'low'\n         WHEN o.amount <= c.p50 THEN 'medium'\n         WHEN o.amount <= c.p75 THEN 'high'\n         ELSE 'top'\n       END AS size_band\nFROM orders o\nCROSS JOIN cutoffs c\nORDER BY o.amount;","how_it_works":"The cutoffs CTE computes the three quartiles of all amounts in one scan; the CROSS JOIN attaches them to every row as constants. The CASE buckets each amount against them. PERCENTILE_CONT interpolates between values, giving smooth cut points; PERCENTILE_DISC returns an actual amount from the data if you prefer thresholds that really exist.","variants":[{"sql":"WITH banded AS (\n  SELECT id, amount,\n         NTILE(4) OVER (ORDER BY amount) AS quartile\n  FROM orders\n)\nSELECT id, amount,\n       CASE quartile\n         WHEN 1 THEN 'low'\n         WHEN 2 THEN 'medium'\n         WHEN 3 THEN 'high'\n         ELSE 'top'\n       END AS size_band\nFROM banded\nORDER BY amount;"}],"see_also":["median-per-group","ntile-deciles"],"faqs":[{"question":"Why are the bands not exactly 25% of rows each?","answer":"PERCENTILE_CONT buckets by value, and ties on the same amount all fall in the same band however many rows they contain. NTILE buckets by row count, so it guarantees quartile sizes but its cut points shift with ties."}]},"source_url":"https://sqlly.app/sql-snippets/percentile-buckets","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/percentile-outliers","corpus":"sql-snippets","engine":"all","language":"en","title":"Find outliers with percentiles","description":"Use NTILE to bucket ordered values and inspect the extreme tiles, or percentile_cont for a true percentile cut.","body":{"slug":"percentile-outliers","name":"Percentile outliers","h1":"Find outliers with percentiles","category":"data-quality","lede":"Order values and split them into equal tiles with NTILE; the first and last tiles hold the extremes that deserve a look.","engine_slug":"all","problem":"orders.total has a few absurd values: a 0.01 test order, a 999999 placeholder. Rank-based outliers surface them without choosing a threshold by hand.","sql":"WITH buckets AS (\n  SELECT id, total,\n         NTILE(20) OVER (ORDER BY total) AS vigintile\n  FROM orders\n  WHERE total IS NOT NULL\n)\nSELECT id, total, vigintile\nFROM buckets\nWHERE vigintile IN (1, 20)\nORDER BY total;","how_it_works":"NTILE(20) orders every non-NULL total and stamps each row with a tile number from 1 (lowest) to 20 (highest), each tile holding five percent of the rows. Selecting tiles 1 and 20 shows the bottom and top five percent. Values far from the mass of data are the candidates for correction or exclusion.","variants":[{"sql":"WITH bounds AS (\n  SELECT\n    PERCENTILE_CONT(0.01) WITHIN GROUP (ORDER BY total) AS p01,\n    PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY total) AS p99\n  FROM orders\n)\nSELECT o.id, o.total\nFROM orders o, bounds b\nWHERE o.total < b.p01 OR o.total > b.p99;"},{"sql":"WITH buckets AS (\n  SELECT status, total,\n         NTILE(20) OVER (PARTITION BY status ORDER BY total) AS vigintile\n  FROM orders\n  WHERE total IS NOT NULL\n)\nSELECT status, total\nFROM buckets\nWHERE vigintile IN (1, 20);"}],"see_also":["z-score-outliers","value-distribution-histogram"],"faqs":[{"question":"NTILE or percentile_cont?","answer":"NTILE runs on all five engines (SQLite since 3.25, MySQL since 8.0) and answers 'show me the bottom and top five percent' directly. PERCENTILE_CONT gives the exact interpolated threshold, while NTILE tiles differ in size by one row when the count does not divide evenly. Support is uneven: PostgreSQL and Oracle take the WITHIN GROUP aggregate form shown above, SQL Server only accepts it as a window function with OVER (), SQLite 3.47+ builds that include the percentile functions (the sqlite3 shell does) spell it percentile_cont(total, 0.99), and MySQL has none. Start with NTILE; switch when you need the numeric threshold itself."}]},"source_url":"https://sqlly.app/sql-snippets/percentile-outliers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/pivot-rows-to-columns-case","corpus":"sql-snippets","engine":"all","language":"en","title":"Pivot rows to columns with CASE","description":"Turn one row per order status into one row per customer with a column per status, using plain CASE expressions.","body":{"slug":"pivot-rows-to-columns-case","name":"Pivot rows to columns","h1":"Pivot rows to columns with CASE","category":"querying","lede":"The portable pivot: SUM(CASE WHEN ...) grouped by the row key. No PIVOT operator needed.","engine_slug":"all","problem":"Orders have one row per status change, but your report needs one row per customer with shipped, pending and cancelled totals side by side.","sql":"SELECT customer_id,\n       SUM(CASE WHEN status = 'shipped'   THEN amount ELSE 0 END) AS shipped_total,\n       SUM(CASE WHEN status = 'pending'   THEN amount ELSE 0 END) AS pending_total,\n       SUM(CASE WHEN status = 'cancelled' THEN amount ELSE 0 END) AS cancelled_total\nFROM orders\nGROUP BY customer_id\nORDER BY customer_id;","how_it_works":"Each CASE keeps only the amount of one status and turns the rest into 0, so the grouped SUM adds up each status into its own column. This is plain SQL: it runs on every engine, including the ones without a PIVOT operator. You must list the statuses in the query, which is fine for stable domains and annoying for hundreds of values.","variants":[{"sql":"SELECT customer_id,\n       SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS shipped_orders,\n       SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending_orders\nFROM orders\nGROUP BY customer_id;"},{"sql":"SELECT customer_id,\n       SUM(amount) FILTER (WHERE status = 'shipped') AS shipped_total,\n       SUM(amount) FILTER (WHERE status = 'pending') AS pending_total\nFROM orders\nGROUP BY customer_id;"}],"see_also":["unpivot-columns-to-rows","cross-tab-with-totals","count-if-recipe"],"faqs":[{"question":"Why not the PIVOT operator?","answer":"SQL Server and Oracle have one, but it still requires listing the column values, MySQL and SQLite do not have it at all, and the CASE form is usually easier to read. The PIVOT operator mainly wins when the aggregate expression is long and reused."}]},"source_url":"https://sqlly.app/sql-snippets/pivot-rows-to-columns-case","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/plan-regressions-query-store","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Find plan regressions with Query Store in SQL Server","description":"Compares each query's average duration over the last day with its previous 29 days in Query Store, to find queries that got slower, usually after a plan change.","body":{"slug":"plan-regressions-query-store","name":"Plan regressions","h1":"Find plan regressions with Query Store in SQL Server","category":"monitoring","lede":"Query Store remembers what each query used to cost, so \"it got slower last week\" becomes a number you can check.","engine_slug":"sql-server","problem":"Query Store (SQL Server 2016+) persists per-query runtime statistics in the database itself, surviving restarts and plan evictions. Comparing recent runtime stats against historical ones per query_id finds exactly the shape of a plan regression: the same query, suddenly slower than its own history, usually right after a plan change or statistics update.","sql":"WITH stats AS (\n    SELECT p.query_id,\n           CASE WHEN rs.last_execution_time >= DATEADD(DAY, -1, SYSUTCDATETIME()) THEN 'recent' ELSE 'historic' END AS period,\n           rs.avg_duration * rs.count_executions AS total_us,\n           rs.count_executions\n    FROM sys.query_store_runtime_stats rs\n    JOIN sys.query_store_plan p ON p.plan_id = rs.plan_id\n    WHERE rs.last_execution_time >= DATEADD(DAY, -30, SYSUTCDATETIME())\n), agg AS (\n    SELECT query_id,\n           SUM(CASE WHEN period = 'recent' THEN total_us END)\n             / NULLIF(SUM(CASE WHEN period = 'recent' THEN count_executions END), 0) / 1000.0 AS after_ms,\n           SUM(CASE WHEN period = 'historic' THEN total_us END)\n             / NULLIF(SUM(CASE WHEN period = 'historic' THEN count_executions END), 0) / 1000.0 AS before_ms,\n           SUM(CASE WHEN period = 'recent' THEN count_executions END) AS recent_executions\n    FROM stats\n    GROUP BY query_id\n)\nSELECT a.query_id, a.recent_executions,\n       CAST(a.before_ms AS DECIMAL(12,2)) AS before_ms,\n       CAST(a.after_ms AS DECIMAL(12,2)) AS after_ms,\n       CAST(a.after_ms / NULLIF(a.before_ms, 0) AS DECIMAL(10,2)) AS slowdown_factor,\n       LEFT(qt.query_sql_text, 120) AS query\nFROM agg a\nJOIN sys.query_store_query q ON q.query_id = a.query_id\nJOIN sys.query_store_query_text qt ON qt.query_text_id = q.query_text_id\nWHERE a.after_ms > a.before_ms * 2\nORDER BY slowdown_factor DESC;","how_it_works":"Query Store keeps one row per query in sys.query_store_query, one or more plans per query in sys.query_store_plan, and runtime statistics per plan per time interval (one hour by default) in sys.query_store_runtime_stats, with durations in microseconds. The query splits the last 30 days at 24 hours ago, then computes an execution-weighted average for each side: avg_duration times count_executions, summed and divided by total executions, so an interval with one run does not count as much as one with ten thousand. A slowdown_factor above 2 flags a candidate. The variant lists that query's plans; a new plan_id that dominates the recent intervals confirms a plan regression, and sp_query_store_force_plan pins the old plan while you find the cause.","variants":[{"sql":"DECLARE @query_id BIGINT = 42;  -- from the main query\n\nSELECT p.plan_id, p.is_forced_plan,\n       SUM(rs.count_executions) AS executions,\n       CAST(SUM(rs.avg_duration * rs.count_executions) / NULLIF(SUM(rs.count_executions), 0) / 1000.0 AS DECIMAL(12,2)) AS avg_ms,\n       MIN(rs.first_execution_time) AS first_seen,\n       MAX(rs.last_execution_time) AS last_seen\nFROM sys.query_store_plan p\nJOIN sys.query_store_runtime_stats rs ON rs.plan_id = p.plan_id\nWHERE p.query_id = @query_id\nGROUP BY p.plan_id, p.is_forced_plan\nORDER BY last_seen DESC;"}],"see_also":["top-queries-by-total-time","high-logical-reads-queries","statistics-staleness"],"faqs":[{"question":"Is Query Store on by default?","answer":"It is on by default for new databases from SQL Server 2022 onward and in Azure SQL Database. On SQL Server 2016 to 2019 it is off unless someone enabled it, and a database upgraded or restored onto a newer version keeps its old setting. Check actual_state_desc in sys.database_query_store_options; READ_ONLY usually means it ran out of its size quota. Enable it with ALTER DATABASE CURRENT SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE)."},{"question":"Should I force a plan as a fix?","answer":"As a first step, often yes: EXEC sp_query_store_force_plan @query_id = 42, @plan_id = 7 restores the old plan immediately while you work out why the optimizer switched (new statistics, a plan compiled for an unusual parameter value, data growth). The forced plan can become the wrong plan as data changes, and forcing fails if an index it uses is dropped (check force_failure_count in sys.query_store_plan), so review forced plans periodically. SQL Server 2017 and later can also do this automatically with automatic plan correction (FORCE_LAST_GOOD_PLAN)."}]},"source_url":"https://sqlly.app/sql-snippets/plan-regressions-query-store","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/previous-month-same-day","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Get the same day in the previous month in SQL","description":"Subtract one month from any date, and what happens when the target month has no 31st.","body":{"slug":"previous-month-same-day","name":"Previous month, same day","h1":"Get the same day in the previous month in SQL","category":"text","lede":"Month-over-month comparisons compare 'the 15th of this month' with 'the 15th of last month', not with '31 days ago'.","engine_slug":"postgresql","problem":"Subtracting an interval of one month does calendar-aware month arithmetic, not a fixed 30 days.","sql":"SELECT\n    d - interval '1 month' AS prev_month_same_day,\n    (date_trunc('month', d) - interval '1 day')::date AS prev_month_end\nFROM (SELECT DATE '2026-03-31' AS d) x;","how_it_works":"Subtracting interval '1 month' keeps the day number and rewinds the month. When the day does not exist (March 31 minus one month), PostgreSQL clamps to the last day of the target month, here 2026-02-28. SQL Server's DATEADD and MySQL's INTERVAL arithmetic clamp the same way. The result is a timestamp on PostgreSQL; cast it with ::date if you need a date. The second expression gives the previous month's end for month-to-month totals.","variants":[{"sql":"SELECT\n    DATEADD(MONTH, -1, d) AS prev_month_same_day,\n    EOMONTH(d, -1) AS prev_month_end\nFROM (SELECT CAST('2026-03-31' AS DATE) AS d) x;"},{"sql":"SELECT\n    d - INTERVAL 1 MONTH AS prev_month_same_day,\n    LAST_DAY(d - INTERVAL 1 MONTH) AS prev_month_end\nFROM (SELECT CURDATE() AS d) x;"}],"see_also":["month-over-month-delta","first-and-last-day-of-month"],"faqs":[{"question":"Why not just subtract 30 days?","answer":"Thirty days drifts: March 31 minus 30 days is March 1, still in the same month, because months run 28 to 31 days. Calendar-aware subtraction (interval '1 month', DATEADD(MONTH, -1, ...)) lands in the previous month every time."}]},"source_url":"https://sqlly.app/sql-snippets/previous-month-same-day","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/random-row","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Pick a random row","description":"Sort by a random value and take the first row, with the per-engine functions and a faster big-table option.","body":{"slug":"random-row","name":"Random row","h1":"Pick a random row","category":"querying","lede":"ORDER BY RANDOM() is the simple answer; TABLESAMPLE is the fast one.","engine_slug":"postgresql","problem":"You want one random order to feature on a dashboard. Sorting the whole table feels heavy, and it is, but for most tables it is fine.","sql":"SELECT id, customer_id, order_date, amount\nFROM orders\nORDER BY RANDOM()\nLIMIT 1;","how_it_works":"The engine computes a random value per row, sorts by it, and LIMIT 1 keeps the winner. That is a full scan plus a sort (PostgreSQL runs a top-N heapsort bounded by the LIMIT, so memory stays small, but every row is still read). The statement runs unchanged on SQLite; elsewhere only the function and row-limit syntax change: MySQL uses RAND(), SQL Server NEWID() with TOP (1), Oracle ORDER BY DBMS_RANDOM.VALUE FETCH FIRST 1 ROW ONLY. shuffled-sample draws many rows with this same TABLESAMPLE clause and shuffles them.","variants":[{"sql":"SELECT id, customer_id, order_date, amount\nFROM orders\nORDER BY RAND()\nLIMIT 1;"},{"sql":"SELECT TOP (1) id, customer_id, order_date, amount\nFROM orders\nORDER BY NEWID();"},{"sql":"SELECT id, customer_id, order_date, amount\nFROM orders TABLESAMPLE SYSTEM (1)\nLIMIT 1;"}],"see_also":["shuffled-sample","weighted-sample"],"faqs":[{"question":"How do I get a random row from a very large table cheaply?","answer":"TABLESAMPLE SYSTEM (1) reads about 1% of the table's pages and LIMIT 1 takes the first row it finds, so it is fast but rows on the same page are favoured together, and a small table can return nothing. SQL Server spells it TABLESAMPLE (1 PERCENT) with TOP (1), Oracle SAMPLE (1). Another trick is picking a random id in the known range and taking the first row with id >= that value; gaps from deleted ids make the rows after a gap more likely."}]},"source_url":"https://sqlly.app/sql-snippets/random-row","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/rank-within-category","corpus":"sql-snippets","engine":"all","language":"en","title":"Rank rows within a category","description":"Give every product a rank inside its own category with PARTITION BY, and size each group in the same pass.","body":{"slug":"rank-within-category","name":"Rank within category","h1":"Rank rows within a category","category":"querying","lede":"PARTITION BY restarts the ranking per category; a second window counts the group in the same pass.","engine_slug":"all","problem":"You want each product ranked by price within its category, plus how many products the category holds, so you can show '3rd of 25' style labels.","sql":"SELECT name, category, price,\n       RANK() OVER (PARTITION BY category\n                    ORDER BY price DESC) AS rank_in_category,\n       COUNT(*) OVER (PARTITION BY category) AS products_in_category\nFROM products\nORDER BY category, rank_in_category;","how_it_works":"PARTITION BY category makes both window functions restart from row one in every category. RANK orders products by price inside the partition; the unordered COUNT window counts every row in the partition, giving the group size without a second query. Ties share a rank, which is usually what a leaderboard wants.","variants":[{"sql":"SELECT name, category, price,\n       DENSE_RANK() OVER (PARTITION BY category\n                          ORDER BY price DESC) AS rank_in_category,\n       ROUND(100.0 * RANK() OVER (PARTITION BY category\n                                  ORDER BY price DESC)\n             / COUNT(*) OVER (PARTITION BY category), 1) AS percentile_in_category\nFROM products\nORDER BY category, rank_in_category;"}],"see_also":["top-n-with-ties","share-of-parent","ntile-deciles"],"faqs":[{"question":"Why not GROUP BY category?","answer":"GROUP BY collapses each category to one row and throws away the individual products. Window functions rank the rows and keep them, which is exactly the leaderboard shape."},{"question":"Why does the rank jump from 1 to 3 inside a category?","answer":"RANK gives tied rows the same number and skips the next one, so two products tied at rank 1 push the following product to 3 on every engine. DENSE_RANK keeps the numbers consecutive, and ROW_NUMBER breaks the tie by whichever column you add to the ORDER BY."}]},"source_url":"https://sqlly.app/sql-snippets/rank-within-category","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/re-parent-children-merge-duplicates","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Merge duplicate rows by re-parenting children","description":"Move the children of duplicate parents onto the surviving parent, folding lines that would collide into one, then retire the duplicates.","body":{"slug":"re-parent-children-merge-duplicates","name":"Re-parent children","h1":"Merge duplicate rows by re-parenting children","category":"data-quality","lede":"Pick one survivor line per product across the three orders, give it the combined quantity and move it to order 101, then delete the leftover lines and the empty duplicate orders.","engine_slug":"postgresql","problem":"Orders 102 and 103 are duplicates of order 101. Their order_items must move to 101, but 101 may already have a line for the same product, and 102 and 103 may both have one, so colliding lines must merge their quantities instead of moving blindly.","sql":"-- Run everything below in one transaction (BEGIN; ... COMMIT;)\n\n-- 1. One survivor line per product, carrying the combined quantity\nWITH lines AS (\n  SELECT id,\n         ROW_NUMBER() OVER (\n           PARTITION BY product_id\n           ORDER BY CASE WHEN order_id = 101 THEN 0 ELSE 1 END, id\n         ) AS rn,\n         SUM(quantity) OVER (PARTITION BY product_id) AS total_quantity\n  FROM order_items\n  WHERE order_id IN (101, 102, 103)\n)\nUPDATE order_items oi\nSET order_id = 101,\n    quantity = l.total_quantity\nFROM lines l\nWHERE l.id = oi.id\n  AND l.rn = 1;\n\n-- 2. Whatever is still on 102/103 was folded into a survivor\nDELETE FROM order_items WHERE order_id IN (102, 103);\n\n-- 3. Retire the now-empty duplicate orders\nDELETE FROM orders WHERE id IN (102, 103);","how_it_works":"The CTE ranks the lines of all three orders per product, preferring a line already on 101 and then the lowest id, and computes each product's total quantity across the three. The UPDATE moves each rank-1 line to 101 with that total, so every product ends up with exactly one line on the survivor. Every line still pointing at 102 or 103 afterwards is a copy whose quantity was just counted, which makes step 2 a plain DELETE. UPDATE ... FROM with a CTE is PostgreSQL syntax; SQL Server accepts the same shape with UPDATE oi SET ... FROM order_items oi JOIN lines l ON l.id = oi.id. Run the variant first and compare its totals with order 101 afterwards.","variants":[{"sql":"SELECT product_id,\n       COUNT(*) AS lines_now,\n       SUM(quantity) AS quantity_after_merge\nFROM order_items\nWHERE order_id IN (101, 102, 103)\nGROUP BY product_id\nORDER BY product_id;"}],"see_also":["delete-duplicates-keep-one","id-remap-preview","duplicate-natural-keys-different-ids"],"faqs":[{"question":"What happens to child data that has no equivalent on the survivor?","answer":"It moves as it is: a product only 102 had becomes a line on 101 with its original quantity, because it is the only line in its partition. Summing quantities is the right merge rule for order lines; for other children you may need a different one, such as keeping the newest note or concatenating comments, or tagging moved rows with their source id so the merge stays auditable."}]},"source_url":"https://sqlly.app/sql-snippets/re-parent-children-merge-duplicates","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/recursive-cte-cycle-guard","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Stop infinite loops in recursive CTEs","description":"Carry a visited-ids array through a recursive CTE and refuse to revisit a node, so cycles cannot loop forever.","body":{"slug":"recursive-cte-cycle-guard","name":"Cycle guard in recursive CTEs","h1":"Stop infinite loops in recursive CTEs","category":"querying","lede":"The visited list is the guard: no path may pass through the same node twice.","engine_slug":"postgresql","problem":"Your edges table can contain cycles and you still want a traversal that terminates without a hard depth limit.","sql":"WITH RECURSIVE walk AS (\n  SELECT e.src, e.dst,\n         ARRAY[e.src, e.dst] AS visited\n  FROM edges e\n  WHERE e.src = 1\n  UNION ALL\n  SELECT w.src, e.dst, w.visited || e.dst\n  FROM walk w\n  JOIN edges e ON e.src = w.dst\n  WHERE NOT e.dst = ANY(w.visited)\n)\nSELECT DISTINCT dst\nFROM walk\nORDER BY dst;","how_it_works":"Every row carries the path of nodes already visited as an array. The WHERE clause only expands an edge when its destination is not on that path, so no path can loop and the recursion runs dry instead of spinning. The guard is per path, not global: a node reachable by many routes is visited once per route, which can explode on dense graphs. PostgreSQL 14+ builds the same guard in with CYCLE dst SET is_cycle USING path. The depth-cap variant works everywhere once SQL Server and Oracle get their spelling: drop RECURSIVE and name the columns, WITH walk (src, dst, depth) AS (...).","variants":[{"sql":"WITH RECURSIVE walk AS (\n  SELECT e.src, e.dst, 1 AS depth\n  FROM edges e\n  WHERE e.src = 1\n  UNION ALL\n  SELECT w.src, e.dst, w.depth + 1\n  FROM walk w\n  JOIN edges e ON e.src = w.dst\n  WHERE w.depth < 20\n)\nSELECT DISTINCT dst FROM walk;"}],"see_also":["transitive-closure-recursive-cte","org-chart-walk"],"faqs":[{"question":"Visited array or depth cap?","answer":"The visited array is exact: it stops precisely at cycles and explores everything else, but it needs arrays (PostgreSQL) or a delimited path string elsewhere. The depth cap works on every engine and is trivial to reason about, but it can silently truncate deep legitimate paths, and on a cyclic graph it still re-walks the loop until the cap, so set the limit to the deepest real path you expect."}]},"source_url":"https://sqlly.app/sql-snippets/recursive-cte-cycle-guard","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/redundant-prefix-indexes","corpus":"sql-snippets","engine":"mysql","language":"en","title":"Find redundant indexes that are a prefix of another index in MySQL","description":"Uses sys.schema_redundant_indexes to find indexes whose columns are a leading prefix of another index on the same table, with a ready DROP INDEX statement.","body":{"slug":"redundant-prefix-indexes","name":"Redundant prefix indexes","h1":"Find redundant indexes that are a prefix of another index in MySQL","category":"indexes","lede":"An index on (a, b, c) can answer every lookup an index on (a) can. This finds the short indexes hiding behind longer ones.","engine_slug":"mysql","problem":"MySQL's sys schema ships a view for this: sys.schema_redundant_indexes compares the indexes on each table and reports one as redundant when another index starts with the same columns in the same order, or has exactly the same columns. An index on (customer_id) next to one on (customer_id, created_at) doubles the write cost on customer_id for no read benefit, because the longer index serves every lookup the shorter one can.","sql":"SELECT table_schema, table_name,\n       redundant_index_name, redundant_index_columns, redundant_index_non_unique,\n       dominant_index_name, dominant_index_columns, dominant_index_non_unique,\n       subpart_exists, sql_drop_index\nFROM sys.schema_redundant_indexes\nORDER BY table_schema, table_name, redundant_index_name;","how_it_works":"The view is built on information_schema.STATISTICS: it flattens each index into a column list in SEQ_IN_INDEX order and pairs indexes on the same table where one list is a prefix of, or equal to, the other. The *_non_unique columns show 0 for a unique index. A unique index is never reported as redundant to a non-unique one, since dropping it would drop the rule. The reverse can happen: with UNIQUE (a) in place, an index on (a, b) is reported as redundant to it, because a lookup on a already finds at most one row. subpart_exists = 1 means a prefix-length column such as name(10) is involved, so compare the definitions by hand. sql_drop_index holds the generated ALTER TABLE ... DROP INDEX. Exact duplicates are reported once, with one index as redundant to the other. Before dropping, search the code for FORCE INDEX or USE INDEX hints naming the index, because those queries fail once it is gone.","variants":[{"sql":"SELECT s.TABLE_SCHEMA, s.TABLE_NAME,\n       s.INDEX_NAME AS redundant_index, s.cols AS redundant_columns,\n       d.INDEX_NAME AS dominant_index, d.cols AS dominant_columns\nFROM (SELECT TABLE_SCHEMA, TABLE_NAME, INDEX_NAME, MIN(NON_UNIQUE) AS NON_UNIQUE,\n             GROUP_CONCAT(CONCAT(COLUMN_NAME, IFNULL(CONCAT('(', SUB_PART, ')'), ''))\n                          ORDER BY SEQ_IN_INDEX) AS cols\n      FROM information_schema.STATISTICS\n      WHERE TABLE_SCHEMA = DATABASE() AND INDEX_TYPE = 'BTREE'\n      GROUP BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME\n      HAVING SUM(COLUMN_NAME IS NULL) = 0) s\nJOIN (SELECT TABLE_SCHEMA, TABLE_NAME, INDEX_NAME,\n             GROUP_CONCAT(CONCAT(COLUMN_NAME, IFNULL(CONCAT('(', SUB_PART, ')'), ''))\n                          ORDER BY SEQ_IN_INDEX) AS cols\n      FROM information_schema.STATISTICS\n      WHERE TABLE_SCHEMA = DATABASE() AND INDEX_TYPE = 'BTREE'\n      GROUP BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME) d\n  ON d.TABLE_SCHEMA = s.TABLE_SCHEMA\n AND d.TABLE_NAME = s.TABLE_NAME\n AND d.INDEX_NAME <> s.INDEX_NAME\n AND LEFT(d.cols, CHAR_LENGTH(s.cols) + 1) = CONCAT(s.cols, ',')\nWHERE s.NON_UNIQUE = 1\nORDER BY s.TABLE_NAME, s.INDEX_NAME;"}],"see_also":["duplicate-indexes","unused-indexes","largest-indexes"],"faqs":[{"question":"Is a prefix index always safe to drop when a longer one exists?","answer":"For reads, nearly always: a query that can use (a) can use (a, b, c). Three things to check first. A UNIQUE index on (a) enforces something the longer index does not, so keep it. A foreign key on a needs some index that leads with a, and InnoDB will use the longer one, but DROP INDEX fails if no other index qualifies. And the longer index is wider, so a range scan on a alone reads more pages through it than through the short one; on a hot query that difference can be measurable."},{"question":"Does every MySQL server have the sys schema?","answer":"MySQL 5.7.7 and later install it by default, including 8.0 and 8.4, unless someone dropped it or the server was set up with it disabled. Where it is missing, the information_schema variant finds strict prefix pairs for the current database. It skips functional indexes and does not list exact duplicates; to find those, change the join condition to d.cols = s.cols AND d.INDEX_NAME < s.INDEX_NAME."}]},"source_url":"https://sqlly.app/sql-snippets/redundant-prefix-indexes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/referential-audit-both-directions","corpus":"sql-snippets","engine":"all","language":"en","title":"Audit all foreign keys in both directions","description":"One labeled result set counting orphans per foreign-key relationship across the whole schema.","body":{"slug":"referential-audit-both-directions","name":"Referential audit","h1":"Audit all foreign keys in both directions","category":"data-quality","lede":"Stack a LEFT JOIN anti-join per foreign key with UNION ALL to get an orphan count for every relationship in one query.","engine_slug":"all","problem":"Before trusting a vendor database, run one integrity sweep: for each FK relationship, how many child rows point at a missing parent? The labeled output doubles as documentation of the schema's relationships.","sql":"SELECT 'orders.customer_id -> customers.id' AS relationship,\n       COUNT(*) AS orphaned_rows\nFROM orders o\nLEFT JOIN customers c ON c.id = o.customer_id\nWHERE o.customer_id IS NOT NULL AND c.id IS NULL\nUNION ALL\nSELECT 'order_items.order_id -> orders.id', COUNT(*)\nFROM order_items oi\nLEFT JOIN orders o ON o.id = oi.order_id\nWHERE oi.order_id IS NOT NULL AND o.id IS NULL\nUNION ALL\nSELECT 'order_items.product_id -> products.id', COUNT(*)\nFROM order_items pi\nLEFT JOIN products p ON p.id = pi.product_id\nWHERE pi.product_id IS NOT NULL AND p.id IS NULL\nORDER BY orphaned_rows DESC;","how_it_works":"Each branch is the orphan check for one relationship: LEFT JOIN the parent, keep rows the join could not satisfy, and COUNT them under a descriptive label. UNION ALL stacks the cheap counts into one report, and the engine cannot skip a branch even when a constraint exists, which is the point: NOT VALID on PostgreSQL and NOCHECK on SQL Server leave orphans in place for exactly this query to find. ORDER BY puts the most damaged relationship on top; a clean schema returns all zeros. multi-parent-orphan-sweep counts orphans per relationship from one child table; this audit stacks every relationship in the schema into one report.","variants":[{"sql":"SELECT 'customers with no orders' AS relationship, COUNT(*) AS row_count\nFROM customers c\nWHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)\nUNION ALL\nSELECT 'orders with no items', COUNT(*)\nFROM orders o\nWHERE NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.order_id = o.id);"}],"see_also":["find-orphaned-rows","multi-parent-orphan-sweep","missing-parent-references"],"faqs":[{"question":"Why label with column -> column strings?","answer":"The labels are free text, so this report reads the same for a developer and a stakeholder, and each row names the exact join to write when fixing the orphans. Keep one branch per declared or planned foreign key and the query becomes an integrity checklist you can rerun after every import."},{"question":"Do enforced foreign keys make this audit redundant?","answer":"No: a foreign key added NOT VALID on PostgreSQL still allows existing orphans, and SQL Server's NOCHECK leaves rows unchecked until you re-enable it. Run the count anyway and re-validate with ALTER TABLE ... VALIDATE CONSTRAINT where the flag is set."}]},"source_url":"https://sqlly.app/sql-snippets/referential-audit-both-directions","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/remove-all-whitespace","corpus":"sql-snippets","engine":"all","language":"en","title":"Remove all whitespace from a string in SQL","description":"Strip every space, tab and line break out of a value such as a phone number or account code.","body":{"slug":"remove-all-whitespace","name":"Remove all whitespace","h1":"Remove all whitespace from a string in SQL","category":"text","lede":"Phone numbers, account codes and search keys should not contain blanks at all. Clean them in one expression.","engine_slug":"all","problem":"Imported values contain blanks everywhere. Before matching them against clean reference data, delete every space (and, where the engine allows, tab and break characters).","sql":"SELECT REPLACE(phone_raw, ' ', '') AS phone_clean\nFROM contacts;","how_it_works":"REPLACE simply deletes each space. It exists on every engine, so the basic form is fully portable. When you also need tabs, carriage returns and line feeds gone, chain more REPLACE calls with each engine's character function: CHAR(n) on SQL Server, MySQL and SQLite, CHR(n) on PostgreSQL and Oracle.","variants":[{"sql":"SELECT REPLACE(REPLACE(REPLACE(REPLACE(phone_raw, ' ', ''), CHAR(9), ''), CHAR(13), ''), CHAR(10), '') AS phone_clean\nFROM contacts;"},{"sql":"SELECT REPLACE(REPLACE(REPLACE(REPLACE(phone_raw, ' ', ''), CHR(9), ''), CHR(13), ''), CHR(10), '') AS phone_clean\nFROM contacts;"}],"see_also":["normalize-whitespace","remove-non-printable-characters"],"faqs":[{"question":"Why not just compare after TRIM?","answer":"TRIM only removes characters at the two ends. An interior blank like '555  0100' still fails to match '5550100', so delete interior blanks too when the target format has none."}]},"source_url":"https://sqlly.app/sql-snippets/remove-all-whitespace","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/remove-column-default","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Remove a column default","description":"Drop a default from a column: one statement on MySQL and PostgreSQL, a constraint lookup first on SQL Server, where defaults are named objects.","body":{"slug":"remove-column-default","name":"Remove a column default","h1":"Remove a column default","category":"schema","lede":"Removing a default is the reverse of setting one: future inserts must supply the value explicitly or get NULL. The mechanics differ most on SQL Server, where the default is a named constraint you must find first.","engine_slug":"postgresql","problem":"Application code now always supplies the value, so the lingering default only hides bugs by filling in omitted inserts. SQL Server makes this a two-step job because its defaults are named objects.","sql":"ALTER TABLE users\n  ALTER COLUMN is_active DROP DEFAULT;","how_it_works":"DROP DEFAULT removes the value used for omitted inserts but changes no existing rows, and the statement is catalog-only. On PostgreSQL an omitted column then gets NULL, so inserts that skip a NOT NULL column start failing. Check for INSERT paths that omit the column before removing the default. Re-running is harmless: dropping an absent default is a no-op.","variants":[{"sql":"-- look up the (often system-generated) constraint name first\nDECLARE @df sysname, @sql nvarchar(400);\nSELECT @df = dc.name\nFROM sys.default_constraints dc\nJOIN sys.columns c ON c.object_id = dc.parent_object_id\n                  AND c.column_id = dc.parent_column_id\nWHERE dc.parent_object_id = OBJECT_ID('dbo.Users')\n  AND c.name = 'IsActive';\nIF @df IS NOT NULL\nBEGIN\n    SET @sql = N'ALTER TABLE dbo.Users DROP CONSTRAINT ' + QUOTENAME(@df);\n    EXEC sp_executesql @sql;\nEND;"},{"sql":"ALTER TABLE users\n  ALTER COLUMN is_active DROP DEFAULT;\n-- in strict mode this makes even a nullable column mandatory\n-- in INSERTs; to keep omitted inserts storing NULL, use\n-- ALTER TABLE users ALTER COLUMN is_active SET DEFAULT NULL;"},{"sql":"-- defaults are part of the column definition; rebuild the\n-- table with the new definition (see set-column-default)"}],"see_also":["set-column-default","change-column-nullable","make-column-not-null-safely"],"faqs":[{"question":"What is the difference between DROP DEFAULT and setting NULL?","answer":"On PostgreSQL there is none: a column without a default behaves as DEFAULT NULL. On MySQL they differ. After DROP DEFAULT the column has no default at all, and in strict mode an INSERT that omits it fails with error 1364 even if the column is nullable; SET DEFAULT NULL keeps those inserts working and stores NULL. MySQL rejects SET DEFAULT NULL on a NOT NULL column."}]},"source_url":"https://sqlly.app/sql-snippets/remove-column-default","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/remove-emojis-control-chars","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Remove emojis and symbol characters in SQL","description":"Strip emoji ranges out of user text on PostgreSQL with Unicode-aware regex patterns.","body":{"slug":"remove-emojis-control-chars","name":"Remove emojis and pictographs","h1":"Remove emojis and symbol characters in SQL","category":"text","lede":"Slack-style names and comments full of \uD83C\uDF89 break fixed-width exports and old clients. Remove the pictograph ranges.","engine_slug":"postgresql","problem":"Emoji live in defined Unicode blocks. PostgreSQL regex escapes \\Uhhhhhhhh (8 hex digits) and \\uhhhh (4 hex digits) name code points, so whole blocks can be matched and deleted.","sql":"SELECT regexp_replace(display_text, '[\\U0001F000-\\U0001FAFF\\u2600-\\u27BF\\uFE0F]', '', 'g') AS clean_text\nFROM comments;","how_it_works":"The pattern matches the emoji and pictograph blocks (1F000-1FAFF), dingbats and misc symbols (2600-27BF) and the variation selector FE0F, deleting every match. Extend or trim the ranges to match what your data actually contains; new emoji keep moving the upper bound.","variants":[{"sql":"SELECT REGEXP_REPLACE(display_text,\n         '[' || UNISTR('\\D83C\\DC00') || '-' || UNISTR('\\D83E\\DEFF')\n             || UNISTR('\\2600') || '-' || UNISTR('\\27BF') || UNISTR('\\FE0F') || ']', '') AS clean_text\nFROM comments;"},{"sql":"SELECT REGEXP_REPLACE(display_text, '[\\\\x{1F000}-\\\\x{1FAFF}\\\\x{2600}-\\\\x{27BF}\\\\x{FE0F}]', '') AS clean_text\nFROM comments;"}],"see_also":["remove-non-printable-characters","replace-multiple-patterns"],"faqs":[{"question":"What about SQL Server?","answer":"SQL Server 2025 adds REGEXP_REPLACE, so a character-class pattern works there. On 2022 and older there is no regex: chain REPLACE for the specific emoji you care about, or clean the text once in application code or an ETL step rather than in every query."},{"question":"Why does the MySQL pattern never match on my table?","answer":"The regex works on characters, and a column still in utf8mb3 cannot even store a 4-byte emoji: strict mode rejects the write and older rows keep a mangled placeholder. Convert the column to utf8mb4 first, or there is nothing for the pattern to find."}]},"source_url":"https://sqlly.app/sql-snippets/remove-emojis-control-chars","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/remove-non-printable-characters","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Remove non-printable and control characters in SQL","description":"Delete control characters and other unprintable bytes that ride along with pasted or imported text.","body":{"slug":"remove-non-printable-characters","name":"Remove non-printable characters","h1":"Remove non-printable and control characters in SQL","category":"text","lede":"Pasted text often carries zero-width characters, form feeds or stray control bytes that break matching and exports. Strip them down to printable text.","engine_slug":"postgresql","problem":"Free-text fields accumulate control characters from copy-paste and imports. They are invisible on screen but break joins, exports and full-text search.","sql":"SELECT REGEXP_REPLACE(comment_text, '[^' || chr(32) || '-' || chr(126) || ']', '', 'g') AS clean_text\nFROM comments;","how_it_works":"The pattern matches any character outside the printable ASCII range (space through tilde) and deletes it, so control characters, zero-width spaces and every non-ASCII letter go. This is the strictest form. If you want to keep accented letters, delete only the control range instead: '[[:cntrl:]]' on PostgreSQL and Oracle.","variants":[{"sql":"SELECT REGEXP_REPLACE(comment_text, '[^' || CHR(32) || '-' || CHR(126) || ']', '') AS clean_text\nFROM comments;"},{"sql":"SELECT REPLACE(REPLACE(REPLACE(comment_text, CHAR(9), ''), CHAR(10), ''), CHAR(13), '') AS clean_text\nFROM comments;"}],"see_also":["remove-emojis-control-chars","normalize-whitespace"],"faqs":[{"question":"Does this delete accented letters and emojis?","answer":"Yes, the strict pattern keeps ASCII printable characters only. That is usually what you want for codes and keys, but for human text prefer a pattern that keeps non-ASCII letters and only drops control characters. SQL Server 2025 adds REGEXP_REPLACE, which replaces every match by default: REGEXP_REPLACE(comment_text, '[^ -~]', '') is the same strict filter there."}]},"source_url":"https://sqlly.app/sql-snippets/remove-non-printable-characters","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/rename-column-if-exists","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Rename a column if it exists","description":"Guarded column renames: check the metadata first so re-running the migration is a no-op instead of an error.","body":{"slug":"rename-column-if-exists","name":"Rename column if exists","h1":"Rename a column if it exists","category":"schema","lede":"Renames fail loudly when the column is already renamed, which breaks idempotent migrations. Guard the rename with a metadata check per engine.","engine_slug":"sql-server","problem":"One environment already has the new column name and another does not, so the migration has to detect which state it is in before it acts.","sql":"IF COL_LENGTH('dbo.Users', 'username') IS NOT NULL\n    EXEC sp_rename 'dbo.Users.username', 'user_name', 'COLUMN';","how_it_works":"COL_LENGTH returns NULL for a missing column, so the IF makes the block a no-op once the column has been renamed; SQL Server has no IF EXISTS clause for renames. sp_rename takes the old name qualified and the new name bare; qualifying the new name too would make the brackets part of the column name. sp_rename does not update views or procedures that mention the old name, so search sys.sql_modules for it afterwards.","variants":[{"sql":"-- RENAME COLUMN has no IF EXISTS; guard it with a DO block\nDO $$\nBEGIN\n  IF EXISTS (SELECT 1 FROM information_schema.columns\n             WHERE table_schema = 'public' AND table_name = 'users'\n               AND column_name = 'username') THEN\n    ALTER TABLE public.users RENAME COLUMN username TO user_name;\n  END IF;\nEND $$;"},{"sql":"-- RENAME COLUMN needs MySQL 8.0+; no IF EXISTS, so build\n-- the statement conditionally\nSET @sql := IF(EXISTS (\n    SELECT 1 FROM information_schema.columns\n    WHERE table_schema = DATABASE()\n      AND table_name = 'users' AND column_name = 'username'),\n  'ALTER TABLE users RENAME COLUMN username TO user_name',\n  'DO 0');\nPREPARE stmt FROM @sql;\nEXECUTE stmt;\nDEALLOCATE PREPARE stmt;"},{"sql":"ALTER TABLE users RENAME COLUMN username TO user_name;\n-- SQLite 3.25+; also rewrites references in indexes,\n-- triggers and views. Check pragma_table_info first."}],"see_also":["rename-table-safely","add-column-if-missing","find-tables-with-column"],"faqs":[{"question":"What breaks when a column is renamed?","answer":"Anything that stores the old name as text. Views on MySQL and SQL Server keep the old name and fail at the next SELECT; PostgreSQL views follow the rename because they reference columns by number. Stored procedures and functions, ORM mappings, reports and SQL in application code all break on every engine. Search the codebase and the module definitions for the old name before the rename, not after."},{"question":"Is the rename itself instant on every engine?","answer":"Yes, it is catalog work everywhere here: PostgreSQL's ALTER TABLE RENAME, MySQL 8's RENAME COLUMN, SQLite's RENAME COLUMN (3.25+) and SQL Server's sp_rename all touch metadata, never rows. The expensive part is the aftermath: views and procedures that spelled the old name need recreating."}]},"source_url":"https://sqlly.app/sql-snippets/rename-column-if-exists","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/rename-table-safely","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Rename a table safely","description":"One-statement table renames on each engine, and the checks to run first, since views, procedures and application queries may still use the old name.","body":{"slug":"rename-table-safely","name":"Rename a table safely","h1":"Rename a table safely","category":"schema","lede":"Renaming a table is instant at the database level. The risk is everything outside the database that spells the old name: views, foreign keys, application code and dashboards.","engine_slug":"postgresql","problem":"The table needs a new name to match a reworked domain model, and nothing in the database or the application should break when the rename lands.","sql":"ALTER TABLE users RENAME TO users_archive;\n-- catalog-only change; views and foreign keys reference the\n-- table by OID, so they follow it to the new name","how_it_works":"The rename is a catalog update, so its duration does not depend on table size, but it needs an ACCESS EXCLUSIVE lock: it waits for running queries on the table and blocks new ones while waiting, so set lock_timeout on a busy system. On PostgreSQL, views and foreign keys follow the table. Function bodies, dynamic SQL, scripts and application code that use the old name now fail. Search them for the name before renaming.","variants":[{"sql":"RENAME TABLE users TO users_archive;\n-- foreign keys follow the table, but views store the name\n-- and fail until recreated against users_archive"},{"sql":"EXEC sp_rename 'dbo.Users', 'Users_Archive';\n-- sp_rename does NOT update referencing objects; check\n-- sys.sql_modules for stale definitions afterwards"},{"sql":"ALTER TABLE users RENAME TO users_archive;\n-- views and triggers are rewritten to the new name since\n-- 3.25, FKs in other tables since 3.26, unless\n-- legacy_alter_table is on (macOS's bundled sqlite3 sets it)"}],"see_also":["swap-two-table-names","rename-column-if-exists","move-table-between-schemas"],"faqs":[{"question":"Will my foreign keys still work after a rename?","answer":"Yes. On every engine here, foreign keys stay attached to the renamed table and keep enforcing (SQLite rewrites the REFERENCES clause unless legacy_alter_table is on). Views are where engines differ: PostgreSQL and SQLite update them, MySQL and SQL Server views keep the old name and fail until you recreate them. Code and dynamic SQL that spell the old name break everywhere."},{"question":"Does MySQL need a transaction for a rename?","answer":"RENAME TABLE cannot run inside a transaction, but it accepts several renames in one statement and applies them all atomically, which is the primitive the swap-two-table-names recipe builds on. PostgreSQL, SQL Server and SQLite get the same all-or-nothing behavior from the surrounding transaction."}]},"source_url":"https://sqlly.app/sql-snippets/rename-table-safely","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/replace-multiple-patterns","corpus":"sql-snippets","engine":"all","language":"en","title":"Replace multiple patterns in one SQL expression","description":"Clean '(555) 010-0111' to '5550100111' by nesting REPLACE, or use TRANSLATE for single-character maps.","body":{"slug":"replace-multiple-patterns","name":"Replace multiple patterns at once","h1":"Replace multiple patterns in one SQL expression","category":"text","lede":"Phone numbers arrive with parentheses, dashes and spaces. Delete every punctuation variant in one expression.","engine_slug":"all","problem":"Before dialing or joining on phone numbers, remove parentheses, dashes and spaces in one go.","sql":"SELECT REPLACE(REPLACE(REPLACE(REPLACE(phone_raw, '(', ''), ')', ''), '-', ''), ' ', '') AS phone_clean\nFROM contacts;","how_it_works":"Each REPLACE strips one pattern, applied inside-out. This is fully portable because REPLACE exists on every engine, and the pattern set is explicit in the code. It gets unwieldy past four or five patterns; that is where TRANSLATE helps for single characters, though each engine treats a missing replacement character differently (see the variants).","variants":[{"sql":"SELECT TRANSLATE(phone_raw, '()- ', '') AS phone_clean\nFROM contacts;"},{"sql":"SELECT TRANSLATE(phone_raw, '#()- ', '#') AS phone_clean\nFROM contacts;"}],"see_also":["remove-non-printable-characters","remove-all-whitespace","format-money-string"],"faqs":[{"question":"Why does the TRANSLATE variant only handle single characters?","answer":"TRANSLATE maps each character in the second argument to the character at the same position in the third; it works on characters, not substrings, so it cannot target a sequence like 'ext.'. PostgreSQL and Oracle delete characters that have no partner. SQL Server 2017+ requires both lists to be the same length, so it can only substitute (for example to spaces, then one REPLACE), and MySQL and SQLite have no TRANSLATE."}]},"source_url":"https://sqlly.app/sql-snippets/replace-multiple-patterns","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/replication-lag","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Measure replication lag in PostgreSQL","description":"Shows per-standby WAL replay lag in bytes and time from pg_stat_replication, with the standby-side seconds-behind check.","body":{"slug":"replication-lag","name":"Replication lag","h1":"Measure replication lag in PostgreSQL","category":"monitoring","lede":"How far behind are the standbys? The primary reports it in bytes and time per standby; the standby can report its own delay.","engine_slug":"postgresql","problem":"Replication lag is the gap between the WAL the primary has written and what each standby has received, flushed and replayed. A little lag is normal. Growing lag means a standby cannot keep up, because of network, disk, or queries on the standby holding up replay. With asynchronous replication, the unreceived part is what a failover would lose, and the unreplayed part is how stale reads on the standby are. pg_stat_replication on the primary has one row per connected standby.","sql":"SELECT client_addr, application_name, state, sync_state,\n       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes,\n       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS replay_backlog,\n       write_lag, flush_lag, replay_lag\nFROM pg_stat_replication\nORDER BY replay_lag_bytes DESC;","how_it_works":"Run it on the primary. pg_wal_lsn_diff gives the byte distance between the primary's current WAL position and the standby's replay position. write_lag, flush_lag and replay_lag are the times between the primary writing recent WAL and the standby reporting it written, flushed to disk and replayed. Data-loss exposure on failover depends on flush, and read staleness on replay. A standby with small flush_lag and large replay_lag is receiving WAL fine but applying it slowly, often because a long query on the standby is blocking replay. The *_lag columns go NULL after the standby has caught up and the primary has been idle for a moment, so NULL there is not an error.","variants":[{"sql":"SELECT pg_is_in_recovery() AS in_recovery,\n       pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() AS caught_up,\n       now() - pg_last_xact_replay_timestamp() AS since_last_replayed_commit;"},{"sql":"SHOW REPLICA STATUS;\n-- MySQL 8.0.22 and later. Key columns: Seconds_Behind_Source,\n-- Replica_IO_Running, Replica_SQL_Running, Last_IO_Error, Last_SQL_Error.\n-- Older versions: SHOW SLAVE STATUS with Seconds_Behind_Master."}],"see_also":["long-transactions","wal-redo-size","checkpoint-warnings"],"faqs":[{"question":"The primary shows no lag, but a standby is behind. How?","answer":"pg_stat_replication lists only standbys that are connected right now. A standby whose connection dropped has no row, so it shows no lag at all while it falls further behind; if it uses a replication slot, pg_replication_slots shows it with active = false and an old restart_lsn. The reverse confusion happens on the standby side: since_last_replayed_commit keeps growing on a quiet primary even though nothing is waiting to be applied, so check caught_up in the same variant before alerting on it. The primary-side byte count is the better alert for a quiet system."},{"question":"What makes replay lag grow suddenly?","answer":"Common causes: a bulk load, index build or large UPDATE on the primary producing WAL faster than the network or the standby's disk can take it; queries on the standby that conflict with replay, which pause replay for up to max_standby_streaming_delay (30 seconds by default, -1 means indefinitely); and replay being single-threaded, so one standby CPU core can be the limit. Frequent checkpoints on the primary make it worse, because each one triggers full-page images and more WAL; see the checkpoint-warnings recipe."}]},"source_url":"https://sqlly.app/sql-snippets/replication-lag","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/restore-able-rows","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"List soft-deleted rows that can be restored","description":"Rows with a deleted_at still inside the retention window: the undo list for soft deletes.","body":{"slug":"restore-able-rows","name":"Restore-able rows","h1":"List soft-deleted rows that can be restored","category":"data-quality","lede":"Select rows where deleted_at is set and recent enough to be within your retention window, newest first: that is the restore list.","engine_slug":"postgresql","problem":"Support asks to un-delete a customer from last week. Soft deletes make that a SELECT away, provided you catch them before retention or a hard-delete job removes them.","sql":"SELECT id, email, name, deleted_at\nFROM customers\nWHERE deleted_at IS NOT NULL\n  AND deleted_at >= CURRENT_TIMESTAMP - INTERVAL '30 days'\nORDER BY deleted_at DESC;","how_it_works":"The first condition keeps only soft-deleted rows; the second bounds them to the 30-day retention window so the list matches what a restore job would still accept. Ordering by deleted_at DESC puts the freshest undo candidates on top. The variant shows the UPDATE that brings a row back.","variants":[{"sql":"BEGIN;\nUPDATE customers\nSET deleted_at = NULL\nWHERE id = 42\n  AND deleted_at IS NOT NULL;\n-- expect UPDATE 1, then COMMIT; anything else, ROLLBACK;"},{"sql":"SELECT id, email, name, deleted_at\nFROM customers\nWHERE deleted_at IS NOT NULL\n  AND deleted_at >= NOW() - INTERVAL 30 DAY\nORDER BY deleted_at DESC;"}],"see_also":["soft-delete-audit","cascade-impact-preview"],"faqs":[{"question":"Should restoring also restore the row's children?","answer":"If the parent was soft-deleted with a cascade of soft deletes on its children, yes. A customer restored while their orders stay deleted is a new kind of inconsistency. Either cascade the restore the same way the delete cascaded, or design soft deletes to flag the parent only and derive child visibility from it."}]},"source_url":"https://sqlly.app/sql-snippets/restore-able-rows","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/revoke-all-privileges","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Revoke all privileges","description":"Strip a departing role's access to tables and sequences in one pass, with the syntax on each engine and the ownership problem that blocks DROP ROLE.","body":{"slug":"revoke-all-privileges","name":"Revoke all privileges","h1":"Revoke all privileges","category":"schema","lede":"When someone leaves or a service is decommissioned, its access should go with it. Revoke table and sequence privileges in one pass rather than hunting them down object by object.","engine_slug":"postgresql","problem":"A contractor finished or a service was retired, and its role must lose every grant now rather than turning up in the next access audit.","sql":"REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM intern;\nREVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM intern;\n-- and, for completeness, schema usage itself\nREVOKE USAGE ON SCHEMA public FROM intern;","how_it_works":"REVOKE ALL PRIVILEGES ON ALL TABLES removes every table-level privilege (SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER and, on PostgreSQL 17+, MAINTAIN) from tables existing in the schema. It does not touch role membership, privileges granted to PUBLIC, or default privileges, so check pg_auth_members and pg_default_acl too. Each database in the cluster keeps its own grants, so repeat it per database.","variants":[{"sql":"-- ON mydb.* removes database-level grants only, and errors\n-- (1141) if there are none. This form removes every global,\n-- database, table, column and routine grant at once:\nREVOKE ALL PRIVILEGES, GRANT OPTION FROM 'intern'@'%';\nSHOW GRANTS FOR 'intern'@'%';  -- verify what remains"},{"sql":"-- REVOKE ALL is deprecated, and ALL has no mapping for schemas\n-- at all, so name the permissions\nREVOKE SELECT, INSERT, UPDATE, DELETE, EXECUTE\n    ON SCHEMA::dbo FROM intern;\n-- DENY beats grants from role membership too, db_owner\n-- included (not sysadmin or the dbo user itself);\n-- ALTER ROLE ... DROP MEMBER removes the memberships\nDENY SELECT ON SCHEMA::dbo TO intern;"}],"see_also":["list-user-privileges","grant-select-all-tables","default-privileges-future-tables"],"faqs":[{"question":"Can I revoke if the role owns objects?","answer":"You can, but it changes little: an owner's rights come from ownership, not from grants, and PostgreSQL refuses DROP ROLE while the role owns objects or holds privileges. In each database run REASSIGN OWNED BY intern TO app_owner, then DROP OWNED BY intern, which also revokes every privilege granted to intern there. After that DROP ROLE intern succeeds."},{"question":"Does revoking stop the role's active sessions?","answer":"No: existing connections keep running, and the role can simply log back in while it still has login rights. Pair the revoke with ALTER ROLE intern NOLOGIN on PostgreSQL, ALTER USER intern ACCOUNT LOCK on MySQL, or ALTER LOGIN intern DISABLE on SQL Server."}]},"source_url":"https://sqlly.app/sql-snippets/revoke-all-privileges","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/rotate-partition","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Rotate a table partition","description":"Add next month's partition and detach an expired one, which replaces a huge archive DELETE with two catalog operations.","body":{"slug":"rotate-partition","name":"Rotate a partition","h1":"Rotate a table partition","category":"schema","lede":"Instead of deleting old rows, rotate whole partitions: attach an empty one for the new period, detach the full one for the expired period. Both steps are metadata operations, no row copying.","engine_slug":"postgresql","problem":"A time-series table grows without bound and the monthly purge has become a multi-hour, lock-holding DELETE. Partition rotation turns it into two instant catalog operations.","sql":"-- attach the new period's partition\nCREATE TABLE measurements_2026_12\n  PARTITION OF measurements\n  FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');\n\n-- detach an expired one; its rows stay in what becomes a\n-- standalone table. CONCURRENTLY (PostgreSQL 14+) avoids\n-- blocking queries on the parent, but cannot run in a transaction.\nALTER TABLE measurements\n  DETACH PARTITION measurements_2024_11;","how_it_works":"CREATE TABLE ... PARTITION OF registers a new empty partition for the declared range, and DETACH PARTITION removes an old one from the parent without moving a row; both are catalog changes. The detached table becomes an ordinary table you can dump, archive or drop. Plain DETACH takes an ACCESS EXCLUSIVE lock on the parent, so it waits for running queries and blocks new ones until it gets the lock; DETACH ... CONCURRENTLY, added in PostgreSQL 14, uses a weaker lock.","variants":[{"sql":"-- table PARTITION BY RANGE COLUMNS (ts); split the catch-all\n-- partition (instant while it is empty), then drop the oldest\nALTER TABLE measurements\n  REORGANIZE PARTITION p_future INTO (\n    PARTITION p2026_12 VALUES LESS THAN ('2027-01-01'),\n    PARTITION p_future VALUES LESS THAN (MAXVALUE));\nALTER TABLE measurements DROP PARTITION p2024_11;\n-- DROP PARTITION deletes its rows; to keep them, first move\n-- them out with EXCHANGE PARTITION ... WITH TABLE"},{"sql":"-- ATTACH scans the table to prove every row fits the bounds;\n-- a matching valid CHECK constraint lets it skip the scan\nALTER TABLE measurements_2024_11\n  ADD CONSTRAINT m_2024_11_bounds\n  CHECK (ts IS NOT NULL AND ts >= '2024-11-01' AND ts < '2024-12-01');\nALTER TABLE measurements\n  ATTACH PARTITION measurements_2024_11\n  FOR VALUES FROM ('2024-11-01') TO ('2024-12-01');\nALTER TABLE measurements_2024_11\n  DROP CONSTRAINT m_2024_11_bounds;"}],"see_also":["archive-old-rows-to-history","create-empty-like-table","swap-two-table-names"],"faqs":[{"question":"What happens to queries that hit the detached partition?","answer":"They stop seeing its rows immediately: the parent's data now excludes that period while the rows sit in the standalone table. If reports still need the expired period, either keep the partition attached until its data leaves all service-level queries, or archive it somewhere the reports can reach."}]},"source_url":"https://sqlly.app/sql-snippets/rotate-partition","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/round-timestamps","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Round timestamps to the nearest minute or hour in SQL","description":"Truncate timestamps to clean boundaries, or round to the nearest minute or hour, with per-engine one-liners.","body":{"slug":"round-timestamps","name":"Round timestamps","h1":"Round timestamps to the nearest minute or hour in SQL","category":"querying","lede":"Logging pipelines normalize timestamps: truncate for bucket keys, round-to-nearest when the exact second does not matter.","engine_slug":"postgresql","problem":"date_trunc floors to a unit; date_bin (PostgreSQL 14+) floors to any interval, such as 15 minutes. Rounding to the nearest unit is a floor after adding half a unit.","sql":"SELECT\n    date_trunc('hour', occurred_at) AS hour_start,\n    date_bin(interval '15 minutes', occurred_at, TIMESTAMP '2000-01-01') AS quarter_hour,\n    date_trunc('minute', occurred_at + interval '30 seconds') AS rounded_minute,\n    date_trunc('hour', occurred_at + interval '30 minutes') AS rounded_hour\nFROM events;","how_it_works":"date_trunc('hour') always floors: 10:59:31 becomes 10:00. date_bin floors to any stride measured from the origin in its third argument, which is required. Adding half the unit before truncating turns the floor into round-to-nearest, so 10:59:31 rounds to 11:00 both for the minute and for the hour. On a timestamptz column date_trunc works in the session time zone.","variants":[{"sql":"SELECT\n    DATEADD(MINUTE, DATEDIFF(MINUTE, '2000-01-01', occurred_at), '2000-01-01') AS minute_trunc,\n    DATEADD(HOUR, DATEDIFF(HOUR, '2000-01-01', occurred_at), '2000-01-01') AS hour_trunc,\n    DATEADD(MINUTE, DATEDIFF(MINUTE, '2000-01-01', DATEADD(SECOND, 30, occurred_at)), '2000-01-01') AS rounded_minute\nFROM events;"},{"sql":"SELECT\n    DATE_FORMAT(occurred_at, '%Y-%m-%d %H:00:00') AS hour_trunc,\n    DATE_FORMAT(occurred_at, '%Y-%m-%d %H:%i:00') AS minute_trunc\nFROM events;"}],"see_also":["timestamp-bucketing-5-minutes","iso-week-number"],"faqs":[{"question":"Is there a difference between truncating and rounding?","answer":"Yes and it matters: truncation puts 10:59:59 in the 10:00 bucket, rounding puts it in 11:00. Charts usually want truncation; de-duplication and approximate matching often want rounding. Pick deliberately, not by whichever function you found first."}]},"source_url":"https://sqlly.app/sql-snippets/round-timestamps","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/row-counts-every-table","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Row counts of every table","description":"Approximate row counts for every table in one query, read from each engine's maintained statistics instead of running COUNT(*) per table.","body":{"slug":"row-counts-every-table","name":"Row counts of every table","h1":"Row counts of every table","category":"schema","lede":"COUNT(*) reads every row, so running it on every table of a big database takes a long time. Each engine keeps a row figure in its catalogs that costs nothing to read and is close enough for dashboards and sanity checks.","engine_slug":"postgresql","problem":"You need a rough row census across the whole database right now, and running an exact COUNT(*) against every table would take longer than the answer is worth.","sql":"SELECT relname AS table_name,\n       n_live_tup AS approx_row_count\nFROM pg_stat_user_tables\nORDER BY n_live_tup DESC;","how_it_works":"n_live_tup in pg_stat_user_tables is kept up to date from committed inserts and deletes and re-measured by VACUUM and ANALYZE, so reading it costs nothing. It drops to zero after crash recovery or pg_stat_reset() until the next analyze; pg_class.reltuples is the planner's figure and survives both. For exact counts on a handful of tables, run COUNT(*) on those.","variants":[{"sql":"SELECT table_name, table_rows AS approx_row_count\nFROM information_schema.tables\nWHERE table_schema = 'mydb' AND table_type = 'BASE TABLE'\nORDER BY table_rows DESC;\n-- InnoDB table_rows is sampled and cached for\n-- information_schema_stats_expiry; ANALYZE TABLE refreshes it"},{"sql":"SELECT t.name AS table_name,\n       SUM(ps.row_count) AS approx_row_count\nFROM sys.dm_db_partition_stats ps\nJOIN sys.tables t ON t.object_id = ps.object_id\nWHERE ps.index_id IN (0, 1)\nGROUP BY t.name\nORDER BY SUM(ps.row_count) DESC;\n-- index 0 (heap) or 1 (clustered index) holds every row once"},{"sql":"-- SQLite keeps no row estimates; count for real, one table at a time\nSELECT 'users' AS table_name, COUNT(*) AS row_count FROM users\nUNION ALL\nSELECT 'orders', COUNT(*) FROM orders;"}],"see_also":["list-all-tables-sizes","table-bloat-estimate","describe-table-columns"],"faqs":[{"question":"How far off can the estimate be?","answer":"PostgreSQL's figure is usually within a few percent on tables autovacuum keeps up with. The MySQL manual warns that InnoDB's table_rows can differ from the real count by 40 to 50 percent. SQL Server's row_count is documented as approximate but tracks the actual count closely in practice, since it is maintained as rows are written."}]},"source_url":"https://sqlly.app/sql-snippets/row-counts-every-table","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/rows-changed-since-yesterday","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find rows changed since yesterday","description":"Use an updated_at timestamp to list everything modified in the last 24 hours, newest first.","body":{"slug":"rows-changed-since-yesterday","name":"Rows changed recently","h1":"Find rows changed since yesterday","category":"data-quality","lede":"Filter on the row's updated_at timestamp against a 24-hour window and sort newest first for a change feed.","engine_slug":"postgresql","problem":"Something rewrote a pile of customers overnight. The updated_at column tells you which rows moved and when, if the app maintains it on every write.","sql":"SELECT id, email, name, updated_at,\n       updated_at::date AS change_day\nFROM customers\nWHERE updated_at >= CURRENT_TIMESTAMP - INTERVAL '24 hours'\nORDER BY updated_at DESC;","how_it_works":"The predicate compares updated_at against now minus 24 hours, so the window rolls with the clock instead of being fixed to calendar days. Ordering by updated_at DESC reads the result as a change feed. The ::date cast buckets rows by day for a quick before/after picture.","variants":[{"sql":"SELECT id, email, name, updated_at\nFROM customers\nWHERE updated_at >= NOW() - INTERVAL 24 HOUR\nORDER BY updated_at DESC;"},{"sql":"SELECT id, email, name, updated_at\nFROM customers\nWHERE updated_at >= DATEADD(HOUR, -24, SYSDATETIME())\nORDER BY updated_at DESC;"}],"see_also":["last-modified-staleness","soft-delete-audit"],"faqs":[{"question":"What if updated_at is not maintained?","answer":"Then the query silently under-reports: rows changed by paths that skip the column look untouched. Check that every write path (app code, bulk updates, triggers) sets the timestamp, or let the database maintain it: ON UPDATE CURRENT_TIMESTAMP on a MySQL column, a BEFORE UPDATE trigger on PostgreSQL and Oracle, and an AFTER UPDATE trigger that updates the row again on SQL Server and SQLite, which cannot change NEW values in a trigger."}]},"source_url":"https://sqlly.app/sql-snippets/rows-changed-since-yesterday","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/rows-violating-business-rule","corpus":"sql-snippets","engine":"all","language":"en","title":"Find rows violating a business rule","description":"Encode each business rule as a predicate and list, or count, every row that breaks one.","body":{"slug":"rows-violating-business-rule","name":"Rule violations","h1":"Find rows violating a business rule","category":"data-quality","lede":"Turn each business rule into a boolean condition, then select every row where at least one condition fails, optionally with the name of the rule it breaks.","engine_slug":"all","problem":"Domain rules say totals are never negative, shipped orders have a positive total, and no order is dated in the future. The schema enforces none of them, so you audit for violators before adding constraints.","sql":"SELECT id, customer_id, status, total, order_date\nFROM orders\nWHERE total < 0\n   OR (status = 'shipped' AND total <= 0)\n   OR order_date > CURRENT_TIMESTAMP;","how_it_works":"Each line of the WHERE clause is one business rule expressed as a predicate; OR-ing them collects every violator in a single pass. Keep the rules in one place and the query doubles as the definition of 'clean' for this table. A row with a NULL total or order_date fails none of these tests, because comparisons with NULL are unknown; add explicit IS NULL rules if a missing value is itself a violation. The future-date rule compares against CURRENT_TIMESTAMP because every engine and version has it (SQL Server gained CURRENT_DATE only in 2025; on 2022 and older spell it CAST(GETDATE() AS date)); today's date sorts before the current timestamp, so only later days count as future.","variants":[{"sql":"SELECT 'negative total' AS rule_name, COUNT(*) AS violations\nFROM orders WHERE total < 0\nUNION ALL\nSELECT 'shipped with non-positive total', COUNT(*)\nFROM orders WHERE status = 'shipped' AND total <= 0\nUNION ALL\nSELECT 'order dated in the future', COUNT(*)\nFROM orders WHERE order_date > CURRENT_TIMESTAMP;"},{"sql":"SELECT id, 'negative total' AS broken_rule\nFROM orders WHERE total < 0\nUNION ALL\nSELECT id, 'shipped with non-positive total'\nFROM orders WHERE status = 'shipped' AND total <= 0\nUNION ALL\nSELECT id, 'order dated in the future'\nFROM orders WHERE order_date > CURRENT_TIMESTAMP\nORDER BY id, broken_rule;"}],"see_also":["check-constraint-violation-preview","impossible-dates"],"faqs":[{"question":"Should these rules become CHECK constraints?","answer":"Usually yes, once the existing violators are cleaned up. This query tells you the size of the cleanup, and the check-constraint-violation-preview recipe confirms no row would fail before you run ALTER TABLE. A CHECK accepts a row when its condition is unknown, so a NULL total passes CHECK (total >= 0); add NOT NULL to the column if that is not what you want."},{"question":"Can the business rules live in one place instead of a query?","answer":"A CHECK constraint per rule enforces it at write time, but MySQL parsed and ignored CHECK bodies before 8.0.16, and rules that need the current time are rejected or unreliable in CHECK constraints across engines. Keep this query as the portable definition and add constraints only where they are honored."}]},"source_url":"https://sqlly.app/sql-snippets/rows-violating-business-rule","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/running-count","corpus":"sql-snippets","engine":"all","language":"en","title":"Running count","description":"Count how many orders have happened so far, next to every row, with a windowed COUNT.","body":{"slug":"running-count","name":"Running count","h1":"Running count","category":"querying","lede":"COUNT(*) over a growing frame: the same numbers as ROW_NUMBER on a unique sort, different ones on ties.","engine_slug":"all","problem":"You want to see, next to each order, how many orders have been placed up to and including that point in time.","sql":"SELECT order_date, id,\n       COUNT(*) OVER (ORDER BY order_date, id\n                      ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS orders_so_far\nFROM orders\nORDER BY order_date, id;","how_it_works":"COUNT(*) with an ordered window frame counts every row from the start of the partition through the current one. Ordered by a unique key it is identical to ROW_NUMBER, but it reads as what it is. The difference appears when you drop the unique tiebreaker and keep the default RANGE frame: peers are all counted at once, so the count stays flat across tied rows and then jumps.","variants":[{"sql":"SELECT customer_id, order_date,\n       COUNT(*) OVER (PARTITION BY customer_id\n                      ORDER BY order_date, id\n                      ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS orders_so_far\nFROM orders\nORDER BY customer_id, order_date;"}],"see_also":["running-total","top-n-per-group"],"faqs":[{"question":"When is a running count better than ROW_NUMBER?","answer":"When rows share the ORDER BY key and you want all of them to show the same count. Drop the id tiebreaker and the ROWS clause, and the default RANGE frame gives every order on the same timestamp the count including all of them. Over a unique key, as written above, the two produce identical values."}]},"source_url":"https://sqlly.app/sql-snippets/running-count","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/running-total","corpus":"sql-snippets","engine":"all","language":"en","title":"Running total","description":"Add a cumulative sum of order amounts with the SUM window function, ordered row by row.","body":{"slug":"running-total","name":"Running total","h1":"Running total","category":"querying","lede":"The SUM you already know, plus an OVER clause that leaves the rows in place and adds a growing sum.","engine_slug":"all","problem":"You want a cumulative revenue column next to each order, in date order, without a self-join or a loop.","sql":"SELECT order_date, id, amount,\n       SUM(amount) OVER (ORDER BY order_date, id\n                         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total\nFROM orders\nORDER BY order_date, id;","how_it_works":"SUM with OVER (ORDER BY ...) accumulates from the first row up to the current one. The explicit ROWS frame makes the total strictly row-by-row; the default RANGE frame would also include any peer rows that share the current ORDER BY value, which surprises people. The window's ORDER BY decides the accumulation order and the outer ORDER BY only decides display, so keep them identical or the running total will look like it jumps around.","variants":[{"sql":"SELECT customer_id, order_date, amount,\n       SUM(amount) OVER (PARTITION BY customer_id\n                         ORDER BY order_date, id\n                         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total\nFROM orders\nORDER BY customer_id, order_date;"}],"see_also":["running-count","moving-average","cumulative-total-by-month"],"faqs":[{"question":"Why specify ROWS BETWEEN explicitly?","answer":"The default frame is RANGE between UNBOUNDED PRECEDING and the current row's peers, so rows tied on the ORDER BY key all enter the sum at once. That is sometimes what you want, but with duplicate dates it makes the total jump and confuses the running-total intent."},{"question":"How do I restart the total per customer?","answer":"Add PARTITION BY customer_id to the OVER clause and the accumulation resets at each new customer; frame and ordering rules are unchanged on all five engines."}]},"source_url":"https://sqlly.app/sql-snippets/running-total","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/safe-string-to-date","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Safely convert strings to dates in SQL","description":"Convert text like '2026-03-01' to a real date while sending garbage to NULL instead of an error.","body":{"slug":"safe-string-to-date","name":"Safely convert a string to a date","h1":"Safely convert strings to dates in SQL","category":"text","lede":"Dates typed or imported as text range from '2026-03-01' to '3/1/26' to plain nonsense. Convert leniently and keep the rejects visible.","engine_slug":"sql-server","problem":"Converting an imported text column to DATE fails the whole statement as soon as one row is malformed. TRY_CAST turns bad values into NULL so the load continues.","sql":"SELECT TRY_CAST(raw_date AS DATE) AS event_date\nFROM staging.events;","how_it_works":"TRY_CAST applies the server's date-parsing rules and returns NULL for anything unparseable. Pair it with a WHERE TRY_CAST(...) IS NULL query to list rejected rows for fixing. Note the parse depends on the session's language and DATEFORMAT settings for formats like '3/1/26'. On PostgreSQL a regex check is not enough, because '2026-02-30' matches the pattern and still fails the cast; pg_input_is_valid does the real check.","variants":[{"sql":"SELECT STR_TO_DATE(raw_date, '%Y-%m-%d') AS event_date\nFROM staging.events;"},{"sql":"SELECT CASE\n           WHEN pg_input_is_valid(raw_date, 'date')\n           THEN raw_date::DATE\n       END AS event_date\nFROM staging.events;"}],"see_also":["safe-string-to-number","round-timestamps"],"faqs":[{"question":"Why did '3/1/26' convert to a strange date?","answer":"Ambiguous orders depend on server settings: SQL Server's default US language parses it as March 1. Use explicit formats (STR_TO_DATE with a mask on MySQL, or the 'yyyy-MM-dd' style with TRY_CONVERT style 23 on SQL Server) so the result cannot depend on configuration."}]},"source_url":"https://sqlly.app/sql-snippets/safe-string-to-date","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/safe-string-to-number","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Safely convert strings to numbers in SQL","description":"Convert '12.5' to a decimal without the whole query dying on 'N/A', using TRY_CAST or a validation check.","body":{"slug":"safe-string-to-number","name":"Safely convert a string to a number","h1":"Safely convert strings to numbers in SQL","category":"text","lede":"Import tables type everything as text. Converting a numeric column crashes the moment one row holds junk.","engine_slug":"sql-server","problem":"One bad row ('N/A') aborts every CAST(raw_value AS DECIMAL) in the batch. TRY_CAST returns NULL instead of raising an error.","sql":"SELECT TRY_CAST(raw_value AS DECIMAL(12, 2)) AS amount\nFROM staging.import_rows;","how_it_works":"TRY_CAST attempts the conversion and yields NULL when the text is not a valid number, so bad rows surface as NULL instead of killing the statement. Filter them out with IS NULL to audit what failed. TRY_CONVERT is the same idea with a style argument. Oracle 12.2+ has the equivalent CAST(raw_value AS NUMBER DEFAULT NULL ON CONVERSION ERROR), plus VALIDATE_CONVERSION to test a value first.","variants":[{"sql":"SELECT CASE\n           WHEN raw_value ~ '^-?[0-9]+(\\.[0-9]+)?$'\n           THEN raw_value::DECIMAL(12, 2)\n       END AS amount\nFROM staging.import_rows;"},{"sql":"SELECT CASE\n           WHEN raw_value REGEXP '^-?[0-9]+(\\\\.[0-9]+)?$'\n           THEN CAST(raw_value AS DECIMAL(12, 2))\n       END AS amount\nFROM staging.import_rows;"}],"see_also":["safe-string-to-date","extract-leading-digits"],"faqs":[{"question":"Is TRY_CAST slow?","answer":"The parse is the same work as CAST, so the difference is small next to the I/O of reading the rows. The regex variants cost more and accept less: they reject '1e5' and '+3', which a real cast would take. On PostgreSQL 16+, pg_input_is_valid(raw_value, 'numeric') is the closest native equivalent to TRY_CAST."}]},"source_url":"https://sqlly.app/sql-snippets/safe-string-to-number","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/schema-version-table-recipe","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Schema version table recipe","description":"A tiny table recording which schema version the database is at, so scripts can check before running and drift between environments becomes visible.","body":{"slug":"schema-version-table-recipe","name":"Schema version table","h1":"Schema version table recipe","category":"schema","lede":"Hand-rolled deployments need one place that says 'this database is at schema version N'. A two-column table does the job and every script can read it.","engine_slug":"postgresql","problem":"Deploy scripts run against several environments, each needing to know which migrations it has already applied, without adopting a full migration framework.","sql":"CREATE TABLE IF NOT EXISTS schema_version (\n    version    integer PRIMARY KEY,\n    name       text NOT NULL,\n    applied_at timestamptz NOT NULL DEFAULT now(),\n    checksum   text\n);\n\nINSERT INTO schema_version (version, name, checksum)\nVALUES (12, 'add-orders-table', 'sha256:9f1c...')\nON CONFLICT (version) DO NOTHING;","how_it_works":"One row per applied migration, keyed by version, gives you the current state with SELECT max(version) and the full history in the same table. ON CONFLICT DO NOTHING makes the insert re-runnable instead of failing on the primary key. The checksum column is optional; it lets a verification script notice a migration file that was edited after it was applied. MySQL's INSERT IGNORE does the same job but also turns other errors, such as a too-long value, into warnings.","variants":[{"sql":"CREATE TABLE IF NOT EXISTS schema_version (\n    version    INT PRIMARY KEY,\n    name       VARCHAR(200) NOT NULL,\n    applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n    checksum   VARCHAR(80) NULL  -- 'sha256:' + 64 hex digits\n) ENGINE=InnoDB;\n\nINSERT IGNORE INTO schema_version (version, name, checksum)\nVALUES (12, 'add-orders-table', 'sha256:9f1c...');"},{"sql":"IF OBJECT_ID('dbo.SchemaVersion', 'U') IS NULL\n    CREATE TABLE dbo.SchemaVersion (\n        Version INT PRIMARY KEY,\n        Name NVARCHAR(200) NOT NULL,\n        AppliedAt DATETIME2 NOT NULL DEFAULT SYSUTCDATETIME(),\n        Checksum VARCHAR(80) NULL\n    );\n\nINSERT INTO dbo.SchemaVersion (Version, Name, Checksum)\nSELECT 12, 'add-orders-table', 'sha256:9f1c...'\nWHERE NOT EXISTS (\n    SELECT 1 FROM dbo.SchemaVersion WHERE Version = 12);"}],"see_also":["migration-lock-row-recipe","create-table-if-not-exists","row-counts-every-table"],"faqs":[{"question":"Why keep a checksum when the version already matches?","answer":"Because migration files get edited: someone fixes 'the same' migration in git after three environments already ran the old text. The version numbers still match everywhere, but the schemas do not. Comparing the stored checksum with a hash of the current file is how you notice."}]},"source_url":"https://sqlly.app/sql-snippets/schema-version-table-recipe","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/second-highest-value","corpus":"sql-snippets","engine":"all","language":"en","title":"Second-highest value","description":"Find the second-highest order amount overall or per customer, with duplicates handled correctly.","body":{"slug":"second-highest-value","name":"Second-highest value","h1":"Second-highest value","category":"querying","lede":"MAX of everything below the MAX for one value, DENSE_RANK when you need it per group.","engine_slug":"all","problem":"You want the second-highest order amount. MAX(amount) gives the highest, and the naive ORDER BY amount DESC LIMIT 1 OFFSET 1 returns the top amount again when two orders share it.","sql":"SELECT MAX(amount) AS second_highest\nFROM orders\nWHERE amount < (SELECT MAX(amount) FROM orders);","how_it_works":"The inner query finds the highest amount; the outer query takes the MAX of everything strictly below it. Duplicate rows at the top collapse into one MAX, so two orders tied at the highest still yield the true second value. If only one distinct amount exists the result is NULL rather than an error.","variants":[{"sql":"WITH ranked AS (\n  SELECT customer_id, amount,\n         DENSE_RANK() OVER (PARTITION BY customer_id\n                            ORDER BY amount DESC) AS rnk\n  FROM orders\n)\nSELECT customer_id, amount\nFROM ranked\nWHERE rnk = 2\nORDER BY customer_id;"},{"sql":"SELECT DISTINCT amount\nFROM orders\nORDER BY amount DESC\nLIMIT 1 OFFSET 1;"}],"see_also":["top-n-with-ties","running-total"],"faqs":[{"question":"Why DENSE_RANK and not ROW_NUMBER for the per-customer version?","answer":"ROW_NUMBER counts rows, so two orders tied at the highest amount would make the second row the 'second highest'. DENSE_RANK counts distinct values, which is usually what people mean by second-highest."},{"question":"What does the query return when a group has one row?","answer":"NULL: nothing sits strictly below the maximum, and MAX over an empty set is NULL on every engine. Wrap the value in COALESCE when a report prefers a dash over an empty cell."}]},"source_url":"https://sqlly.app/sql-snippets/second-highest-value","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/self-join-pairs","corpus":"sql-snippets","engine":"all","language":"en","title":"Self-join pairs (and mutual pairs)","description":"Join a table to itself to pair rows, with a.id < b.id to keep each pair once and skip self-pairs.","body":{"slug":"self-join-pairs","name":"Pair rows with a self-join","h1":"Self-join pairs (and mutual pairs)","category":"querying","lede":"The half-open comparison is what turns a cross product into clean pairs.","engine_slug":"all","problem":"You want every pair of customers in the same region, each pair listed once, to introduce them to each other.","sql":"SELECT a.name AS customer_a, b.name AS customer_b, a.region\nFROM customers a\nJOIN customers b\n  ON a.region = b.region\n AND a.id < b.id\nORDER BY a.region, a.name;","how_it_works":"The self-join matches every customer row to every other row with the same region. The extra condition a.id < b.id does two jobs: it removes the row joined to itself, and it keeps only one of the (A, B) and (B, A) orderings, so each pair appears exactly once. For a mutual-pairs list where both directions matter, relax the condition to a.id <> b.id.","variants":[{"sql":"SELECT a.name AS customer_a, b.name AS customer_b, a.region\nFROM customers a\nJOIN customers b\n  ON a.region = b.region\n AND a.id <> b.id\nORDER BY a.region, a.name;"}],"see_also":["intersect-common-rows","org-chart-walk"],"faqs":[{"question":"Why a.id < b.id and not just DISTINCT?","answer":"DISTINCT cannot remove (B, A) because the column values are swapped, so the rows differ. The inequality picks a canonical direction once, which is cheaper and clearer than deduplicating after the fact."},{"question":"How do I keep the pair list from exploding?","answer":"The region partition bounds it, but 10,000 customers in one region still produce about 50 million pairs. Aggregate before joining when the question is really a count, or push more predicates into the join, and let a.id < b.id keep halving the work."}]},"source_url":"https://sqlly.app/sql-snippets/self-join-pairs","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/sequence-gap-detection","corpus":"sql-snippets","engine":"all","language":"en","title":"Detect gaps in an id sequence","description":"Find gaps between consecutive ids with LEAD: each row reports the next id and how many are missing.","body":{"slug":"sequence-gap-detection","name":"ID gaps","h1":"Detect gaps in an id sequence","category":"data-quality","lede":"Compare each id with the one after it using LEAD; when the difference is more than one, the ids in between are missing.","engine_slug":"all","problem":"orders uses a plain integer id and someone wants to know whether rows were ever hard-deleted. Consecutive ids with a jump mean ids in between were used and are now gone.","sql":"WITH adjacent AS (\n  SELECT id,\n         LEAD(id) OVER (ORDER BY id) AS next_id\n  FROM orders\n)\nSELECT id AS last_id_before_gap,\n       next_id AS first_id_after_gap,\n       next_id - id - 1 AS missing_ids\nFROM adjacent\nWHERE next_id - id > 1\nORDER BY id;","how_it_works":"LEAD(id) looks one row ahead in id order, pairing every id with its successor. Window functions cannot appear in WHERE, so the CTE computes next_id first and the outer query keeps jumps of two or more. next_id - id - 1 is how many ids the jump skipped. The last row's next_id is NULL, so it drops out of the comparison on its own.","variants":[{"sql":"WITH adjacent AS (\n  SELECT id, LEAD(id) OVER (ORDER BY id) AS next_id\n  FROM orders\n)\nSELECT COUNT(*) AS gap_count,\n       COALESCE(SUM(next_id - id - 1), 0) AS total_missing_ids\nFROM adjacent\nWHERE next_id - id > 1;"}],"see_also":["missing-sequence-values","date-gap-detection"],"faqs":[{"question":"Do sequence gaps always mean deleted rows?","answer":"No. Rolled-back transactions and failed inserts burn sequence values in most databases, so a gap can be an aborted insert rather than a delete. Treat this query as a change detector worth explaining, not proof of data loss. The missing-sequence-values recipe lists the actual ids if you need to probe them."},{"question":"Why does the same gap query return different gaps an hour later?","answer":"Sequences never reclaim ids, so every rolled-back insert manufactures a permanent gap, and ids from uncommitted transactions look missing until they commit. Run the check on a quiet replica, and decide deliberately which gaps deserve backfilling."}]},"source_url":"https://sqlly.app/sql-snippets/sequence-gap-detection","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/session-memory-grants","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Find sessions holding large query memory grants in SQL Server","description":"Lists the requests currently holding memory grants with granted versus used memory, to spot over-granted queries starving the resource semaphore.","body":{"slug":"session-memory-grants","name":"Session memory grants","h1":"Find sessions holding large query memory grants in SQL Server","category":"monitoring","lede":"Queries reserve memory before they run. When the reservations are too big, other queries wait. This shows who holds what.","engine_slug":"sql-server","problem":"Before a query with sorts or hash operations starts, it asks the resource semaphore for a workspace memory grant sized from the optimizer's row estimates. When the estimates are wrong, so is the grant: an over-granted query reserves memory it never touches, and an under-granted one spills its sort or hash to tempdb. sys.dm_exec_query_memory_grants shows every outstanding grant in real time.","sql":"SELECT mg.session_id,\n       CASE WHEN mg.grant_time IS NULL THEN 'waiting' ELSE 'granted' END AS grant_state,\n       mg.request_time,\n       mg.requested_memory_kb / 1024 AS requested_mb,\n       mg.granted_memory_kb / 1024 AS granted_mb,\n       mg.used_memory_kb / 1024 AS used_mb,\n       mg.max_used_memory_kb / 1024 AS peak_mb,\n       mg.ideal_memory_kb / 1024 AS ideal_mb,\n       mg.queue_id, mg.wait_time_ms,\n       LEFT(t.text, 120) AS query\nFROM sys.dm_exec_query_memory_grants mg\nOUTER APPLY sys.dm_exec_sql_text(mg.sql_handle) t\nORDER BY mg.requested_memory_kb DESC;","how_it_works":"Each row is a request holding or waiting for a memory grant. grant_time is NULL while the request waits; then queue_id names the semaphore queue it sits in and wait_time_ms says for how long (both are NULL once granted). The sort is on requested_mb because waiting requests have no granted memory yet. Granted versus peak is the over-grant check: a query granted 2 GB that peaked at 200 MB was estimated badly, and the unused 1.8 GB can still keep other queries waiting. ideal_mb is what the optimizer wanted before the grant was capped. In SQL Server 2019 and later, memory grant feedback adjusts the grant of repeated cached plans automatically; updated statistics or a rewrite fix the cause.","variants":[{"sql":"SELECT TOP 20\n    qs.execution_count,\n    qs.total_grant_kb / 1024 AS total_grant_mb,\n    qs.total_used_grant_kb / 1024 AS used_grant_mb,\n    LEFT(st.text, 120) AS query\nFROM sys.dm_exec_query_stats qs\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st\nWHERE qs.total_grant_kb > 0\nORDER BY qs.total_grant_kb DESC;"}],"see_also":["temp-table-spilling","blocking-queries","high-logical-reads-queries"],"faqs":[{"question":"Why would a query be granted 100x what it uses?","answer":"Row estimates. Stale statistics, a plan compiled for an unusual parameter value, or a predicate the optimizer cannot estimate well (a local variable, a multi-statement function) makes it expect millions of rows where thousands come back, and the grant scales with the expectation. Wide variable-length columns add to it, because the estimate assumes each is half full. UPDATE STATISTICS, OPTION (RECOMPILE) for parameter-sensitive queries, or a rewrite are the usual fixes; the MAX_GRANT_PERCENT query hint caps one query's grant."},{"question":"What is the resource semaphore and how do I see contention?","answer":"It is the gatekeeper for query workspace memory. When the memory requested by new queries exceeds what is free, they wait, and the waits show up as RESOURCE_SEMAPHORE in the wait statistics and as rows with a NULL grant_time here. sys.dm_exec_query_resource_semaphores shows each semaphore's target, available and waiter counts. A few huge grants with many waiters behind them is the usual picture, and the fix is shrinking the over-grants."}]},"source_url":"https://sqlly.app/sql-snippets/session-memory-grants","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/set-column-default","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Set a column default","description":"Add a default to an existing column on each engine, including SQL Server, where a default is a separate named constraint.","body":{"slug":"set-column-default","name":"Set a column default","h1":"Set a column default","category":"schema","lede":"New defaults change what future INSERTs write without touching existing rows. Each engine applies them a little differently; SQL Server is the odd one with named constraints.","engine_slug":"postgresql","problem":"From now on, INSERTs that omit the column should fall back to a sensible value rather than NULL or an error.","sql":"ALTER TABLE users\n  ALTER COLUMN is_active SET DEFAULT true;","how_it_works":"The default applies to rows inserted after this statement; existing rows keep their values, and the change is catalog-only on PostgreSQL even for big tables. Re-running SET DEFAULT just overwrites the default with the same value. The default can be a literal or an expression, including volatile ones such as now() or gen_random_uuid(), which are evaluated separately for each inserted row.","variants":[{"sql":"-- a default is a named constraint; a column can have only\n-- one, so drop an existing one first (see remove-column-default)\nIF NOT EXISTS (SELECT 1 FROM sys.default_constraints\n               WHERE name = 'DF_Users_IsActive')\n    ALTER TABLE dbo.Users\n        ADD CONSTRAINT DF_Users_IsActive DEFAULT 1 FOR IsActive;"},{"sql":"ALTER TABLE users\n  ALTER COLUMN is_active SET DEFAULT 1;\n-- expression defaults need parentheses (MySQL 8.0.13+):\n-- ALTER TABLE users ALTER COLUMN token SET DEFAULT (UUID());"},{"sql":"-- defaults live in the column definition and SQLite has no\n-- ALTER COLUMN, so rebuild the table: run\n-- PRAGMA foreign_keys = OFF first (it is ignored inside a\n-- transaction), then BEGIN and:\n-- 1) CREATE TABLE users_new with the default in the column\n-- 2) INSERT INTO users_new SELECT * FROM users\n-- 3) DROP TABLE users; ALTER TABLE users_new RENAME TO users\n-- 4) recreate indexes and triggers, COMMIT, then\n--    PRAGMA foreign_keys = ON"}],"see_also":["remove-column-default","make-column-not-null-safely","add-column-if-missing"],"faqs":[{"question":"Why didn't my default appear on existing rows?","answer":"A default only fills in for INSERTs that omit the column; an INSERT that passes NULL explicitly still stores NULL. To backfill, run an UPDATE setting the column where it IS NULL, which is also the first step of the make-column-not-null recipe."}]},"source_url":"https://sqlly.app/sql-snippets/set-column-default","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/share-of-parent","corpus":"sql-snippets","engine":"all","language":"en","title":"Share of parent","description":"Give each product its percent share of its own category's revenue with a partitioned window over aggregates.","body":{"slug":"share-of-parent","name":"Share of parent","h1":"Share of parent","category":"querying","lede":"Same grand-total trick, but PARTITION BY the parent instead of the whole set.","engine_slug":"all","problem":"You want each product's sales and what percent of its category that represents, not of the whole catalogue.","sql":"SELECT p.category, p.name,\n       SUM(oi.quantity * oi.unit_price) AS product_sales,\n       ROUND(100.0 * SUM(oi.quantity * oi.unit_price)\n             / SUM(SUM(oi.quantity * oi.unit_price)) OVER (PARTITION BY p.category), 1) AS share_of_category\nFROM order_items oi\nJOIN products p ON p.id = oi.product_id\nGROUP BY p.category, p.name\nORDER BY p.category, product_sales DESC;","how_it_works":"The GROUP BY produces one sales row per product; the windowed SUM then totals those rows per category, which is the parent denominator. Dividing the product's own grouped SUM by it gives the share. It is the percentage-of-total recipe with PARTITION BY, and the same decimal-division warning applies.","variants":[{"sql":"SELECT p.category, p.name,\n       ROUND(100.0 * SUM(oi.quantity * oi.unit_price)\n             / SUM(SUM(oi.quantity * oi.unit_price)) OVER (PARTITION BY p.category), 1) AS share_of_category,\n       ROUND(100.0 * SUM(oi.quantity * oi.unit_price)\n             / SUM(SUM(oi.quantity * oi.unit_price)) OVER (), 1) AS share_of_catalogue\nFROM order_items oi\nJOIN products p ON p.id = oi.product_id\nGROUP BY p.category, p.name;"}],"see_also":["percentage-of-total","rank-within-category"],"faqs":[{"question":"What defines 'the parent' here?","answer":"Whatever you PARTITION BY. The partition key must also be a GROUP BY key so the window sees the aggregated rows; category, region and month are the usual parents."},{"question":"What happens when a parent totals zero?","answer":"SQL Server raises divide-by-zero (error 8134) and PostgreSQL errors too, while MySQL quietly returns NULL. Wrap the denominator in NULLIF(parent_total, 0) so every engine agrees on NULL for an empty parent."}]},"source_url":"https://sqlly.app/sql-snippets/share-of-parent","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/shuffled-sample","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Shuffled sample of rows","description":"Take N rows in random order with ORDER BY RANDOM() and LIMIT, and know when to use TABLESAMPLE instead.","body":{"slug":"shuffled-sample","name":"Shuffled sample of rows","h1":"Shuffled sample of rows","category":"querying","lede":"A random sort plus LIMIT is a fair shuffle; TABLESAMPLE trades fairness for speed.","engine_slug":"postgresql","problem":"You want 100 random orders to eyeball data quality, freshly shuffled every run.","sql":"SELECT id, customer_id, order_date, amount\nFROM orders\nORDER BY RANDOM()\nLIMIT 100;","how_it_works":"Assigning a random value to every row and sorting by it is a full shuffle, so the first 100 rows are an unbiased sample without replacement. The cost is the same sort as random-row, which is why very large tables prefer TABLESAMPLE or a precomputed random column. Each re-run produces a new sample because RANDOM() is re-evaluated per row per query. random-row draws a single row with this clause; here the sample feeds an ORDER BY random() LIMIT.","variants":[{"sql":"SELECT id, customer_id, order_date, amount\nFROM orders TABLESAMPLE BERNOULLI (1)\nLIMIT 100;"}],"see_also":["random-row","weighted-sample"],"faqs":[{"question":"Why did TABLESAMPLE return fewer than 100 rows?","answer":"TABLESAMPLE samples pages or row probabilities, not exact counts, so the row count varies per run and LIMIT 100 only caps it. If you need exactly N rows, keep the ORDER BY RANDOM() shuffle or retry."}]},"source_url":"https://sqlly.app/sql-snippets/shuffled-sample","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/slow-log-excerpt","corpus":"sql-snippets","engine":"mysql","language":"en","title":"Read recent slow queries from the MySQL slow log table","description":"Redirects the MySQL slow query log into a table and queries the newest entries with times, row counts and SQL text, no log files to grep.","body":{"slug":"slow-log-excerpt","name":"Slow log excerpt","h1":"Read recent slow queries from the MySQL slow log table","category":"monitoring","lede":"The slow query log as a table you can query: newest entries first, with query_time, rows examined versus sent, and the SQL text.","engine_slug":"mysql","problem":"MySQL's slow query log captures every statement slower than long_query_time. With log_output = TABLE, entries land in mysql.slow_log instead of a file, so SQL can read them: the newest slow queries, their execution time, rows examined versus rows sent, and the statement text, all without shell access to the server.","sql":"SELECT start_time, user_host, query_time, lock_time,\n       rows_sent, rows_examined,\n       LEFT(CONVERT(sql_text USING utf8mb4), 200) AS sql_text\nFROM mysql.slow_log\nORDER BY start_time DESC\nLIMIT 20;","how_it_works":"slow_log stores entries as they arrive when slow_query_log is ON and log_output is TABLE. rows_examined versus rows_sent is the quick quality check: examining 100,000 rows to send 10 usually means a missing index. mysql.slow_log uses the CSV storage engine, which supports no indexes, so every query against it reads the whole table and sorts it; keep it small with TRUNCATE TABLE mysql.slow_log. sql_text is a binary column, hence the CONVERT to readable text. The default long_query_time of 10 seconds misses most problems on an OLTP system; 1 second, or a fraction such as 0.5, catches realistic offenders. SET GLOBAL changes are lost at restart unless you also put them in the configuration file or use SET PERSIST.","variants":[{"sql":"SET GLOBAL slow_query_log = 'ON';\nSET GLOBAL log_output = 'TABLE';\nSET GLOBAL long_query_time = 1;"},{"sql":"SELECT calls,\n       ROUND(mean_exec_time::numeric, 1) AS mean_ms,\n       LEFT(query, 140) AS query\nFROM pg_stat_statements\nWHERE mean_exec_time > 500\nORDER BY mean_exec_time DESC\nLIMIT 20;"}],"see_also":["top-queries-by-total-time","sort-heavy-queries","high-logical-reads-queries"],"faqs":[{"question":"Is the slow log table a performance risk?","answer":"It costs more than the file. Every logged statement becomes a row inserted into a CSV table, and the table grows without limit until someone truncates it. With a low long_query_time on a busy server that is a lot of writes. FILE output (log_output = 'FILE', or 'FILE,TABLE' for both) plus mysqldumpslow or pt-query-digest is the usual production setup; the table form is convenient on development and moderately loaded servers."},{"question":"What is a healthy rows_examined / rows_sent ratio?","answer":"Near 1:1 for point lookups and a small multiple for well-indexed range queries. Ratios in the thousands mean the statement read far more rows than it returned, usually a full table or index scan where a better index would have gone straight to the rows. Aggregates are the exception: SELECT COUNT(*) over a million rows returns one row and is not necessarily badly indexed."}]},"source_url":"https://sqlly.app/sql-snippets/slow-log-excerpt","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/soft-delete-audit","corpus":"sql-snippets","engine":"all","language":"en","title":"Audit soft-deleted rows","description":"Count live vs soft-deleted rows and catch rows touched after their deletion timestamp.","body":{"slug":"soft-delete-audit","name":"Soft-delete audit","h1":"Audit soft-deleted rows","category":"data-quality","lede":"deleted_at IS NULL marks live rows; everything else is soft-deleted, and a few invariants over the timestamps catch misbehaving writes.","engine_slug":"all","problem":"customers uses deleted_at for soft deletes. Over time you want to know the live-to-deleted ratio, when deletions happened, and whether any supposedly-deleted row was modified afterwards, which is a bug signature.","sql":"SELECT\n  COUNT(*) AS total_rows,\n  SUM(CASE WHEN deleted_at IS NULL THEN 1 ELSE 0 END) AS live_rows,\n  SUM(CASE WHEN deleted_at IS NOT NULL THEN 1 ELSE 0 END) AS deleted_rows,\n  SUM(CASE WHEN deleted_at IS NOT NULL AND updated_at > deleted_at\n           THEN 1 ELSE 0 END) AS touched_after_delete\nFROM customers;","how_it_works":"Three SUM(CASE) flags split the table: live, soft-deleted, and (the interesting one) rows whose updated_at moved past their deleted_at, which means a write path ignores the soft-delete flag. A healthy table shows touched_after_delete = 0. The variant breaks deletions out per month for a trend view; on other engines swap strftime for to_char(deleted_at, 'YYYY-MM') (PostgreSQL, Oracle), DATE_FORMAT(deleted_at, '%Y-%m') (MySQL) or FORMAT(deleted_at, 'yyyy-MM') (SQL Server).","variants":[{"sql":"SELECT strftime('%Y-%m', deleted_at) AS deletion_month,\n       COUNT(*) AS deleted_rows\nFROM customers\nWHERE deleted_at IS NOT NULL\nGROUP BY strftime('%Y-%m', deleted_at)\nORDER BY deletion_month;"}],"see_also":["restore-able-rows","cascade-impact-preview","last-modified-staleness"],"faqs":[{"question":"How do rows get updated after deletion?","answer":"Usually a query somewhere forgot the WHERE deleted_at IS NULL clause: a background job, an import upsert, or an admin tool. Each hit in touched_after_delete is one of those queries. Fix the query, not just the rows, or the count starts growing again next week."},{"question":"When should soft-deleted rows be purged for real?","answer":"On an age policy, not on a whim: keep them past the undo window the flag promises, then delete in id batches so the transaction log on MySQL and SQL Server stays bounded. Immediate hard deletes turn every accidental flag into a restore-from-backup job."}]},"source_url":"https://sqlly.app/sql-snippets/soft-delete-audit","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/sort-heavy-queries","corpus":"sql-snippets","engine":"mysql","language":"en","title":"Find sort-heavy queries in MySQL","description":"Ranks performance_schema digests by sort merge passes and rows sorted to find ORDER BY and GROUP BY work that a matching index would remove.","body":{"slug":"sort-heavy-queries","name":"Sort-heavy queries","h1":"Find sort-heavy queries in MySQL","category":"monitoring","lede":"Sorting is work an index could have done ahead of time. This finds the queries sorting the most rows and spilling the most.","engine_slug":"mysql","problem":"MySQL sorts (EXPLAIN shows Using filesort) when an ORDER BY, or a GROUP BY that needs ordering, cannot read rows in order from an index. The digest table counts rows sorted per statement pattern, plus sort merge passes: when the rows do not fit in sort_buffer_size, MySQL writes sorted chunks to temporary files and merges them, and each merge round counts as a pass. A digest with many merge passes sorts a lot of data often, which is what a matching index removes.","sql":"SELECT SCHEMA_NAME,\n       COUNT_STAR AS calls,\n       SUM_SORT_ROWS AS rows_sorted,\n       SUM_SORT_SCAN AS full_sort_scans,\n       SUM_SORT_MERGE_PASSES AS merge_passes,\n       SUM_CREATED_TMP_DISK_TABLES AS on_disk_tmp,\n       LEFT(DIGEST_TEXT, 120) AS digest\nFROM performance_schema.events_statements_summary_by_digest\nWHERE SUM_SORT_ROWS > 0\nORDER BY SUM_SORT_MERGE_PASSES DESC, SUM_SORT_ROWS DESC\nLIMIT 20;","how_it_works":"events_statements_summary_by_digest keeps one row per normalized statement per schema. SUM_SORT_ROWS totals rows sorted, SUM_SORT_SCAN counts sorts fed by a full table scan, and SUM_SORT_MERGE_PASSES counts merge rounds for sorts that overflowed sort_buffer_size. SUM_CREATED_TMP_DISK_TABLES is listed beside them because GROUP BY, DISTINCT and UNION often build an internal temporary table, and one that outgrows memory goes to disk. Merge passes lead the ordering because they mean the sort went to disk. The digest text has its literals replaced by ?; the variant reads events_statements_history, which keeps the last 10 statements of each connected thread with their real text, so it finds spilling sorts only from sessions that are still connected. Do not look for a sorting state in the processlist: on MySQL 8.4 a sorting query shows the state executing. The usual fix is an index with the WHERE equality columns first and the ORDER BY columns after them.","variants":[{"sql":"SELECT t.PROCESSLIST_ID, t.PROCESSLIST_USER,\n       h.SORT_ROWS, h.SORT_MERGE_PASSES,\n       ROUND(h.TIMER_WAIT / 1e9, 1) AS ms,\n       LEFT(h.SQL_TEXT, 120) AS query\nFROM performance_schema.events_statements_history h\nJOIN performance_schema.threads t ON t.THREAD_ID = h.THREAD_ID\nWHERE h.SORT_MERGE_PASSES > 0\nORDER BY h.SORT_MERGE_PASSES DESC\nLIMIT 20;"}],"see_also":["explain-query-plan-workflow","temp-table-spilling","top-queries-by-total-time"],"faqs":[{"question":"What index satisfies WHERE status = 'paid' ORDER BY created_at DESC?","answer":"An index on (status, created_at): the equality column first, then the sort column. MySQL can read the index backwards for DESC, and since 8.0 you can also declare (status, created_at DESC). Either way the rows come out in final order and EXPLAIN no longer shows Using filesort."},{"question":"Should I raise sort_buffer_size instead?","answer":"Raising it reduces merge passes, but the buffer is allocated per sort, per session, so a large global value multiplies across every connection that sorts. Sorting a million rows also stays expensive in memory. Fix the access path with an index first, and raise sort_buffer_size for a session (SET SESSION sort_buffer_size = ...) only for sorts that cannot be avoided."}]},"source_url":"https://sqlly.app/sql-snippets/sort-heavy-queries","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/split-csv-into-rows","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Split a comma-separated field into rows in SQL","description":"Turn one row with 'a,b,c' into three rows, one per value, with STRING_SPLIT or a set-returning function.","body":{"slug":"split-csv-into-rows","name":"Split a CSV field into rows","h1":"Split a comma-separated field into rows in SQL","category":"text","lede":"Tags stored as a comma-separated blob need one row per tag for counting, joining and filtering.","engine_slug":"sql-server","problem":"The tags column holds 'wifi,pool,pet-friendly' in one cell. To count the most common tags you need each value on its own row.","sql":"SELECT id, LTRIM(RTRIM(value)) AS tag\nFROM amenities\nCROSS APPLY STRING_SPLIT(tags_csv, ',');","how_it_works":"STRING_SPLIT returns one row per comma-separated value. CROSS APPLY multiplies each source row by its values, so the id stays attached to every tag. STRING_SPLIT needs SQL Server 2016+ at compatibility level 130 or higher, has no TRIM option, and before SQL Server 2022 (which added the enable_ordinal argument) does not report each value's position.","variants":[{"sql":"SELECT a.id, btrim(t) AS tag\nFROM amenities a, unnest(string_to_array(a.tags_csv, ',')) AS t;"},{"sql":"SELECT a.id,\n       TRIM(REGEXP_SUBSTR(a.tags_csv, '[^,]+', 1, LEVEL)) AS tag\nFROM amenities a\nCONNECT BY LEVEL <= REGEXP_COUNT(a.tags_csv, '[^,]+')\n    AND PRIOR a.id = a.id\n    AND PRIOR SYS_GUID() IS NOT NULL;"}],"see_also":["join-child-rows-comma-list","split-full-name-first-last"],"faqs":[{"question":"Can I split on a multi-character delimiter?","answer":"Not with STRING_SPLIT: its separator must be exactly one character in every version, including 2022 and 2025. PostgreSQL's string_to_array accepts any delimiter string and Oracle's REGEXP_SUBSTR any pattern; on SQL Server, REPLACE the multi-character delimiter with a single rare character first."}]},"source_url":"https://sqlly.app/sql-snippets/split-csv-into-rows","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/split-full-name-first-last","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Split a full name into first and last name in SQL","description":"Pull 'Ann' and 'Smith' out of 'Ann Smith' with string splitting instead of two manual substring calls.","body":{"slug":"split-full-name-first-last","name":"Split a full name into first and last","h1":"Split a full name into first and last name in SQL","category":"text","lede":"A single full_name column has to feed a first_name / last_name pair, at least for the common two-part case.","engine_slug":"postgresql","problem":"The table stores one full_name column but the mail-merge template needs first and last names. Split on the space.","sql":"SELECT\n    split_part(full_name, ' ', 1) AS first_name,\n    CASE WHEN position(' ' IN full_name) > 0\n         THEN substring(full_name FROM position(' ' IN full_name) + 1)\n         ELSE NULL END AS last_name\nFROM customers;","how_it_works":"split_part grabs the text before the first space for the first name. For the last name the CASE guards single-word names, and substring takes everything after the first space, so 'Ann Marie Smith' keeps 'Marie Smith' as the last name rather than losing a middle name.","variants":[{"sql":"SELECT\n    LEFT(full_name, CHARINDEX(' ', full_name + ' ') - 1) AS first_name,\n    CASE WHEN CHARINDEX(' ', full_name) > 0\n         THEN SUBSTRING(full_name, CHARINDEX(' ', full_name) + 1, LEN(full_name))\n         ELSE NULL END AS last_name\nFROM customers;"},{"sql":"SELECT\n    SUBSTRING_INDEX(full_name, ' ', 1) AS first_name,\n    CASE WHEN full_name LIKE '% %'\n         THEN SUBSTRING_INDEX(full_name, ' ', -1) ELSE NULL END AS last_name\nFROM customers;"}],"see_also":["extract-domain-from-email","split-csv-into-rows"],"faqs":[{"question":"How do middle names fit in?","answer":"The first space defines the split: everything after it stays together as the last name. That preserves middle names in the last-name field; the MySQL variant instead returns only the final word, so 'Ann Marie Smith' gives 'Smith' and the middle name is lost. Decide which behaviour you want; neither handles 'Juan de la Cruz' correctly."}]},"source_url":"https://sqlly.app/sql-snippets/split-full-name-first-last","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/starts-with-ends-with-tests","corpus":"sql-snippets","engine":"all","language":"en","title":"Test whether a string starts or ends with a value in SQL","description":"Match SKUs beginning with 'AB-' or codes ending in '-XY' with LIKE and index-friendly range scans.","body":{"slug":"starts-with-ends-with-tests","name":"Test prefixes and suffixes","h1":"Test whether a string starts or ends with a value in SQL","category":"text","lede":"Prefix tests select product families; suffix tests select regional codes. Both should stay index-friendly where possible.","engine_slug":"all","problem":"LIKE with a wildcard only at the end is a prefix test that can use an index; a leading wildcard is a suffix test that cannot.","sql":"-- starts with AB-\nSELECT sku\nFROM products\nWHERE sku LIKE 'AB-%';\n\n-- ends with -XY (cannot use a plain index)\nSELECT sku\nFROM products\nWHERE sku LIKE '%-XY';","how_it_works":"LIKE 'AB-%' keeps the constant prefix first, so a b-tree index on sku can seek it on SQL Server, MySQL and Oracle. PostgreSQL only does that with the C collation or an index built with text_pattern_ops, and SQLite only when the LIKE's case sensitivity matches the column's collation. LIKE '%-XY' must scan every row because any position could match; large tables deserve an indexed computed column of REVERSE(sku) for suffix searches.","variants":[{"sql":"SELECT sku\nFROM products\nWHERE starts_with(sku, 'AB-');"},{"sql":"SELECT sku\nFROM products\nWHERE sku >= 'AB-' AND sku < 'AB.';"}],"see_also":["extract-leading-digits","find-nth-occurrence-substring"],"faqs":[{"question":"Why does the range trick avoid a scan?","answer":"The upper bound is the prefix with its last character bumped by one ('-' is 0x2D, '.' is 0x2E), so every string starting with 'AB-' sorts between 'AB-' and 'AB.' and the predicate becomes a range an index can seek. That only holds where '-' sorts as an ordinary character. PostgreSQL's default en_US collation, and SQL Server's nvarchar columns and Windows collations, give the hyphen almost no weight, so the range returns only the bare value 'AB-'. Add COLLATE \"C\" on PostgreSQL or COLLATE Latin1_General_BIN2 on SQL Server."}]},"source_url":"https://sqlly.app/sql-snippets/starts-with-ends-with-tests","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/statement-timeout-session","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Set statement timeout per session and role in PostgreSQL","description":"Sets statement_timeout, lock_timeout and idle_in_transaction_session_timeout for the current session, with the per-role defaults that make the limits stick.","body":{"slug":"statement-timeout-session","name":"Statement timeout","h1":"Set statement timeout per session and role in PostgreSQL","category":"monitoring","lede":"Set the limits once per role and every new session for that role enforces them, with no application changes.","engine_slug":"postgresql","problem":"PostgreSQL's timeout parameters bound runaway work at three levels: statement_timeout caps each statement, lock_timeout caps how long anything waits for a lock before erroring, and idle_in_transaction_session_timeout ends sessions that open a transaction and go quiet. PostgreSQL 17 added a fourth, transaction_timeout, for the whole transaction. A SET applies at once to the current session only; ALTER ROLE ... SET makes the value the default for every new session of that role.","sql":"SET statement_timeout = '5s';\nSET lock_timeout = '3s';\nSET idle_in_transaction_session_timeout = '60s';","how_it_works":"SET applies to the current session only, which suits a reporting session or a migration script that needs its own guardrails. A statement that exceeds statement_timeout is cancelled with an error; inside an explicit transaction that leaves the transaction aborted until the client rolls back. idle_in_transaction_session_timeout terminates the whole connection. The per-role variant makes the policy stick: ALTER ROLE reporting SET statement_timeout = '30s' applies to every new reporting session. Migrations need lock_timeout most. An ALTER TABLE waiting for its ACCESS EXCLUSIVE lock makes every later query on that table queue behind it, so a lock_timeout of a few seconds makes the migration fail fast (and retry) instead of stalling all traffic on the table.","variants":[{"sql":"ALTER ROLE reporting SET statement_timeout = '30s';\nALTER ROLE app SET statement_timeout = '5s';\nALTER ROLE app SET idle_in_transaction_session_timeout = '60s';\nALTER ROLE etl SET statement_timeout = '2h';"},{"sql":"SELECT name, setting, unit, source\nFROM pg_settings\nWHERE name IN ('statement_timeout', 'lock_timeout', 'idle_in_transaction_session_timeout')\nORDER BY name;"}],"see_also":["kill-query-safely","terminate-backend","long-transactions"],"faqs":[{"question":"Why did my timeout not seem to apply?","answer":"statement_timeout counts the whole statement, lock waits included, and lock_timeout separately caps each lock wait; whichever runs out first cancels the statement. Neither counts time between statements, which is idle_in_transaction_session_timeout's job. If a value seems ignored, check pg_settings.source. A SET overrides role and database defaults for the session, but a pooler that runs DISCARD ALL or RESET ALL between clients (PgBouncer's server_reset_query, for example) puts the role default back, and in PgBouncer's transaction mode a SET may land on a different server connection than your next query."},{"question":"What is a sensible statement_timeout for an app role?","answer":"A margin above the slowest legitimate query that role runs, measured rather than guessed (pg_stat_statements max_exec_time is a good source). If the slowest normal request takes 2 seconds, 5 seconds leaves room; a 30-second limit on an interactive application role usually means a slow query is being tolerated rather than fixed. Batch and reporting roles get their own, longer limits."}]},"source_url":"https://sqlly.app/sql-snippets/statement-timeout-session","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/statistics-staleness","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find stale planner statistics in PostgreSQL","description":"Ranks tables by rows modified since the last ANALYZE, manual or automatic, to find tables whose planner statistics no longer describe the data.","body":{"slug":"statistics-staleness","name":"Statistics staleness","h1":"Find stale planner statistics in PostgreSQL","category":"monitoring","lede":"The planner is only as good as its statistics. This shows which tables have changed the most since stats were last collected.","engine_slug":"postgresql","problem":"PostgreSQL tracks n_mod_since_analyze per table: the estimated number of rows inserted, updated or deleted since statistics were last collected. When the statistics lag far behind the data, the planner misjudges row counts, and that produces the classic bad plans: the wrong join order, a nested loop over a million rows it expected to be ten, or a hash table sized for a distribution that no longer exists. A common case is a column of dates where the histogram ends last week, so the planner thinks queries for today match almost nothing.","sql":"SELECT relname AS table_name,\n       n_mod_since_analyze,\n       n_live_tup,\n       ROUND(100.0 * n_mod_since_analyze / NULLIF(n_live_tup, 0), 1) AS pct_changed,\n       last_analyze, last_autoanalyze,\n       GREATEST(last_analyze, last_autoanalyze) AS last_stats\nFROM pg_stat_user_tables\nWHERE n_mod_since_analyze > 0\nORDER BY n_mod_since_analyze DESC\nLIMIT 25;","how_it_works":"n_mod_since_analyze is the number of rows inserted, updated or deleted since the last ANALYZE or autoanalyze, from the cumulative statistics system. pct_changed relates it to n_live_tup, so a 1,000-row change reads as trivial on a 10-million-row table and as most of the table on a 2,000-row one; it can exceed 100 when the same rows change repeatedly. GREATEST of last_analyze and last_autoanalyze gives the effective last-stats timestamp; NULL on both means the table has never been analyzed, a strong candidate for immediate action, often right after a bulk load.","variants":[{"sql":"SELECT relname, n_live_tup, last_analyze, last_autoanalyze\nFROM pg_stat_user_tables\nWHERE last_analyze IS NULL AND last_autoanalyze IS NULL\nORDER BY n_live_tup DESC;"},{"sql":"SELECT OBJECT_SCHEMA_NAME(s.object_id) AS schema_name,\n       OBJECT_NAME(s.object_id) AS table_name, s.name AS stats_name,\n       sp.last_updated, sp.rows, sp.modification_counter,\n       CAST(100.0 * sp.modification_counter / NULLIF(sp.rows, 0) AS DECIMAL(8,1)) AS pct_modified\nFROM sys.stats s\nCROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) sp\nWHERE OBJECT_NAME(s.object_id) IS NOT NULL\nORDER BY sp.modification_counter DESC;"}],"see_also":["last-analyze-per-table","index-usage-ratio-per-table","autovacuum-status"],"faqs":[{"question":"Does autovacuum automatically analyze too?","answer":"Yes. The autovacuum daemon analyzes a table once n_mod_since_analyze exceeds autovacuum_analyze_threshold plus autovacuum_analyze_scale_factor times the row count, 50 rows plus 10 percent by default. On a 500-million-row table that is 50 million changes, which can take weeks, so large tables often get a lower per-table autovacuum_analyze_scale_factor. Run ANALYZE yourself right after a bulk load, before the queries that depend on it, because autovacuum gets to it only later."},{"question":"I just ran ANALYZE but the plan is still bad. Why?","answer":"ANALYZE samples about 300 times default_statistics_target rows (30,000 by default) and builds per-column statistics, which leaves several gaps. It assumes columns are independent, so city = 'Paris' AND country = 'France' is underestimated until you create extended statistics (CREATE STATISTICS ... ON city, country). A skewed column may need a higher per-column statistics target. And a prepared statement can switch to a generic plan after five executions, built without knowing the parameter values. Compare estimated and actual rows in EXPLAIN (ANALYZE) to see which estimate is off."}]},"source_url":"https://sqlly.app/sql-snippets/statistics-staleness","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/strip-diacritics-accents","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Strip diacritics and accents in SQL","description":"Turn 'José' into 'Jose'. What each engine can do, and where it falls short.","body":{"slug":"strip-diacritics-accents","name":"Strip diacritics and accents","h1":"Strip diacritics and accents in SQL","category":"text","lede":"Match accented names against ASCII ones: search for 'jose' and still find José.","engine_slug":"postgresql","problem":"Searches for 'jose' never find 'José' unless the accents are gone. PostgreSQL can do this cleanly with the unaccent extension.","sql":"SELECT unaccent(last_name) AS plain_name\nFROM customers\nWHERE unaccent(lower(last_name)) = 'jose';","how_it_works":"unaccent() maps each accented letter to its base letter. The extension ships with PostgreSQL but must be installed once per database (CREATE EXTENSION unaccent) and used with an IMMUTABLE wrapper for expression indexes. Results for non-Latin scripts can be surprising.","variants":[{"sql":"SELECT CONVERT(last_name, 'US7ASCII') AS plain_name\nFROM customers;"},{"sql":"SELECT CONVERT(last_name USING ascii) AS plain_name\nFROM customers;"}],"see_also":["compare-strings-ignoring-case-accents","extract-domain-from-email"],"faqs":[{"question":"Why is this not portable?","answer":"None of the engines agree. PostgreSQL transliterates with unaccent. Oracle's CONVERT to US7ASCII turns 'José García' into 'Jose Garcia' but some letters, Ñ and ñ among them, come back as '?', and it only works on VARCHAR2 values, not NVARCHAR2. MySQL's USING ascii replaces every accented letter with '?'. SQL Server has no function; the known trick CAST(name COLLATE SQL_Latin1_General_CP1253_CI_AI AS varchar(100)) strips accents through a Greek code page, but comparing with an accent-insensitive collation is usually the better fix."}]},"source_url":"https://sqlly.app/sql-snippets/strip-diacritics-accents","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/sum-if-recipe","corpus":"sql-snippets","engine":"all","language":"en","title":"Conditional sums (SUM IF)","description":"Sum a column only for the rows that match each condition, several conditions per query, one table scan.","body":{"slug":"sum-if-recipe","name":"Conditional sums","h1":"Conditional sums (SUM IF)","category":"querying","lede":"CASE picks the rows, SUM adds them. The same expression is what a CASE pivot is built from.","engine_slug":"all","problem":"You want, per customer, the shipped revenue and the returned revenue as a negative number, in one grouped query.","sql":"SELECT customer_id,\n       SUM(CASE WHEN status = 'shipped' THEN amount ELSE 0 END) AS shipped_amount,\n       SUM(CASE WHEN status = 'returned' THEN -amount ELSE 0 END) AS returned_amount\nFROM orders\nGROUP BY customer_id\nORDER BY customer_id;","how_it_works":"Each CASE transforms the rows into a per-condition measure: matching rows contribute their amount (negated for returns), everything else contributes 0, and the grouped SUM collapses it. Any expression can live inside the THEN, so the same pattern handles net amounts, VAT buckets or weighted scores. Like count-if, engines with FILTER make it read nicer.","variants":[{"sql":"SELECT customer_id,\n       SUM(amount) FILTER (WHERE status = 'shipped') AS shipped_amount,\n       SUM(-amount) FILTER (WHERE status = 'returned') AS returned_amount\nFROM orders\nGROUP BY customer_id;"}],"see_also":["count-if-recipe","percentage-of-total","pivot-rows-to-columns-case"],"faqs":[{"question":"Why ELSE 0 and not ELSE NULL?","answer":"For SUM they give the same total, except that a group with no matching rows sums to NULL rather than 0 (the FILTER variant has the same NULL behaviour). For AVG and MIN they differ: ELSE 0 drags averages down and makes 0 the minimum, while ELSE NULL computes those aggregates over the matching rows only."}]},"source_url":"https://sqlly.app/sql-snippets/sum-if-recipe","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/swap-two-table-names","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Swap two table names","description":"Exchange a live table with its rebuilt replacement in one transaction, and check which views and foreign keys end up pointing at the old copy.","body":{"slug":"swap-two-table-names","name":"Swap two table names","h1":"Swap two table names","category":"schema","lede":"Blue-green table deployments end with a swap: the new table takes the old name and the old one steps aside. The trick is doing it without a moment where neither name exists.","engine_slug":"postgresql","problem":"The rebuilt replacement table is loaded and verified, and it must now take over the live name with no gap in which queries cannot find the table.","sql":"BEGIN;\nALTER TABLE products RENAME TO products_old;\nALTER TABLE products_new RENAME TO products;\nCOMMIT;\n-- products_old now holds the previous data; inspect, then drop","how_it_works":"Both renames commit together, so no query ever finds the products name missing; each rename takes an ACCESS EXCLUSIVE lock, so queries on either table wait until COMMIT. Only the names move. Views and foreign keys reference tables by OID, so after the swap they point at products_old, not the new products; recreate them, or use CREATE OR REPLACE VIEW, before dropping the old table. Sequences, indexes and constraints are whatever the new table was built with.","variants":[{"sql":"RENAME TABLE products TO products_old,\n             products_new TO products;\n-- atomic in one statement. Views look tables up by name and\n-- use the new products; foreign keys follow products_old"},{"sql":"BEGIN TRAN;\nEXEC sp_rename 'dbo.Products', 'Products_old';\nEXEC sp_rename 'dbo.Products_New', 'Products';\nCOMMIT;"},{"sql":"-- with legacy_alter_table off (the default), SQLite rewrites\n-- views, triggers and FKs to follow each rename, so they\n-- end up on products_old, as on PostgreSQL\nBEGIN;\nALTER TABLE products RENAME TO products_old;\nALTER TABLE products_new RENAME TO products;\nCOMMIT;"}],"see_also":["create-empty-like-table","copy-table-with-data","rename-table-safely"],"faqs":[{"question":"Will foreign keys pointing at the old table follow the swap?","answer":"No. On PostgreSQL, MySQL and SQLite, a foreign key in another table follows the table it was created against, so after the swap it references products_old. SQL Server behaves the same, since foreign keys store the object ID. Drop and recreate those constraints against the new products, ideally in the same transaction as the swap, before you drop products_old."},{"question":"Is the swap atomic on every engine?","answer":"Each rename is atomic everywhere, and the pair commits together inside one transaction on PostgreSQL, SQL Server and SQLite. MySQL's RENAME TABLE does both moves in a single statement because its DDL cannot be wrapped in a transaction, while SQLite is transactional enough that even a drop-and-recreate would be all or nothing."}]},"source_url":"https://sqlly.app/sql-snippets/swap-two-table-names","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/symmetric-difference-two-tables","corpus":"sql-snippets","engine":"all","language":"en","title":"Find rows that differ between two tables","description":"Symmetric difference of two tables with UNION ALL plus GROUP BY: rows in one table only, either direction.","body":{"slug":"symmetric-difference-two-tables","name":"Symmetric diff","h1":"Find rows that differ between two tables","category":"data-quality","lede":"Stack both tables with UNION ALL, group by every column, and keep groups whose total count is 1: rows that exist on one side only.","engine_slug":"all","problem":"You just rewrote the products load and want proof that products_staging matches the live products table row for row. Rows present in only one side, or with any changed value, must surface.","sql":"SELECT MIN(source) AS found_in, sku, name, price\nFROM (\n  SELECT sku, name, price, 'staging' AS source\n  FROM products_staging\n  UNION ALL\n  SELECT sku, name, price, 'live' AS source\n  FROM products\n) combined\nGROUP BY sku, name, price\nHAVING COUNT(*) = 1\nORDER BY sku, found_in;","how_it_works":"The inner UNION ALL concatenates both tables with a tag. Grouping over every column collapses matched pairs into groups of 2; rows that differ in any column, or exist on one side only, form groups of 1, which HAVING keeps. MIN(source) tells you which side the odd row came from. Because GROUP BY treats NULLs as equal, a NULL price on both sides counts as a match, which the changed-rows variant's <> comparison does not: there a NULL on either side makes the row disappear. migration-diff-preview points this diff at migration copies and pairs it with a per-key join that separates rewritten rows from added ones.","variants":[{"sql":"SELECT o.sku, o.name AS old_name, o.price AS old_price,\n       n.name AS new_name, n.price AS new_price\nFROM products o\nJOIN products_staging n ON n.sku = o.sku\nWHERE o.name <> n.name OR o.price <> n.price;"},{"sql":"SELECT sku, name, price FROM products\nEXCEPT\nSELECT sku, name, price FROM products_staging;"}],"see_also":["migration-diff-preview","compare-table-counts","checksum-a-table"],"faqs":[{"question":"What if each table can contain internal duplicates?","answer":"The COUNT(*) = 1 trick assumes no table repeats a row internally: one row in each side cancels out to 2. If duplicates within a table are possible, first compare per sku with the changed-rows variant, or count occurrences per row per side and compare the two counts explicitly instead of relying on the union trick."},{"question":"Why GROUP BY instead of EXCEPT or MINUS?","answer":"Set operators dedupe, so two identical rows on one side look like one and the diff undercounts; the GROUP BY over every column counts occurrences per side and catches doubled loads too. It also sidesteps dialect trivia such as Oracle spelling the operator MINUS before 21c."}]},"source_url":"https://sqlly.app/sql-snippets/symmetric-difference-two-tables","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/table-bloat-estimate","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Table bloat estimate","description":"How many dead rows each PostgreSQL table carries according to the live/dead tuple counters, which shows whether vacuum is keeping up with the churn.","body":{"slug":"table-bloat-estimate","name":"Table bloat estimate","h1":"Table bloat estimate","category":"schema","lede":"Updates and deletes leave dead rows behind until vacuum reclaims them, and a table can double in size from churn alone. This recipe ranks tables by their dead-tuple overhead.","engine_slug":"postgresql","problem":"A table's footprint keeps growing even though row counts stay flat, and it is unclear when vacuum last caught up. Comparing live and dead tuple counts shows what the space is made of.","sql":"SELECT relname AS table_name,\n       n_live_tup,\n       n_dead_tup,\n       ROUND(100.0 * n_dead_tup\n             / NULLIF(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,\n       last_autovacuum\nFROM pg_stat_user_tables\nWHERE n_dead_tup > 0\nORDER BY n_dead_tup DESC;","how_it_works":"pg_stat_user_tables tracks live and dead tuple estimates per table; dead rows are the ones the next VACUUM can clear. A high dead_pct with an old last_autovacuum points at a table autovacuum is not keeping up with, often because a long-running transaction is holding back cleanup. These counters only show pending cleanup, not bloat: after VACUUM the space is free for reuse inside the table but the file stays the same size, and only a rewrite (VACUUM FULL or pg_repack) shrinks it. The pgstattuple variant measures that free space directly.","variants":[{"sql":"-- needs the pgstattuple extension; exact, but scans the table\nCREATE EXTENSION IF NOT EXISTS pgstattuple;\nSELECT pg_size_pretty(table_len) AS table_size,\n       dead_tuple_percent,\n       free_percent\nFROM pgstattuple('public.orders');"},{"sql":"-- a low avg_page_space_used_in_percent means half-empty\n-- pages (wasted space); forwarded_record_count > 0 on a heap\n-- means updated rows moved and left pointers behind.\n-- Both columns are NULL in the default LIMITED mode.\nSELECT ips.index_id, ips.index_type_desc, ips.page_count,\n       ips.avg_page_space_used_in_percent,\n       ips.avg_fragmentation_in_percent,\n       ips.forwarded_record_count\nFROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID('dbo.Orders'),\n                                    NULL, NULL, 'SAMPLED') ips;"}],"see_also":["row-counts-every-table","list-all-tables-sizes","database-size-summary"],"faqs":[{"question":"Should I run VACUUM FULL on a bloated table?","answer":"VACUUM FULL returns the space to the OS but holds an ACCESS EXCLUSIVE lock for the whole rewrite, blocking reads as well as writes, and needs free disk for a full copy of the table. pg_repack does the rewrite while the table stays in use. To keep it from coming back, tune autovacuum for the hot table, for example ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.02)."}]},"source_url":"https://sqlly.app/sql-snippets/table-bloat-estimate","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/table-dependency-order","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Table dependency order for load and dump","description":"Which tables each table's foreign keys point at, the input for sorting tables so parents load before children and get emptied after them.","body":{"slug":"table-dependency-order","name":"Table dependency order","h1":"Table dependency order for load and dump","category":"schema","lede":"Restore order matters: a row referencing a parent that is not there yet fails. This recipe maps each table to the tables its foreign keys depend on, the input for a load order.","engine_slug":"postgresql","problem":"A seed or import script aborts on foreign-key violations because some tables land before the tables they reference. The fix is an explicit order derived from the dependency map.","sql":"SELECT src.relname AS table_name,\n       string_agg(DISTINCT tgt.relname, ', ' ORDER BY tgt.relname) AS depends_on\nFROM pg_constraint con\nJOIN pg_class src ON src.oid = con.conrelid\nJOIN pg_class tgt ON tgt.oid = con.confrelid\nWHERE con.contype = 'f'\nGROUP BY src.relname\nORDER BY src.relname;","how_it_works":"Every foreign key points from a child table to a parent table, so the child must be loaded after everything it lists here. Tables missing from this output have no foreign keys and can load first. A table that references itself, such as employees.manager_id, lists itself; load it in one pass with parents first or with the constraint deferred. Cycles between tables have no valid order, so break them as the FAQ describes.","variants":[{"sql":"-- load_order 0 = no foreign keys; load in ascending order.\n-- T-SQL CTEs are recursive without the RECURSIVE keyword.\n-- Self-references are skipped. Tables in a cycle are left\n-- out, or, if the cycle hangs off a loadable table, the\n-- query stops with the 100-level MAXRECURSION error.\nWITH fk AS (\n    SELECT DISTINCT parent_object_id AS child_id,\n           referenced_object_id AS parent_id\n    FROM sys.foreign_keys\n    WHERE parent_object_id <> referenced_object_id),\ndepth AS (\n    SELECT t.object_id, 0 AS lvl FROM sys.tables t\n    WHERE NOT EXISTS (SELECT 1 FROM fk WHERE fk.child_id = t.object_id)\n    UNION ALL\n    SELECT fk.child_id, depth.lvl + 1\n    FROM fk JOIN depth ON depth.object_id = fk.parent_id)\nSELECT OBJECT_SCHEMA_NAME(object_id) AS schema_name,\n       OBJECT_NAME(object_id) AS table_name,\n       MAX(lvl) AS load_order\nFROM depth\nGROUP BY object_id\nORDER BY load_order, table_name;"},{"sql":"SELECT kcu.table_name AS child_table,\n       kcu.referenced_table_name AS parent_table\nFROM information_schema.key_column_usage kcu\nWHERE kcu.table_schema = 'mydb'\n  AND kcu.referenced_table_name IS NOT NULL\nORDER BY kcu.table_name;"}],"see_also":["truncate-all-tables-safe-order","generate-drop-table-statements","list-foreign-keys-targets"],"faqs":[{"question":"How do I handle circular foreign keys?","answer":"Two tables that reference each other have no valid order. On PostgreSQL, declare the constraints DEFERRABLE and load both tables in one transaction after SET CONSTRAINTS ALL DEFERRED, so the check runs at COMMIT. Otherwise turn checking off for the load (SET FOREIGN_KEY_CHECKS = 0 on MySQL, ALTER TABLE ... NOCHECK CONSTRAINT on SQL Server, SET session_replication_role = replica on PostgreSQL, which needs superuser), or create the foreign keys after all the data is in."},{"question":"How do cycles work on engines without deferrable constraints?","answer":"SQL Server has no DEFERRABLE option, so a cycle there must be broken by loading with a nullable foreign key and filling it in afterward, or by disabling the constraint for the load and re-checking it with ALTER TABLE ... WITH CHECK CHECK CONSTRAINT. The order from this query still applies to everything outside the cycle."}]},"source_url":"https://sqlly.app/sql-snippets/table-dependency-order","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/table-index-sizes-topn","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find the largest tables and indexes in PostgreSQL","description":"Ranks tables by total size with the table, index and toast portions broken out, so you know whether bytes live in rows, in indexes or in both.","body":{"slug":"table-index-sizes-topn","name":"Table sizes top N","h1":"Find the largest tables and indexes in PostgreSQL","category":"monitoring","lede":"Top tables by size, split into heap, index and toast. The breakdown tells you what kind of problem you have.","engine_slug":"postgresql","problem":"A table's size is really three numbers: the heap (the rows), its indexes, and TOAST (large values stored out of line). A table that is 80 percent index has too many or bloated indexes; one that is mostly TOAST is holding large documents; one that is mostly heap with many dead rows needs vacuum attention. pg_total_relation_size minus pg_relation_size gives the index plus TOAST part, and pg_indexes_size separates the two.","sql":"SELECT schemaname, relname AS table_name,\n       pg_relation_size(relid) AS heap_bytes,\n       pg_indexes_size(relid) AS index_bytes,\n       pg_total_relation_size(relid) - pg_relation_size(relid) - pg_indexes_size(relid) AS toast_bytes,\n       pg_total_relation_size(relid) AS total_bytes,\n       pg_size_pretty(pg_relation_size(relid)) AS heap,\n       pg_size_pretty(pg_indexes_size(relid)) AS indexes,\n       pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid) - pg_indexes_size(relid)) AS toast,\n       pg_size_pretty(pg_total_relation_size(relid)) AS total,\n       n_live_tup, n_dead_tup\nFROM pg_stat_user_tables\nORDER BY pg_total_relation_size(relid) DESC\nLIMIT 25;","how_it_works":"pg_relation_size(relid) is the heap's main fork only. pg_indexes_size is all indexes on the table, and pg_total_relation_size adds those, the TOAST table with its index, and the small free-space and visibility map forks, so the toast column also carries those few pages. The raw byte columns sit beside the pretty ones because they sort and diff correctly. n_live_tup and n_dead_tup put the heap figure in context: a large dead count means part of that heap is reusable space rather than data. largest-indexes does this ranking instance-wide; the variant here zooms into one table's indexes.","variants":[{"sql":"SELECT TOP 25\n    OBJECT_SCHEMA_NAME(ps.object_id) AS schema_name,\n    OBJECT_NAME(ps.object_id) AS table_name,\n    CAST(SUM(ps.reserved_page_count) * 8 / 1024.0 AS DECIMAL(12,1)) AS reserved_mb,\n    CAST(SUM(ps.used_page_count) * 8 / 1024.0 AS DECIMAL(12,1)) AS used_mb,\n    CAST(SUM(CASE WHEN ps.index_id IN (0, 1) THEN ps.used_page_count ELSE 0 END) * 8 / 1024.0 AS DECIMAL(12,1)) AS data_mb,\n    CAST(SUM(CASE WHEN ps.index_id > 1 THEN ps.used_page_count ELSE 0 END) * 8 / 1024.0 AS DECIMAL(12,1)) AS nonclustered_mb\nFROM sys.dm_db_partition_stats ps\nWHERE OBJECTPROPERTY(ps.object_id, 'IsUserTable') = 1\nGROUP BY ps.object_id\nORDER BY reserved_mb DESC;"},{"sql":"SELECT relname AS table_name, indexrelname AS index_name,\n       pg_size_pretty(pg_relation_size(indexrelid)) AS size, idx_scan\nFROM pg_stat_user_indexes\nORDER BY pg_relation_size(indexrelid) DESC\nLIMIT 25;"}],"see_also":["largest-indexes","index-bloat-estimate","per-database-file-sizes"],"faqs":[{"question":"My table shrank after DELETE but the size stayed the same. Why?","answer":"DELETE only marks rows dead. A plain VACUUM makes their space reusable by later inserts and updates, and gives space back to the operating system only when the empty pages are at the very end of the table. VACUUM FULL rewrites the table compactly but holds an ACCESS EXCLUSIVE lock for the whole rewrite; the pg_repack extension does the same job with only brief locks. SQL Server keeps freed pages allocated to the data file in the same way unless you shrink the file, which fragments indexes and is rarely worth it."},{"question":"Toast is huge on a table I thought was small. What does that mean?","answer":"When a row would exceed about 2 KB, PostgreSQL compresses its largest variable-length values (text, jsonb, bytea) and moves them out of line into the TOAST table until the row fits. A big TOAST part means the table holds large documents. Updating other columns reuses the existing TOAST values, but every change to a large value writes a complete new copy, so a frequently edited jsonb document grows TOAST and WAL quickly. Splitting the large column into its own table, switching to lz4 compression (PostgreSQL 14 and later), or keeping large files in object storage are the usual remedies."}]},"source_url":"https://sqlly.app/sql-snippets/table-index-sizes-topn","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/table-scan-detector","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Detect recent sequential scans in PostgreSQL","description":"Ranks tables by seq_scan and rows read sequentially, to find the tables where a missing or unused index hurts the most.","body":{"slug":"table-scan-detector","name":"Sequential scan detector","h1":"Detect recent sequential scans in PostgreSQL","category":"indexes","lede":"A high seq_tup_read means PostgreSQL is walking entire tables. This shows which ones and how badly.","engine_slug":"postgresql","problem":"pg_stat_user_tables counts both seq_scan (sequential, full-table scans) and idx_scan (index scans) per table, plus seq_tup_read, the number of rows actually streamed during those full scans. A table with a handful of seq_scans but billions of seq_tup_read is a giant table being read end to end by queries that probably wanted an index.","sql":"SELECT schemaname, relname AS table_name,\n       seq_scan, seq_tup_read,\n       idx_scan, idx_tup_fetch,\n       pg_size_pretty(pg_relation_size(relid)) AS table_size,\n       ROUND(seq_tup_read::numeric / NULLIF(seq_scan, 0)) AS avg_rows_per_scan\nFROM pg_stat_user_tables\nWHERE seq_scan > 0\nORDER BY seq_tup_read DESC\nLIMIT 25;","how_it_works":"seq_tup_read counts the live rows returned by sequential scans, so it measures the work, while seq_scan only counts how often it happened: one scan a minute of a 100-million-row table costs far more than a thousand scans a minute of a 10-row lookup table. avg_rows_per_scan close to the table's row count means each scan reads the whole table; a much lower figure usually means scans that stop early, such as a LIMIT without a matching index. Check pg_stat_statements before adding an index, because some full scans are correct: a query that aggregates most of the table is faster as a sequential scan.","variants":[{"sql":"SELECT relname AS table_name, seq_scan, seq_tup_read, n_live_tup,\n       pg_size_pretty(pg_relation_size(relid)) AS table_size\nFROM pg_stat_user_tables\nWHERE n_live_tup > 100000 AND seq_scan > 100\nORDER BY seq_tup_read DESC;"}],"see_also":["high-read-tables","index-usage-ratio-per-table","missing-index-suggestions","explain-query-plan-workflow"],"faqs":[{"question":"Can I reset seq_scan counters to measure a specific period?","answer":"pg_stat_reset() zeroes every table and index counter in the current database, which also restarts the clock for unused-index checks and anyone else's monitoring. pg_stat_reset_single_table_counters('orders'::regclass) limits the damage to one table. Copying the values into a table now and diffing later avoids resetting anything."},{"question":"Every table shows some seq_scan. Is that bad?","answer":"No. Small tables are cheaper to scan than to probe through an index, and queries that read most of a table should scan it. Look at the top of the seq_tup_read ranking together with table size, and use pg_stat_statements to find the queries behind it. PostgreSQL 16 and later also record last_seq_scan per table, which tells you whether the scans are still happening."}]},"source_url":"https://sqlly.app/sql-snippets/table-scan-detector","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/tables-without-any-index","corpus":"sql-snippets","engine":"mysql","language":"en","title":"Find tables without any index","description":"Tables with no index at all, not even a primary key, force a full scan for every lookup. This query finds them in the engine's index metadata.","body":{"slug":"tables-without-any-index","name":"Find tables without any index","h1":"Find tables without any index","category":"schema","lede":"Every lookup on an unindexed table is a full scan. Small lookup tables get away with it; anything that grows does not. This query lists tables with no index of any kind.","engine_slug":"mysql","problem":"Lookups against one table get slower as rows pile up and you suspect nothing indexes it. Before adding another index somewhere else, find which tables carry no index at all.","sql":"SELECT t.table_schema, t.table_name,\n       t.table_rows AS row_estimate\nFROM information_schema.tables t\nWHERE t.table_type = 'BASE TABLE'\n  AND t.table_schema = 'mydb'\n  AND NOT EXISTS (\n        SELECT 1 FROM information_schema.statistics s\n        WHERE s.table_schema = t.table_schema\n          AND s.table_name = t.table_name)\nORDER BY t.table_rows DESC;","how_it_works":"In MySQL every index, including the primary key, appears in information_schema.statistics, so a table with zero rows there has no index at all. The NOT EXISTS filter keeps only such tables, and the row estimate sorts the largest offenders first. InnoDB still clusters such a table on a hidden 6-byte row ID, but nothing can search on that ID, so every lookup scans the whole table. tables-without-primary-key narrows this to the replication-risk case: tables with no key at all.","variants":[{"sql":"SELECT n.nspname AS schema_name, c.relname AS table_name,\n       c.reltuples::bigint AS row_estimate\nFROM pg_class c\nJOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE c.relkind = 'r'\n  AND n.nspname NOT IN ('pg_catalog', 'information_schema')\n  AND NOT EXISTS (\n        SELECT 1 FROM pg_index i\n        WHERE i.indrelid = c.oid)\nORDER BY c.reltuples DESC;"},{"sql":"-- an INTEGER PRIMARY KEY is the rowid and has no entry in\n-- index_list, hence the second check\nSELECT m.name AS table_name\nFROM sqlite_master m\nWHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%'\n  AND NOT EXISTS (\n        SELECT 1 FROM pragma_index_list(m.name) il)\n  AND NOT EXISTS (\n        SELECT 1 FROM pragma_table_info(m.name) ti WHERE ti.pk > 0);"}],"see_also":["tables-without-primary-key","list-table-indexes-columns","unused-index-candidates"],"faqs":[{"question":"Should every table have an index, then?","answer":"Not every table, but every table you search. A bridge table with three rows and a monthly truncate can stay index-free; a multi-million-row fact table without any index is a full scan waiting to happen."}]},"source_url":"https://sqlly.app/sql-snippets/tables-without-any-index","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/tables-without-primary-key","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find tables without a primary key","description":"Tables with no primary key make single-row updates ambiguous and break logical replication of UPDATE and DELETE. This query lists them in one pass.","body":{"slug":"tables-without-primary-key","name":"Find tables without a primary key","h1":"Find tables without a primary key","category":"schema","lede":"A table without a primary key can hold exact duplicate rows, gives you no reliable way to target one row in an UPDATE, and slows MySQL row-based replicas, which must scan to find each changed row.","engine_slug":"postgresql","problem":"An audit of a schema you did not build should answer one question early: which tables have nothing enforcing unique row identity.","sql":"SELECT n.nspname AS schema_name, c.relname AS table_name,\n       c.reltuples::bigint AS row_estimate\nFROM pg_class c\nJOIN pg_namespace n ON n.oid = c.relnamespace\nWHERE c.relkind = 'r'\n  AND n.nspname NOT IN ('pg_catalog', 'information_schema')\n  AND NOT EXISTS (\n        SELECT 1 FROM pg_constraint con\n        WHERE con.conrelid = c.oid AND con.contype = 'p')\nORDER BY c.reltuples DESC, c.relname;","how_it_works":"The NOT EXISTS subquery keeps only tables that have no 'p'-type constraint in pg_constraint. relkind 'r' limits the scan to ordinary tables; add 'p' if you also want to check partitioned parents. Sorting by the row estimate puts the riskiest offenders at the top. tables-without-any-index widens the sweep to tables that lack even a secondary index.","variants":[{"sql":"SELECT s.name AS schema_name, t.name AS table_name\nFROM sys.tables t\nJOIN sys.schemas s ON s.schema_id = t.schema_id\nWHERE NOT EXISTS (\n      SELECT 1 FROM sys.key_constraints kc\n      WHERE kc.parent_object_id = t.object_id AND kc.type = 'PK')\nORDER BY s.name, t.name;"},{"sql":"-- pk_columns = number of columns in the declared primary key\nSELECT m.name AS table_name,\n       COALESCE(SUM(CASE WHEN p.pk > 0 THEN 1 ELSE 0 END), 0) AS pk_columns\nFROM sqlite_master m\nLEFT JOIN pragma_table_info(m.name) p ON true\nWHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%'\nGROUP BY m.name\nHAVING pk_columns = 0;"}],"see_also":["list-primary-keys","find-tables-with-column","tables-without-any-index"],"faqs":[{"question":"Are primary-key-less tables always wrong?","answer":"No. Append-only logs that are never updated and ETL staging tables that are truncated each run can do without one. On PostgreSQL, though, a table in a logical replication publication rejects UPDATE and DELETE unless it has a primary key or a REPLICA IDENTITY set, so add a synthetic key if the table might ever be replicated."}]},"source_url":"https://sqlly.app/sql-snippets/tables-without-primary-key","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/temp-space-consumers","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Find the sessions consuming tempdb space in SQL Server","description":"Ranks live sessions by tempdb pages allocated for user and internal objects; internal pages are the signature of sort and hash spills.","body":{"slug":"temp-space-consumers","name":"Temp space consumers","h1":"Find the sessions consuming tempdb space in SQL Server","category":"monitoring","lede":"tempdb fills up at the worst moment. This shows which session is holding or spilling the pages right now.","engine_slug":"sql-server","problem":"tempdb holds user objects (temp tables, table variables) and internal objects (sort runs, hash join and hash aggregate work files, spools) that SQL Server tracks per session, plus the version store for snapshot isolation and online index builds, which is shared and not charged to any session. When tempdb fills, the session with the largest outstanding internal allocation is usually the spilling query to chase.","sql":"WITH running AS (\n    SELECT session_id,\n           SUM(user_objects_alloc_page_count - user_objects_dealloc_page_count) AS user_pages,\n           SUM(internal_objects_alloc_page_count - internal_objects_dealloc_page_count) AS internal_pages\n    FROM sys.dm_db_task_space_usage\n    GROUP BY session_id\n)\nSELECT s.session_id, s.login_name, s.program_name,\n       r.command, r.status,\n       (su.user_objects_alloc_page_count - su.user_objects_dealloc_page_count\n          + ISNULL(t.user_pages, 0)) / 128 AS user_objects_mb,\n       (su.internal_objects_alloc_page_count - su.internal_objects_dealloc_page_count\n          + ISNULL(t.internal_pages, 0)) / 128 AS internal_objects_mb,\n       ISNULL(t.internal_pages, 0) / 128 AS running_request_internal_mb\nFROM sys.dm_db_session_space_usage su\nJOIN sys.dm_exec_sessions s ON s.session_id = su.session_id\nLEFT JOIN running t ON t.session_id = su.session_id\nLEFT JOIN sys.dm_exec_requests r ON r.session_id = su.session_id\nWHERE s.is_user_process = 1\nORDER BY internal_objects_mb DESC, user_objects_mb DESC;","how_it_works":"Page counts divide by 128 to become megabytes. sys.dm_db_session_space_usage holds what each session's finished tasks allocated and have not freed; it does not include the request running right now. sys.dm_db_task_space_usage covers the running tasks, one row per task, so a parallel query has several rows and the CTE sums them per session. Adding the two gives what each session holds at this moment, and running_request_internal_mb isolates the live spiller during an incident. Internal objects are work tables and work files for sorts, hashes, spools and index builds; if they dominate, a query is spilling, and better estimates or indexes fix it more cheaply than a bigger tempdb. User objects are temp tables and table variables that are still allocated.","variants":[{"sql":"ALTER SYSTEM SET log_temp_files = 102400;\nSELECT pg_reload_conf();"}],"see_also":["temp-table-spilling","session-memory-grants","per-database-file-sizes"],"faqs":[{"question":"tempdb is nearly full. What can I do without restarting?","answer":"Find the session with the largest allocation here; killing a runaway query frees its pages as soon as its rollback completes. If this view shows little but tempdb is still full, check the version store with sys.dm_tran_version_store_space_usage: it cannot shrink while an old snapshot transaction is open, and sys.dm_tran_active_snapshot_database_transactions names the oldest. Adding a tempdb data file on a volume with free space works online and buys time."},{"question":"Do temp tables count against this view?","answer":"Yes. User object pages cover the temp tables and table variables a session has created and not yet dropped. A local #temp table lives until it is dropped or the session ends, so a pooled connection that never drops its temp tables keeps holding them; that shows here as a large user_objects_mb on an idle session."}]},"source_url":"https://sqlly.app/sql-snippets/temp-space-consumers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/temp-table-spilling","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find queries spilling to temp in PostgreSQL","description":"Ranks pg_stat_statements by temp blocks written to catch sorts, hashes and CTEs that overflow work_mem to disk.","body":{"slug":"temp-table-spilling","name":"Temp table spilling","h1":"Find queries spilling to temp in PostgreSQL","category":"monitoring","lede":"When a sort or hash does not fit in work_mem, PostgreSQL spills to disk. This finds the queries doing it most.","engine_slug":"postgresql","problem":"Each sort, hash join and hash aggregate in a plan gets up to work_mem of memory (hash operations get work_mem times hash_mem_multiplier, 2.0 by default). When the data does not fit, PostgreSQL writes it to temporary files and merges or re-reads them, which is much slower than doing the work in memory. pg_stat_statements accumulates temp_blks_written per normalized query, so the queries that spill most often and most heavily are easy to rank. It needs the extension installed and listed in shared_preload_libraries.","sql":"SELECT calls,\n       temp_blks_written,\n       ROUND(temp_blks_written::numeric / 128, 1) AS temp_mb_written,\n       ROUND(temp_blks_written::numeric / NULLIF(calls, 0) / 128, 2) AS temp_mb_per_call,\n       ROUND(mean_exec_time::numeric, 2) AS mean_ms,\n       LEFT(query, 120) AS query\nFROM pg_stat_statements\nWHERE temp_blks_written > 0\nORDER BY temp_blks_written DESC\nLIMIT 20;","how_it_works":"temp_blks_written counts 8 KB blocks written to temp files, so dividing by 128 gives megabytes (8192 bytes per block, 128 blocks per MB). temp_mb_per_call is the more useful number. A few MB per call on a query that runs a million times means a modest work_mem increase, for that role or session, removes a large total cost. Gigabytes per call usually means the query sorts or hashes far more rows than it needs, for example a DISTINCT or GROUP BY over a join that multiplied rows, and the query needs rewriting. EXPLAIN (ANALYZE) shows which node spilled: Sort Method: external merge Disk, or Batches greater than 1 on a Hash node.","variants":[{"sql":"SELECT COUNT_STAR,\n       SUM_CREATED_TMP_TABLES, SUM_CREATED_TMP_DISK_TABLES,\n       ROUND(SUM_TIMER_WAIT / 1e12, 3) AS total_sec,\n       LEFT(DIGEST_TEXT, 120) AS digest\nFROM performance_schema.events_statements_summary_by_digest\nWHERE SUM_CREATED_TMP_DISK_TABLES > 0\nORDER BY SUM_CREATED_TMP_DISK_TABLES DESC\nLIMIT 20;"},{"sql":"SELECT tu.session_id, r.command, r.status,\n       SUM(tu.internal_objects_alloc_page_count - tu.internal_objects_dealloc_page_count) / 128 AS internal_mb,\n       SUM(tu.user_objects_alloc_page_count - tu.user_objects_dealloc_page_count) / 128 AS user_obj_mb\nFROM sys.dm_db_task_space_usage tu\nJOIN sys.dm_exec_requests r ON r.session_id = tu.session_id AND r.request_id = tu.request_id\nGROUP BY tu.session_id, r.command, r.status\nHAVING SUM(tu.internal_objects_alloc_page_count) > 0\nORDER BY internal_mb DESC;"}],"see_also":["temp-space-consumers","sort-heavy-queries","top-queries-by-total-time"],"faqs":[{"question":"Should I just raise work_mem globally?","answer":"Not without arithmetic. work_mem applies per sort or hash node, not per query, and one complex query can have several such nodes, each in every parallel worker. A 64 MB work_mem with 200 concurrent sorts can claim about 12.5 GB, and hash nodes can take twice that. Raise it for the role or session that runs the heavy reports (ALTER ROLE reporting SET work_mem = '256MB'), and keep the global value modest."},{"question":"The top query is a simple ORDER BY on an indexed column. Why does it spill?","answer":"An index on the sort column only avoids the sort if the planner reads rows through that index. If the WHERE clause is served by a different index, or the query sorts the output of a join or aggregate, PostgreSQL sorts explicitly. Run EXPLAIN (ANALYZE) and look for Sort Method: external merge Disk. An index that covers the filter columns first and the sort column after them, such as (status, created_at) for WHERE status = $1 ORDER BY created_at, removes the sort."}]},"source_url":"https://sqlly.app/sql-snippets/temp-table-spilling","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/terminate-backend","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Terminate a session in PostgreSQL","description":"Drops the target PostgreSQL connection with pg_terminate_backend and rolls back its open work, with the checks to run first and when to escalate.","body":{"slug":"terminate-backend","name":"Terminate backend","h1":"Terminate a session in PostgreSQL","category":"monitoring","lede":"pg_terminate_backend ends the connection and rolls back its transaction. Use it when there is no statement to cancel, or the cancel did not work.","engine_slug":"postgresql","problem":"pg_terminate_backend(pid) sends the backend a SIGTERM: the connection closes, its open transaction rolls back, and the application sees a connection error on its next call. In PostgreSQL the rollback itself is quick, because the changes stay in place as dead row versions for vacuum to clean up later, so the locks are released almost immediately even after a large write. It is the step after pg_cancel_backend, for sessions idle in transaction (nothing to cancel) and for sessions that ignore a cancel.","sql":"SELECT pid, usename, datname, application_name, state,\n       now() - xact_start AS xact_age,\n       now() - state_change AS idle_for,\n       LEFT(query, 100) AS last_query,\n       pg_terminate_backend(pid) AS terminate_requested\nFROM pg_stat_activity\nWHERE state = 'idle in transaction'\n  AND now() - state_change > interval '30 minutes'\n  AND backend_type = 'client backend'\n  AND pid <> pg_backend_pid()\nORDER BY state_change;","how_it_works":"The recipe targets the common case, sessions idle inside an open transaction for over 30 minutes, but the same function terminates any pid. Run it without the pg_terminate_backend column first and read the list. Checks: leave out your own pid; keep backend_type = 'client backend' so WAL senders and background workers are never hit; prefer pg_cancel_backend when a statement is running; and remember the work is lost, so terminating a bulk import at 90 percent means starting it over. Without superuser, you can terminate only sessions of your own role or, with membership in pg_signal_backend, those of other non-superusers. kill-query-safely shows the gentler pg_cancel_backend form to try first.","variants":[{"sql":"SELECT pg_terminate_backend(12345);"},{"sql":"-- SQL Server rolls back by undoing the logged changes, which can take as long as the work did\nKILL 53 WITH STATUSONLY;"}],"see_also":["kill-query-safely","idle-in-transaction","long-transactions"],"faqs":[{"question":"Terminate or cancel: what is the decision rule?","answer":"If the session is running a statement, cancel. If it is idle in transaction (no statement to cancel) and holding locks, or it ignored a cancel, terminate. Cancel rolls back the statement, and inside an explicit transaction leaves that transaction aborted until the client rolls back; terminate rolls back the whole transaction and drops the connection."},{"question":"Can I make the database do this automatically?","answer":"Yes. idle_in_transaction_session_timeout ends exactly the sessions this query looks for, statement_timeout caps how long a statement may run, and lock_timeout caps how long a statement waits for a lock. PostgreSQL 17 added transaction_timeout, which caps a whole transaction. Set them per role (ALTER ROLE ... SET) so interactive and batch roles get different limits."}]},"source_url":"https://sqlly.app/sql-snippets/terminate-backend","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/tiebreak-ordering","corpus":"sql-snippets","engine":"all","language":"en","title":"Stable ordering with tiebreaks","description":"Add a unique final column to every ORDER BY so equal rows keep one order across runs, pages and window functions.","body":{"slug":"tiebreak-ordering","name":"Stable ordering with tiebreaks","h1":"Stable ordering with tiebreaks","category":"querying","lede":"SQL does not guarantee row order without it; ties are free to shuffle.","engine_slug":"all","problem":"Rows with the same order_date come back in a different order on every run, which breaks pagination, screenshots and ROW_NUMBER determinism.","sql":"SELECT id, customer_id, order_date, amount\nFROM orders\nORDER BY order_date DESC, amount DESC, id;","how_it_works":"The first two keys express the real sort; id, which is unique, makes the order total, so no two rows can tie and the engine has no freedom left. Any unique column works, such as the primary key or another column with a unique constraint. The same tiebreak belongs inside window ORDER BY clauses when ROW_NUMBER must be reproducible.","variants":[{"sql":"WITH ranked AS (\n  SELECT id, customer_id, amount,\n         ROW_NUMBER() OVER (ORDER BY amount DESC, id) AS rn\n  FROM orders\n)\nSELECT id, customer_id, amount, rn\nFROM ranked\nWHERE rn <= 5\nORDER BY rn;"}],"see_also":["keyset-pagination","offset-pagination-pitfalls","top-n-per-group"],"faqs":[{"question":"Why does the same query return rows in a different order each time?","answer":"Without a unique key in the ORDER BY, the plan may use a hash or parallel scan whose visit order varies. SQL only promises order when ORDER BY can distinguish every pair of rows, which is what the tiebreak column provides."},{"question":"Does the tiebreaker column cost index use?","answer":"It completes the index instead: an index on (region, created_at, id) serves the whole ORDER BY, so the engine reads rows in final order directly. Without the unique column the engine sorts after the index scan, and tie order is whatever the sort produced."}]},"source_url":"https://sqlly.app/sql-snippets/tiebreak-ordering","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/timestamp-bucketing-5-minutes","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Bucket timestamps into 5-minute windows in SQL","description":"Group event timestamps into fixed 5-minute buckets for time-series charts and rollups.","body":{"slug":"timestamp-bucketing-5-minutes","name":"Bucket timestamps to 5-minute windows","h1":"Bucket timestamps into 5-minute windows in SQL","category":"querying","lede":"Charts and rate alerts need events grouped into fixed windows. Epoch flooring makes the bucket boundary independent of any calendar rules.","engine_slug":"postgresql","problem":"Divide the epoch seconds by the window size, floor it, and multiply back: every timestamp lands on a 5-minute mark.","sql":"SELECT\n    to_timestamp(floor(extract(epoch from occurred_at) / 300) * 300) AS bucket_start,\n    count(*) AS events\nFROM page_views\nGROUP BY 1\nORDER BY 1;","how_it_works":"extract(epoch) gives seconds since 1970 as a continuous number, so dividing by 300 and flooring snaps to the containing 5-minute window regardless of time zones, DST or month lengths. to_timestamp converts the bucket edge back to a timestamptz, which displays in the session time zone; if occurred_at is a plain timestamp, append AT TIME ZONE 'UTC' to get a plain timestamp back. Change 300 to 60, 900 or 3600 for other window sizes. PostgreSQL 14+ can write the same bucket as date_bin('5 minutes', occurred_at, TIMESTAMP '2000-01-01').","variants":[{"sql":"SELECT\n    DATEADD(MINUTE, (DATEDIFF(MINUTE, '2000-01-01', occurred_at) / 5) * 5, '2000-01-01') AS bucket_start,\n    COUNT(*) AS events\nFROM page_views\nGROUP BY DATEADD(MINUTE, (DATEDIFF(MINUTE, '2000-01-01', occurred_at) / 5) * 5, '2000-01-01')\nORDER BY bucket_start;"},{"sql":"SELECT\n    FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(occurred_at) / 300) * 300) AS bucket_start,\n    COUNT(*) AS events\nFROM page_views\nGROUP BY bucket_start;"}],"see_also":["month-over-month-delta","round-timestamps"],"faqs":[{"question":"Why floor epoch seconds instead of date_trunc?","answer":"date_trunc only snaps to whole units such as minutes, hours and days. Epoch flooring works for any window size, on any PostgreSQL version, and stays correct across DST because epoch seconds are zone-free. On PostgreSQL 14+ date_bin does the same job, and SQL Server 2022+ has DATE_BUCKET(minute, 5, occurred_at)."}]},"source_url":"https://sqlly.app/sql-snippets/timestamp-bucketing-5-minutes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/title-case-names","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Title-case names in SQL (INITCAP and friends)","description":"Capitalize the first letter of each word in a name, the way INITCAP does on PostgreSQL and Oracle.","body":{"slug":"title-case-names","name":"Title-case names","h1":"Title-case names in SQL (INITCAP and friends)","category":"text","lede":"ALL-CAPS imports like 'ANN MARIE SMITH' look wrong in a CRM. Convert them to title case at query time.","engine_slug":"postgresql","problem":"Bulk imports arrive shouting. INITCAP turns 'ANN MARIE SMITH' into 'Ann Marie Smith' in one call.","sql":"SELECT INITCAP(full_name) AS display_name\nFROM customers;","how_it_works":"INITCAP uppercases the first letter of every word and lowercases the rest, treating any non-letter as a word boundary. That boundary rule cuts both ways: 'o'brien' becomes 'O'Brien', but 'mcdonald' becomes 'Mcdonald', not 'McDonald'. MySQL, SQL Server and SQLite have no INITCAP, so plain string functions can only fix the first letter of the whole string; per-word capitalization there needs a loop or application code. uppercase-first-letter is this recipe reduced to the one-word case.","variants":[{"sql":"SELECT INITCAP(full_name) AS display_name\nFROM customers;"},{"sql":"SELECT CONCAT(UPPER(LEFT(full_name, 1)), LOWER(SUBSTRING(full_name, 2))) AS display_name\nFROM customers;"}],"see_also":["uppercase-first-letter","split-full-name-first-last"],"faqs":[{"question":"Does INITCAP handle hyphenated names?","answer":"Yes: it capitalizes after any character that is not a letter or digit, so 'jean-luc' becomes 'Jean-Luc' and 'o'brien' becomes 'O'Brien'. A letter right after a digit stays lowercase ('3rd' stays '3rd'), and Mc/Mac and van/de prefixes are never handled, so spot-check real names."}]},"source_url":"https://sqlly.app/sql-snippets/title-case-names","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/top-io-sessions","corpus":"sql-snippets","engine":"oracle","language":"en","title":"Find the sessions doing the most I/O in Oracle","description":"Ranks live Oracle sessions by physical reads and consistent gets from v$sess_io, joined to v$session for user and current SQL context.","body":{"slug":"top-io-sessions","name":"Top I/O sessions","h1":"Find the sessions doing the most I/O in Oracle","category":"monitoring","lede":"Which session is doing the most I/O? v$sess_io ranks every connected session by its I/O since it logged on.","engine_slug":"oracle","problem":"When storage is saturated, the first question is which session is responsible. v$sess_io accumulates logical reads (block_gets plus consistent_gets) and physical_reads per session since logon. Joined to v$session it gains the username, machine, module, status and current sql_id, which is enough to find the owner and the statement.","sql":"SELECT s.sid, s.serial#, s.username, s.status, s.machine, s.module,\n       s.sql_id, s.last_call_et AS seconds_in_status,\n       io.block_gets, io.consistent_gets, io.physical_reads\nFROM v$session s\nJOIN v$sess_io io ON io.sid = s.sid\nWHERE s.username IS NOT NULL\n  AND s.username NOT IN ('SYS', 'SYSTEM')\nORDER BY io.physical_reads DESC\nFETCH FIRST 20 ROWS ONLY;","how_it_works":"consistent_gets are block reads in consistent (read-consistent) mode and block_gets are reads in current mode, the kind used to modify a block; together they are the session's logical reads. physical_reads are blocks read from disk, the number that matters when I/O is the bottleneck. last_call_et is the seconds since the session's status last changed: for an ACTIVE session, how long the current call has been running, and for an INACTIVE one, how long it has been idle. An ACTIVE session with a large last_call_et and climbing physical_reads is running a long, I/O-heavy statement right now. SYS and SYSTEM are filtered out to reduce noise; the variant resolves the session's current statement through sql_id. Querying v$ views as a normal user needs SELECT_CATALOG_ROLE, SELECT ANY DICTIONARY or a direct grant on the underlying v_$ views.","variants":[{"sql":"SELECT s.sid, s.username, sq.sql_text, sq.executions,\n       sq.disk_reads, sq.buffer_gets\nFROM v$session s\nJOIN v$sqlarea sq ON sq.sql_id = s.sql_id\nWHERE s.sid = 123;  -- the sid from the main query"},{"sql":"SELECT user, processlist_id, total AS io_events,\n       total_latency, avg_latency, max_latency\nFROM sys.io_by_thread_by_latency\nORDER BY total DESC\nLIMIT 20;"}],"see_also":["parse-vs-execute-ratio","wait-events-summary","longest-running-queries-now"],"faqs":[{"question":"Physical reads are high but the buffer cache is large. What does that mean?","answer":"Either the data the session reads does not fit in the cache, or it is reading with direct path reads, which bypass the buffer cache entirely. Oracle uses direct path reads for parallel query and often for serial full scans of large tables, so a big full scan shows up as physical reads however large the cache is. Look at the statement: a full scan of a large table with a selective WHERE clause is the classic case an index fixes."},{"question":"The counters are cumulative since logon. How do I see recent activity?","answer":"Snapshot v$sess_io twice a few minutes apart and compare, because a pooled connection that has been logged on for a week has a week of totals. For recent statement-level history, v$active_session_history samples active sessions every second, but it requires the Diagnostics Pack license on Enterprise Edition."}]},"source_url":"https://sqlly.app/sql-snippets/top-io-sessions","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/top-n-per-group","corpus":"sql-snippets","engine":"all","language":"en","title":"Top-N rows per group","description":"Get the three most recent orders per customer with ROW_NUMBER instead of a correlated subquery per row.","body":{"slug":"top-n-per-group","name":"Top-N per group","h1":"Top-N rows per group","category":"querying","lede":"Keep the first N rows of every group, ranked by any column, without losing the other columns.","engine_slug":"all","problem":"You want each customer's three most recent orders. A plain GROUP BY collapses the rows and a correlated subquery re-scans the table for every customer.","sql":"WITH ranked AS (\n  SELECT id, customer_id, order_date, amount,\n         ROW_NUMBER() OVER (PARTITION BY customer_id\n                            ORDER BY order_date DESC, id DESC) AS rn\n  FROM orders\n)\nSELECT id, customer_id, order_date, amount\nFROM ranked\nWHERE rn <= 3\nORDER BY customer_id, order_date DESC;","how_it_works":"ROW_NUMBER numbers each customer's orders newest-first. The outer query keeps the rows numbered 1 to 3, so you get exactly three rows per customer with all columns intact. An index on (customer_id, order_date DESC) lets most engines stream this without sorting each partition.","variants":[{"sql":"WITH ranked AS (\n  SELECT id, customer_id, amount,\n         ROW_NUMBER() OVER (PARTITION BY customer_id\n                            ORDER BY amount DESC) AS rn\n  FROM orders\n)\nSELECT id, customer_id, amount\nFROM ranked\nWHERE rn <= 3\nORDER BY customer_id, amount DESC;"},{"sql":"SELECT o.*\nFROM orders o\nWHERE (\n  SELECT COUNT(*)\n  FROM orders o2\n  WHERE o2.customer_id = o.customer_id\n    AND (o2.order_date > o.order_date\n         OR (o2.order_date = o.order_date AND o2.id > o.id))\n) < 3;"}],"see_also":["top-n-with-ties","latest-row-per-customer","rank-within-category"],"faqs":[{"question":"Why ROW_NUMBER and not RANK?","answer":"ROW_NUMBER gives every row a different number, so you always get at most N rows per group. RANK would give tied rows the same rank and could return more than N rows when amounts or dates are equal."},{"question":"Can I do this without a CTE?","answer":"You can swap the CTE for a derived table (FROM (SELECT ...) ranked), but you cannot drop the subquery: a window function is evaluated after WHERE, so WHERE ROW_NUMBER() OVER (...) <= 3 is rejected on every engine. Snowflake and DuckDB add a QUALIFY clause for exactly this; none of the five engines covered here has it."}]},"source_url":"https://sqlly.app/sql-snippets/top-n-per-group","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/top-n-with-ties","corpus":"sql-snippets","engine":"all","language":"en","title":"Top-N with ties per group","description":"Keep every product tied at the top of its category with RANK, so equal prices are never silently dropped.","body":{"slug":"top-n-with-ties","name":"Top-N with ties per group","h1":"Top-N with ties per group","category":"querying","lede":"ROW_NUMBER throws away ties. RANK keeps every row that shares a leading value.","engine_slug":"all","problem":"You want the two most expensive products in every category, but if three products tie at the top you want all three, not two of them picked at random.","sql":"WITH ranked AS (\n  SELECT name, category, price,\n         RANK() OVER (PARTITION BY category\n                      ORDER BY price DESC) AS rnk\n  FROM products\n)\nSELECT name, category, price\nFROM ranked\nWHERE rnk <= 2\nORDER BY category, rnk;","how_it_works":"RANK gives tied rows the same rank and skips the next number, so a three-way tie for first leaves every row at rank 1 and the next row at rank 4. The filter rnk <= 2 keeps everything tied inside the top two ranks. Swap in ROW_NUMBER when you need exactly N rows and can accept an arbitrary winner.","variants":[{"sql":"WITH ranked AS (\n  SELECT name, category, price,\n         DENSE_RANK() OVER (PARTITION BY category\n                            ORDER BY price DESC) AS rnk\n  FROM products\n)\nSELECT name, category, price\nFROM ranked\nWHERE rnk <= 2\nORDER BY category, rnk;"}],"see_also":["top-n-per-group","second-highest-value","multi-condition-ranking"],"faqs":[{"question":"RANK, DENSE_RANK or ROW_NUMBER?","answer":"ROW_NUMBER is 1, 2, 3 with ties broken arbitrarily. RANK is 1, 1, 3 on ties. DENSE_RANK is 1, 1, 2. Use RANK to keep ties, DENSE_RANK when downstream logic wants consecutive levels."},{"question":"How do I return exactly N rows without splitting a tie?","answer":"Rank first and filter on the rank, as this recipe does; a bare LIMIT cuts mid-tie and returns an arbitrary member of the tied set. SQL Server's TOP N WITH TIES and FETCH FIRST ... WITH TIES on PostgreSQL 13+ and Oracle are the one-clause spelling of the same rule."}]},"source_url":"https://sqlly.app/sql-snippets/top-n-with-ties","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/top-queries-by-total-time","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find the most expensive queries in PostgreSQL","description":"Ranks pg_stat_statements by total execution time, with equivalent queries for SQL Server's plan cache, MySQL's digest table and Oracle's v$sql.","body":{"slug":"top-queries-by-total-time","name":"Most expensive queries","h1":"Find the most expensive queries in PostgreSQL","category":"monitoring","lede":"Rank by total time and both kinds of expensive query show up: the rare slow one and the fast one that runs a million times.","engine_slug":"postgresql","problem":"pg_stat_statements normalizes every executed statement (literals replaced by placeholders) and accumulates calls, total, min, max and mean execution time, rows and I/O. Ranking by total_exec_time lists the statements that account for the most server time across the whole workload. That is usually the first place to optimize: a 20 percent improvement to the top statement can be worth more than fixing the ten slowest queries you have ever seen.","sql":"SELECT calls,\n       ROUND(total_exec_time::numeric, 1) AS total_ms,\n       ROUND(mean_exec_time::numeric, 2) AS mean_ms,\n       rows, rows / NULLIF(calls, 0) AS rows_per_call,\n       ROUND(100.0 * shared_blks_hit / NULLIF(shared_blks_hit + shared_blks_read, 0), 1) AS cache_hit_pct,\n       LEFT(query, 120) AS query\nFROM pg_stat_statements\nORDER BY total_exec_time DESC\nLIMIT 20;","how_it_works":"total_exec_time is the sum of all executions since stats were reset (pg_stat_statements_reset). mean_exec_time splits it per call, and rows_per_call distinguishes a query returning 1 row from one returning 100,000; they need different fixes. shared_blks_hit and shared_blks_read give that statement's own buffer cache hit ratio. Setup takes two steps: add pg_stat_statements to shared_preload_libraries in postgresql.conf and restart, then run CREATE EXTENSION pg_stat_statements in the database you query from. A role without superuser or pg_read_all_stats sees <insufficient privilege> in place of the text of other users' statements. PostgreSQL 13 renamed total_time to total_exec_time and split planning time into its own columns, so queries copied from pre-13 notes need their column names updated.","variants":[{"sql":"SELECT TOP 20\n    qs.execution_count,\n    CAST(qs.total_elapsed_time / 1000.0 AS DECIMAL(18,1)) AS total_ms,\n    CAST(qs.total_elapsed_time / 1000.0 / qs.execution_count AS DECIMAL(18,2)) AS mean_ms,\n    LEFT(SUBSTRING(st.text, qs.statement_start_offset / 2 + 1,\n         (CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(st.text)\n               ELSE qs.statement_end_offset END - qs.statement_start_offset) / 2 + 1), 120) AS query\nFROM sys.dm_exec_query_stats qs\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st\nORDER BY qs.total_elapsed_time DESC;"},{"sql":"SELECT SCHEMA_NAME,\n       COUNT_STAR AS calls,\n       ROUND(SUM_TIMER_WAIT / 1e12, 3) AS total_sec,\n       ROUND(AVG_TIMER_WAIT / 1e9, 3) AS mean_ms,\n       LEFT(DIGEST_TEXT, 120) AS digest\nFROM performance_schema.events_statements_summary_by_digest\nORDER BY SUM_TIMER_WAIT DESC\nLIMIT 20;"},{"sql":"SELECT executions,\n       ROUND(elapsed_time / 1000 / 1000, 3) AS total_sec,\n       ROUND(elapsed_time / 1000 / 1000 / NULLIF(executions, 0), 4) AS mean_sec,\n       SUBSTR(sql_text, 1, 120) AS sql_text\nFROM v$sql\nORDER BY elapsed_time DESC\nFETCH FIRST 20 ROWS ONLY;"}],"see_also":["high-logical-reads-queries","longest-running-queries-now","expensive-stored-procedures"],"faqs":[{"question":"Total time or mean time: which should I optimize first?","answer":"Total time first if the goal is less load on the server; mean time first if the goal is a specific slow page or report. A query near the top of both lists goes first either way. Check rows_per_call before you start: a query with a high mean that returns 100,000 rows per call may need a smaller result, not a better plan."},{"question":"Does pg_stat_statements slow the database down?","answer":"The overhead is small enough that most production systems, and most managed PostgreSQL services, run it permanently. It is a contrib module that ships with the standard PostgreSQL packages; enabling it needs the shared_preload_libraries entry and a restart. The cost that can show up is with many distinct statements: it keeps pg_stat_statements.max entries (5,000 by default) and evicts the least-used when full, so an application that generates unique SQL text churns that table."}]},"source_url":"https://sqlly.app/sql-snippets/top-queries-by-total-time","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/transitive-closure-recursive-cte","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Transitive closure with a recursive CTE","description":"Reach every node that is directly or indirectly linked from a starting node, with UNION to stop cycles.","body":{"slug":"transitive-closure-recursive-cte","name":"Transitive closure","h1":"Transitive closure with a recursive CTE","category":"querying","lede":"Seed, expand, and let UNION's deduplication be the termination proof.","engine_slug":"postgresql","problem":"From an edges(src, dst) table you want everything reachable from node 1, whether that takes one hop or ten.","sql":"WITH RECURSIVE reachable AS (\n  SELECT src, dst FROM edges WHERE src = 1\n  UNION\n  SELECT r.src, e.dst\n  FROM reachable r\n  JOIN edges e ON e.src = r.dst\n)\nSELECT DISTINCT dst\nFROM reachable\nWHERE dst <> 1\nORDER BY dst;","how_it_works":"The anchor selects the direct neighbours; the recursive step joins every frontier node to its own outgoing edges until no new rows appear. Using UNION rather than UNION ALL discards rows already produced, which both dedupes the closure and guarantees termination even if the graph has cycles. The statement runs as-is on PostgreSQL, MySQL 8 and SQLite. SQL Server and Oracle reject the RECURSIVE keyword and allow only UNION ALL in a recursive CTE, so there you need a depth cap (variant below) or Oracle's CYCLE clause to survive cycles.","variants":[{"sql":"WITH RECURSIVE reachable AS (\n  SELECT src, dst, 1 AS hops FROM edges WHERE src = 1\n  UNION\n  SELECT r.src, e.dst, r.hops + 1\n  FROM reachable r\n  JOIN edges e ON e.src = r.dst\n  WHERE r.hops < 20\n)\nSELECT dst, MIN(hops) AS shortest_hops\nFROM reachable\nWHERE dst <> 1\nGROUP BY dst\nORDER BY dst;"},{"sql":"WITH reachable (dst, depth) AS (\n  SELECT dst, 1 FROM edges WHERE src = 1\n  UNION ALL\n  SELECT e.dst, r.depth + 1\n  FROM reachable r\n  JOIN edges e ON e.src = r.dst\n  WHERE r.depth < 20\n)\nSELECT DISTINCT dst\nFROM reachable\nWHERE dst <> 1\nORDER BY dst;"}],"see_also":["org-chart-walk","bill-of-materials-walk","recursive-cte-cycle-guard"],"faqs":[{"question":"Why does UNION terminate on cyclic graphs?","answer":"Because a row is only fed back into the recursive step if it differs from every row already produced. Once every (src, dst) pair has been emitted, the recursion has nothing new and stops, unlike UNION ALL which would loop forever on a cycle. The hop-count variant breaks this: hops makes every lap of a cycle a new row, which is why it carries the WHERE r.hops < 20 cap."}]},"source_url":"https://sqlly.app/sql-snippets/transitive-closure-recursive-cte","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/trim-and-dedupe","corpus":"sql-snippets","engine":"all","language":"en","title":"Trim whitespace then remove duplicates","description":"A three-step recipe: preview padded rows, UPDATE the column with TRIM, then delete the duplicates the merge creates.","body":{"slug":"trim-and-dedupe","name":"Trim and dedupe","h1":"Trim whitespace then remove duplicates","category":"data-quality","lede":"Normalize whitespace with an UPDATE, then re-run the duplicate cleanup on the trimmed values, previewing and wrapping both steps in a transaction.","engine_slug":"all","problem":"Whitespace-padded emails hide duplicates. The fix is two moves: strip the padding, then collapse the duplicates it reveals, previewing each step before it runs.","sql":"-- Step 1: how many rows have padding?\nSELECT id, email FROM customers\nWHERE email <> TRIM(email);\n\n-- Open a transaction here: BEGIN / START TRANSACTION /\n-- BEGIN TRANSACTION depending on the engine (implicit on Oracle)\n\n-- Step 2: strip the padding\nUPDATE customers\nSET email = TRIM(email)\nWHERE email <> TRIM(email);\n\n-- Step 3: delete duplicates the trim revealed, keep lowest id\nDELETE FROM customers\nWHERE id IN (\n  SELECT id\n  FROM (\n    SELECT id,\n           ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn\n    FROM customers\n    WHERE email IS NOT NULL\n  ) ranked\n  WHERE rn > 1\n);\n-- check both row counts, then COMMIT or ROLLBACK","how_it_works":"Step 1 is the read-only preview; never skip it. Step 2 normalizes in place, only touching rows that actually change. Step 3 re-ranks by the now-clean email and deletes every copy except the first; the derived table keeps it legal on MySQL and Oracle (see delete-duplicates-keep-one). One transaction spans both writes so a bad surprise rolls back everything at once. On SQL Server, step 1 and step 2 only see leading spaces, because its comparisons ignore trailing ones; that is harmless, since trailing spaces never made two emails differ there in the first place.","variants":[{"sql":"UPDATE customers\nSET email = TRIM(email),\n    name = TRIM(name),\n    phone = TRIM(phone)\nWHERE email <> TRIM(email)\n   OR name <> TRIM(name)\n   OR phone <> TRIM(phone);"}],"see_also":["delete-duplicates-keep-one","trim-whitespace-duplicates"],"faqs":[{"question":"Why not trim and dedupe in one statement?","answer":"SQL has no single statement that both rewrites a value and deletes the rows that now collide with it. Running two statements also gives you a checkpoint: the UPDATE's row count should match the step 1 preview before you let the DELETE run. If a unique index already exists on email, the UPDATE itself fails on the first collision, so on such tables delete the padded copies first and trim the survivors afterwards."},{"question":"Does TRIM remove tabs and newlines too?","answer":"No: TRIM with no second argument strips spaces only on all five engines. Chain REPLACE calls with CHAR(9), CHAR(10) and CHAR(13) (CHR on PostgreSQL and Oracle) for the control characters, as the normalize-whitespace recipe does."}]},"source_url":"https://sqlly.app/sql-snippets/trim-and-dedupe","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/trim-whitespace-duplicates","corpus":"sql-snippets","engine":"all","language":"en","title":"Find duplicates hiding behind whitespace","description":"Group by TRIM(col) to expose values that differ only by leading or trailing spaces.","body":{"slug":"trim-whitespace-duplicates","name":"Whitespace duplicates","h1":"Find duplicates hiding behind whitespace","category":"data-quality","lede":"Trim the suspect column before grouping so 'a@x.com' and 'a@x.com ' land in the same group and reveal as duplicates.","engine_slug":"all","problem":"find-duplicates-on-a-key reports no duplicate emails, yet support swears customers are double. Leading or trailing spaces (often from copy-paste) can make identical values look distinct.","sql":"SELECT TRIM(email) AS cleaned_email, COUNT(*) AS occurrences,\n       MIN(email) AS stored_example\nFROM customers\nWHERE email IS NOT NULL\nGROUP BY TRIM(email)\nHAVING COUNT(*) > 1\nORDER BY occurrences DESC;","how_it_works":"TRIM strips leading and trailing spaces from each email before grouping, so values that differ only by whitespace collapse together. HAVING keeps the collapsed groups with more than one row; MIN(email) shows one raw example of how the values look in storage. TRIM needs SQL Server 2017 or later. SQL Server also compares strings as if the shorter one were padded with spaces, so 'a@x.com' = 'a@x.com ' is true there: trailing spaces never split a group, and email <> TRIM(email) only finds leading ones. Use DATALENGTH(email) <> DATALENGTH(TRIM(email)) to find trailing spaces on SQL Server.","variants":[{"sql":"SELECT COUNT(*) AS rows_with_padding\nFROM customers\nWHERE email IS NOT NULL\n  AND email <> TRIM(email);"},{"sql":"SELECT regexp_replace(email, '\\s+', '', 'g') AS squeezed, COUNT(*) AS occurrences\nFROM customers\nWHERE email IS NOT NULL\nGROUP BY 1\nHAVING COUNT(*) > 1;"}],"see_also":["trim-and-dedupe","find-duplicates-on-a-key","blank-strings-vs-nulls"],"faqs":[{"question":"Does TRIM remove tabs and newlines too?","answer":"No. Plain TRIM removes spaces only, so tab- and newline-padded values survive it. Most engines let you name the characters to strip: TRIM(BOTH CHR(9) FROM email) on PostgreSQL and Oracle, TRIM(CHAR(9) FROM email) on SQL Server 2017+, TRIM(BOTH CHAR(9) FROM email) on MySQL, trim(email, char(9) || ' ') on SQLite. The regexp variant or a nested REPLACE catches them anywhere in the string."},{"question":"Why does this report more duplicates than the plain check?","answer":"Because the groups are wider: ' a@x.io' and 'a@x.io' are two values to a bare GROUP BY but one after TRIM. Dedupe on the trimmed key, then pick which raw spelling survives the merge."}]},"source_url":"https://sqlly.app/sql-snippets/trim-whitespace-duplicates","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/truncate-all-tables-safe-order","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Truncate all tables in safe order","description":"Empty every table in a schema without tripping over foreign keys, using each engine's way around dependency order.","body":{"slug":"truncate-all-tables-safe-order","name":"Truncate all tables safely","h1":"Truncate all tables in safe order","category":"schema","lede":"Resetting a test database means emptying every table, and foreign keys make hand-written TRUNCATE lists fail halfway. This recipe handles the FK problem per engine.","engine_slug":"postgresql","problem":"One TRUNCATE against a referenced table aborts the whole cleanup, so emptying a schema means either dependency order or a per-engine trick that sidesteps it.","sql":"-- one statement, all tables: PostgreSQL checks FKs against the\n-- combined truncate and only requires CASCADE for outside references\nTRUNCATE TABLE\n    public.users,\n    public.orders,\n    public.order_items,\n    public.products\nRESTART IDENTITY CASCADE;","how_it_works":"PostgreSQL lets one TRUNCATE name many tables and validates foreign keys across the whole set at once, so parents and children truncate together and order does not matter. CASCADE extends the operation to tables that reference the listed ones from outside, and RESTART IDENTITY resets sequences. To avoid typing the list, the first variant builds the same single statement from information_schema inside a DO block.","variants":[{"sql":"DO $$\nDECLARE stmt text;\nBEGIN\n  SELECT 'TRUNCATE TABLE '\n         || string_agg(format('%I.%I', table_schema, table_name), ', ')\n         || ' RESTART IDENTITY CASCADE'\n    INTO stmt\n  FROM information_schema.tables\n  WHERE table_schema = 'public' AND table_type = 'BASE TABLE';\n  IF stmt IS NOT NULL THEN\n    EXECUTE stmt;\n  END IF;\nEND $$;"},{"sql":"-- TRUNCATE of a referenced table fails (error 1701) unless\n-- checks are off in the same session\nSET FOREIGN_KEY_CHECKS = 0;\nTRUNCATE TABLE order_items;\nTRUNCATE TABLE orders;\nTRUNCATE TABLE users;\nSET FOREIGN_KEY_CHECKS = 1;\n-- generate the list with\n-- SELECT CONCAT('TRUNCATE TABLE `', table_name, '`;')\n-- FROM information_schema.tables WHERE table_schema = 'mydb'\n-- AND table_type = 'BASE TABLE';"},{"sql":"-- TRUNCATE is refused on any table a foreign key references,\n-- even an empty one (error 4712). Disable the FKs and DELETE:\nEXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL';\nEXEC sp_MSforeachtable 'DELETE FROM ?';\nEXEC sp_MSforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL';\n-- sp_MSforeachtable is undocumented and covers every table in\n-- the database; DELETE does not reset IDENTITY (use DBCC CHECKIDENT)"}],"see_also":["generate-drop-table-statements","table-dependency-order","archive-old-rows-to-history"],"faqs":[{"question":"Why TRUNCATE instead of DELETE for resets?","answer":"TRUNCATE deallocates the table's storage instead of removing rows one at a time, so it takes about the same time for ten rows or ten million, and it skips ON DELETE triggers. It can be rolled back on PostgreSQL and SQL Server, but on MySQL it commits implicitly. DELETE is slower on big tables but fires delete triggers and works through foreign keys, so use it when you rely on those triggers."}]},"source_url":"https://sqlly.app/sql-snippets/truncate-all-tables-safe-order","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/truncate-word-boundary","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Truncate text on a word boundary in SQL","description":"Cut a blurb to 120 characters without slicing a word in half: 'first line of the...' not 'first line of the pr...'.","body":{"slug":"truncate-word-boundary","name":"Truncate on a word boundary","h1":"Truncate text on a word boundary in SQL","category":"text","lede":"List previews that cut mid-word look broken. Find the last full space before the limit and cut there.","engine_slug":"postgresql","problem":"A 120-character preview that ends 'the introduct' looks broken. Cut at the last space inside the first 120 characters instead.","sql":"SELECT CASE WHEN length(blurb) <= 120 THEN blurb\n            ELSE left(blurb, COALESCE(121 - NULLIF(strpos(reverse(left(blurb, 121)), ' '), 0), 120))\n       END AS preview\nFROM articles;","how_it_works":"Text that already fits comes back unchanged. Otherwise left(blurb, 121) takes one character past the limit, so a word that ends exactly at character 120 counts as complete; reverse flips it so strpos finds the last space, and the outer left cuts just before that space. When there is no space at all, NULLIF and COALESCE fall back to a hard cut at 120. Add a suffix with the ellipsize recipe if you want trailing dots.","variants":[{"sql":"SELECT CASE WHEN LEN(blurb) <= 120 THEN blurb\n            ELSE LEFT(blurb, COALESCE(121 - NULLIF(CHARINDEX(' ', REVERSE(LEFT(blurb, 121))), 0), 120))\n       END AS preview\nFROM articles;"}],"see_also":["ellipsize-long-text","normalize-whitespace"],"faqs":[{"question":"What if the text is shorter than the limit?","answer":"The CASE returns it unchanged. Without that guard, the shorter one-liner left(blurb, 120 - strpos(reverse(left(blurb, 120)), ' ')) cuts short text too: a 111-character string whose last space sits at position 11 comes back as 19 characters."},{"question":"Is the SQL Server variant safe for text with emoji?","answer":"No: REVERSE on SQL Server swaps UTF-16 code units, so a surrogate-pair emoji comes back scrambled and CHARINDEX then finds spaces at shifted positions. For text that can hold emoji, cut at the boundary in application code or on PostgreSQL, whose reverse() works on whole characters."}]},"source_url":"https://sqlly.app/sql-snippets/truncate-word-boundary","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/unpivot-columns-to-rows","corpus":"sql-snippets","engine":"all","language":"en","title":"Unpivot columns to rows","description":"Flip several total columns back into status/amount rows with UNION ALL, portable on every engine.","body":{"slug":"unpivot-columns-to-rows","name":"Unpivot columns to rows","h1":"Unpivot columns to rows","category":"querying","lede":"A SELECT per column, glued with UNION ALL, is the unpivot that works everywhere.","engine_slug":"all","problem":"A report table has one column per status. Before you can join it back to orders or chart it properly, you need one row per status again.","sql":"WITH pivoted AS (\n  SELECT customer_id,\n         SUM(CASE WHEN status = 'shipped'   THEN amount ELSE 0 END) AS shipped_total,\n         SUM(CASE WHEN status = 'pending'   THEN amount ELSE 0 END) AS pending_total,\n         SUM(CASE WHEN status = 'cancelled' THEN amount ELSE 0 END) AS cancelled_total\n  FROM orders\n  GROUP BY customer_id\n)\nSELECT customer_id, 'shipped'   AS status, shipped_total   AS amount FROM pivoted\nUNION ALL\nSELECT customer_id, 'pending'   AS status, pending_total   AS amount FROM pivoted\nUNION ALL\nSELECT customer_id, 'cancelled' AS status, cancelled_total AS amount FROM pivoted\nORDER BY customer_id, status;","how_it_works":"Each branch of the UNION ALL picks one column and labels it with a literal, producing the long format directly. UNION ALL (not UNION) keeps every row and skips a pointless deduplication pass. Columns are named in the first branch; the rest follow by position.","variants":[{"sql":"WITH pivoted AS (\n  SELECT customer_id,\n         SUM(CASE WHEN status = 'shipped'   THEN amount ELSE 0 END) AS shipped_total,\n         SUM(CASE WHEN status = 'pending'   THEN amount ELSE 0 END) AS pending_total,\n         SUM(CASE WHEN status = 'cancelled' THEN amount ELSE 0 END) AS cancelled_total\n  FROM orders\n  GROUP BY customer_id\n)\nSELECT customer_id, status, amount\nFROM pivoted\nUNPIVOT (amount FOR status IN\n         (shipped_total, pending_total, cancelled_total)) u\nORDER BY customer_id, status;"}],"see_also":["pivot-rows-to-columns-case","cross-tab-with-totals"],"faqs":[{"question":"Does UNPIVOT drop NULLs?","answer":"Yes, the UNPIVOT operator excludes rows where the value column is NULL, which changes the row count (Oracle keeps them with UNPIVOT INCLUDE NULLS). The UNION ALL form keeps them. Note also that UNPIVOT fills status with the column names, such as shipped_total (SHIPPED_TOTAL on Oracle), not the clean labels the UNION ALL branches write."}]},"source_url":"https://sqlly.app/sql-snippets/unpivot-columns-to-rows","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/unused-index-candidates","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find unused index candidates","description":"Indexes the engine's usage counters say have never been scanned, listed with their size so you know what dropping each one would reclaim.","body":{"slug":"unused-index-candidates","name":"Find unused indexes","h1":"Find unused index candidates","category":"schema","lede":"Every index slows writes and eats disk. The usage statistics track how often each index is scanned; zeroes mean the optimizer never touches it. This query lists them with their size.","engine_slug":"postgresql","problem":"Writes on a busy table lag and the index list keeps growing. Before adding another one, check the usage counters for indexes that have never earned their keep.","sql":"SELECT s.schemaname, s.relname AS table_name,\n       s.indexrelname AS index_name,\n       s.idx_scan AS scans,\n       pg_size_pretty(pg_relation_size(s.indexrelid)) AS size\nFROM pg_stat_user_indexes s\nJOIN pg_index i ON i.indexrelid = s.indexrelid\nWHERE s.idx_scan = 0\n  AND NOT i.indisunique   -- unique/PK indexes enforce rules even unscanned\nORDER BY pg_relation_size(s.indexrelid) DESC;","how_it_works":"pg_stat_user_indexes counts index scans since the statistics were last reset, so idx_scan = 0 means no query used the index in that window. The counters survive a clean restart but are wiped by crash recovery and by pg_stat_reset(), and each replica keeps its own, so an index that only serves read-replica queries looks unused on the primary. Dropping the biggest zeroes first reclaims the most space.","variants":[{"sql":"SELECT OBJECT_SCHEMA_NAME(i.object_id) AS schema_name,\n       OBJECT_NAME(i.object_id) AS table_name,\n       i.name AS index_name,\n       ISNULL(us.user_seeks + us.user_scans + us.user_lookups, 0) AS uses,\n       us.last_user_seek\nFROM sys.indexes i\nJOIN sys.tables t ON t.object_id = i.object_id\nLEFT JOIN sys.dm_db_index_usage_stats us\n  ON us.object_id = i.object_id AND us.index_id = i.index_id\n   AND us.database_id = DB_ID()\nWHERE i.index_id > 1 AND i.is_unique = 0\n  AND ISNULL(us.user_seeks + us.user_scans + us.user_lookups, 0) = 0;\n-- the DMV is cleared on every instance restart"},{"sql":"-- built on performance_schema, so counts start at the last\n-- server restart; it also lists indexes that back foreign keys\nSELECT object_schema, object_name, index_name\nFROM sys.schema_unused_indexes\nWHERE object_schema = 'mydb';"}],"see_also":["duplicate-index-candidates","list-table-indexes-columns","tables-without-any-index"],"faqs":[{"question":"Is a zero-scan index always safe to drop?","answer":"No. Unique and primary-key indexes enforce rules even when no query reads them, MySQL needs an index on every foreign key column, and an index that only serves a quarterly report reads as unused for most of the year. Collect stats over a full business cycle and check what each index backs before dropping it."}]},"source_url":"https://sqlly.app/sql-snippets/unused-index-candidates","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/unused-indexes","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find unused indexes in PostgreSQL","description":"Lists indexes with zero scans since the last statistics reset, skipping unique and constraint-backed ones, largest first so the biggest savings top the list.","body":{"slug":"unused-indexes","name":"Unused indexes","h1":"Find unused indexes in PostgreSQL","category":"indexes","lede":"Every index slows down every write to its table. This finds the ones PostgreSQL has not scanned once, sorted by the space they take.","engine_slug":"postgresql","problem":"Every INSERT, and every UPDATE that cannot be done as a HOT update, has to maintain every index on the table, and each index takes disk and shared_buffers. pg_stat_user_indexes counts how many times each index has been scanned. An index with idx_scan = 0 across a long, representative window is overhead you can remove, unless it enforces a constraint or serves a job that runs once a quarter.","sql":"SELECT s.schemaname, s.relname AS table_name, s.indexrelname AS index_name,\n       s.idx_scan, pg_size_pretty(pg_relation_size(s.indexrelid)) AS size,\n       s.idx_tup_read, s.idx_tup_fetch\nFROM pg_stat_user_indexes s\nJOIN pg_index i ON i.indexrelid = s.indexrelid\nWHERE s.idx_scan = 0\n  AND NOT i.indisunique\n  AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = s.indexrelid)\nORDER BY pg_relation_size(s.indexrelid) DESC;","how_it_works":"pg_stat_user_indexes has one row per index on a user table, and idx_scan counts the scans that used it since the last statistics reset. Joining pg_index drops unique indexes (primary keys are unique too), and the pg_constraint check drops indexes that back an exclusion constraint. Those enforce rules, so a zero scan count does not make them removable. Sorting by pg_relation_size puts the largest at the top. The counters reset after crash recovery or a pg_stat_reset call, so the result means something only with weeks of real traffic behind it.","variants":[{"sql":"SELECT format('DROP INDEX CONCURRENTLY %I.%I;', s.schemaname, s.indexrelname) AS drop_statement\nFROM pg_stat_user_indexes s\nJOIN pg_index i ON i.indexrelid = s.indexrelid\nWHERE s.idx_scan = 0 AND NOT i.indisunique\n  AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = s.indexrelid)\n  AND pg_relation_size(s.indexrelid) > 100 * 1024 * 1024\nORDER BY pg_relation_size(s.indexrelid) DESC;"}],"see_also":["never-scanned-indexes","duplicate-indexes","redundant-prefix-indexes"],"faqs":[{"question":"How long should I wait before trusting idx_scan = 0?","answer":"At least one full business cycle, which usually means several weeks including a month-end. Check stats_reset in pg_stat_database for your database to see when counting started. The counters are also per server: an index used only by queries on a read replica shows idx_scan = 0 on the primary, so run the query on every node before dropping anything. On PostgreSQL 16 and later, last_idx_scan shows when each index was last used."},{"question":"Is DROP INDEX CONCURRENTLY safe?","answer":"It is the safer form. A plain DROP INDEX takes an ACCESS EXCLUSIVE lock on the table, which blocks reads and writes while it waits for running queries to finish. CONCURRENTLY waits for conflicting transactions without blocking new ones. It cannot run inside a transaction block, so run each generated statement on its own."}]},"source_url":"https://sqlly.app/sql-snippets/unused-indexes","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/uppercase-first-letter","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Capitalize only the first letter of a value in SQL","description":"Turn 'london' into 'London' without touching the rest of the word, per engine.","body":{"slug":"uppercase-first-letter","name":"Capitalize the first letter","h1":"Capitalize only the first letter of a value in SQL","category":"text","lede":"City names, product codes and statuses stored lowercase need just one letter fixed.","engine_slug":"sql-server","problem":"When 'london' should read 'London', you only need the first character capitalized, leaving the rest of the word alone.","sql":"SELECT UPPER(LEFT(city, 1)) + LOWER(SUBSTRING(city, 2, LEN(city))) AS city_display\nFROM addresses;","how_it_works":"LEFT takes the first character, UPPER capitalizes it, and LOWER(SUBSTRING(...)) lowercases everything after position one. Concatenating the pieces gives 'london' -> 'London' and 'LONDON' -> 'London'. Drop the LOWER if the rest must stay as stored: with it, 'new York' becomes 'New york'. title-case-names extends this expression word by word across the whole name.","variants":[{"sql":"SELECT UPPER(LEFT(city, 1)) || LOWER(SUBSTRING(city FROM 2)) AS city_display\nFROM addresses;"},{"sql":"SELECT CONCAT(UPPER(LEFT(city, 1)), LOWER(SUBSTRING(city, 2))) AS city_display\nFROM addresses;"}],"see_also":["title-case-names"],"faqs":[{"question":"What about a NULL or empty string?","answer":"NULL in gives NULL out, because every function and the concatenation propagate NULL; wrap it in COALESCE if you need a default. An empty string comes back as an empty string on SQL Server, PostgreSQL and MySQL. Oracle treats '' as NULL anyway."}]},"source_url":"https://sqlly.app/sql-snippets/uppercase-first-letter","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/validate-email-shape","corpus":"sql-snippets","engine":"all","language":"en","title":"Validate email address shape","description":"A portable LIKE test for the minimum shape of an email: something, an @, something, a dot, something.","body":{"slug":"validate-email-shape","name":"Validate email shape","h1":"Validate email address shape","category":"data-quality","lede":"Use a coarse LIKE pattern to catch rows that are not even shaped like an email, and list them for correction.","engine_slug":"all","problem":"customers.email came from free-text input and a form bug once stored whole sentences. Full RFC validation is overkill; you just want rows that clearly are not emails.","sql":"SELECT id, email\nFROM customers\nWHERE email IS NOT NULL\n  AND (email NOT LIKE '%_@_%._%'\n       OR email LIKE '% %');","how_it_works":"The LIKE pattern '%_@_%._%' demands at least one character before an @, then at least one character, a dot, and at least one character after that dot, and NOT LIKE keeps the rows failing that. The second condition rejects embedded spaces, the most common free-text accident. It is a shape check, not an address-existence check. validate-phone-shape reuses this LIKE-with-exceptions playbook for phone columns.","variants":[{"sql":"SELECT id, email\nFROM customers\nWHERE email IS NOT NULL\n  AND email !~ '^[^@[:space:]]+@[^@[:space:]]+\\.[^@[:space:]]+$';"},{"sql":"SELECT id, email\nFROM customers\nWHERE email IS NOT NULL\n  AND (email NOT LIKE '%_@_%._%'\n       OR email LIKE '%@%@%'\n       OR email LIKE '% %');"}],"see_also":["case-insensitive-duplicate-emails","find-control-characters","validate-phone-shape"],"faqs":[{"question":"Why not validate with a full regex?","answer":"Email grammar (RFC 5322) is famously permissive (quoted local parts, comments, long TLDs), so strict regexes both explode in complexity and reject real addresses. For storage hygiene the coarse shape test catches the broken rows; deliverability is the mail server's problem, not the database's."},{"question":"Why is there no SQLite regex variant?","answer":"SQLite ships no pattern-matching functions beyond LIKE, so anything finer than this shape test has to run in application code or an extension. MySQL 8's REGEXP_LIKE and PostgreSQL's regexp use different engines too, so character classes are not portable between them."}]},"source_url":"https://sqlly.app/sql-snippets/validate-email-shape","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/validate-phone-shape","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Validate phone number shape","description":"A regex that allows the shapes a phone number legitimately takes and rejects everything else.","body":{"slug":"validate-phone-shape","name":"Validate phone shape","h1":"Validate phone number shape","category":"data-quality","lede":"Allow an optional leading plus, digits, spaces, parentheses and hyphens, with a sane minimum length, and list the violations.","engine_slug":"postgresql","problem":"customers.phone is free text and holds 'n/a', extension notes, and pasted addresses. A shape test isolates the rows that need normalizing before an SMS integration goes live.","sql":"SELECT id, phone\nFROM customers\nWHERE phone IS NOT NULL\n  AND phone !~ '^\\+?[0-9 ()-]{7,20}$'\nORDER BY id;","how_it_works":"The regex reads: optional leading plus, then 7 to 20 characters drawn from digits, space, parentheses and hyphen, and nothing else. !~ is PostgreSQL's 'does not match' operator, so the query returns the rows that fail. The window counts formatting characters too, which is why it is wider than E.164's 15-digit maximum; the digits-only variant checks the real digit count. validate-email-shape runs the same coarse-pattern sweep on email columns.","variants":[{"sql":"SELECT id, phone\nFROM customers\nWHERE phone IS NOT NULL\n  AND (phone NOT LIKE '%[0-9]%' OR phone LIKE '%[^0-9+() -]%');"},{"sql":"SELECT id, phone,\n       LENGTH(REGEXP_REPLACE(phone, '[^0-9]', '', 'g')) AS digit_count\nFROM customers\nWHERE phone IS NOT NULL\n  AND LENGTH(REGEXP_REPLACE(phone, '[^0-9]', '', 'g')) NOT BETWEEN 7 AND 15;"}],"see_also":["validate-email-shape","blank-strings-vs-nulls","trim-and-dedupe"],"faqs":[{"question":"Why not store phones as numbers?","answer":"A numeric column silently destroys leading zeros, cannot hold the + prefix, and blocks formatting characters that humans actually read. Store the raw string, validate its shape, and keep a normalized E.164 column alongside it when you need to dial or match."}]},"source_url":"https://sqlly.app/sql-snippets/validate-phone-shape","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/value-distribution-histogram","corpus":"sql-snippets","engine":"all","language":"en","title":"Build a value-distribution histogram","description":"Bucket numeric values into fixed-width bins with FLOOR and count rows per bin for a text-free histogram.","body":{"slug":"value-distribution-histogram","name":"Value histogram","h1":"Build a value-distribution histogram","category":"data-quality","lede":"Divide the value by the bin width, floor it to a bin number, and count rows per bin: a histogram in one GROUP BY.","engine_slug":"all","problem":"A raw MIN/MAX of orders.total says nothing about shape. Fixed-width buckets show whether totals cluster low, trail long, or have suspicious spikes at round numbers.","sql":"SELECT bucket * 50 AS bucket_start,\n       bucket * 50 + 50 AS bucket_end,\n       COUNT(*) AS order_count\nFROM (\n  SELECT FLOOR(total / 50.0) AS bucket\n  FROM orders\n  WHERE total IS NOT NULL\n) b\nGROUP BY bucket\nORDER BY bucket;","how_it_works":"FLOOR(total / 50.0) maps each total to its 50-wide bin number, and multiplying back gives the bin's edges: a bin covers bucket_start up to but not including bucket_end, so 49.99 lands in 0-50 and 50.00 in 50-100. Dividing by 50.0 rather than 50 matters on SQLite, SQL Server and PostgreSQL when the column is an integer: integer division truncates toward zero, which would put -5 in the 0 bin instead of -50. The bin number is computed in a derived table and grouped there, because MySQL's ONLY_FULL_GROUP_BY mode rejects SELECT FLOOR(total / 50) * 50 ... GROUP BY FLOOR(total / 50). Halve the width for finer grain, double it to zoom out.","variants":[{"sql":"WITH buckets AS (\n  SELECT total, NTILE(10) OVER (ORDER BY total) AS decile\n  FROM orders\n  WHERE total IS NOT NULL\n)\nSELECT decile,\n       MIN(total) AS lowest_in_bucket,\n       MAX(total) AS highest_in_bucket,\n       COUNT(*) AS order_count\nFROM buckets\nGROUP BY decile\nORDER BY decile;"}],"see_also":["bucketed-counts","dominant-value-frequency","percentile-outliers"],"faqs":[{"question":"Why does NULL disappear from the histogram?","answer":"It would not disappear on its own: FLOOR(NULL / 50.0) is NULL, and GROUP BY puts all NULLs into one extra bin with no edges, which charts badly. The WHERE total IS NOT NULL drops them on purpose. If the NULL count matters, report it separately with COUNT(*) - COUNT(total)."},{"question":"Can the buckets be equal-height instead of equal-width?","answer":"Not with arithmetic: FLOOR math gives equal-width bins, while equal-height buckets need NTILE(10) OVER (ORDER BY total), which requires window support (MySQL 8+, SQLite 3.25+). The ntile-deciles recipe is that form."}]},"source_url":"https://sqlly.app/sql-snippets/value-distribution-histogram","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/wait-events-summary","corpus":"sql-snippets","engine":"sql-server","language":"en","title":"Summarize wait types in SQL Server","description":"Ranks sys.dm_os_wait_stats by total wait time with idle background waits filtered out, to show what queries on the instance actually wait on.","body":{"slug":"wait-events-summary","name":"Wait events summary","h1":"Summarize wait types in SQL Server","category":"monitoring","lede":"What the instance's threads spend their time waiting for, ranked, once the idle background waits are removed.","engine_slug":"sql-server","problem":"sys.dm_os_wait_stats accumulates, since the last restart, every millisecond threads spent waiting for anything: locks, latches, I/O, network, memory grants. Most of the total belongs to background threads that wait by design, such as the lazy writer sleeping between passes or dispatchers waiting for work, so the filter matters more than the ranking. With those removed, the top few rows usually point at one class of pressure: I/O, locking, log writes, memory grants or CPU.","sql":"SELECT TOP 20\n    wait_type,\n    waiting_tasks_count,\n    CAST(wait_time_ms / 1000.0 AS DECIMAL(18,1)) AS wait_seconds,\n    CAST(100.0 * wait_time_ms / SUM(wait_time_ms) OVER () AS DECIMAL(5,1)) AS pct_of_all,\n    CAST(signal_wait_time_ms * 100.0 / NULLIF(wait_time_ms, 0) AS DECIMAL(5,1)) AS signal_pct\nFROM sys.dm_os_wait_stats\nWHERE wait_time_ms > 0\n  AND wait_type NOT LIKE 'SLEEP[_]%'\n  AND wait_type NOT LIKE 'QDS[_]%'\n  AND wait_type NOT LIKE 'HADR[_]%'\n  AND wait_type NOT LIKE 'PARALLEL[_]REDO%'\n  AND wait_type NOT LIKE 'BROKER[_]%'\n  AND wait_type NOT LIKE 'XE[_]%'\n  AND wait_type NOT IN (\n    'SOS_WORK_DISPATCHER', 'DISPATCHER_QUEUE_SEMAPHORE', 'LAZYWRITER_SLEEP',\n    'SQLTRACE_BUFFER_FLUSH', 'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', 'CHECKPOINT_QUEUE',\n    'LOGMGR_QUEUE', 'REQUEST_FOR_DEADLOCK_SEARCH', 'DIRTY_PAGE_POLL', 'ONDEMAND_TASK_QUEUE',\n    'PWAIT_EXTENSIBILITY_CLEANUP_TASK', 'PVS_PREALLOCATE', 'SP_SERVER_DIAGNOSTICS_SLEEP',\n    'FT_IFTS_SCHEDULER_IDLE_WAIT', 'CLR_AUTO_EVENT', 'CLR_MANUAL_EVENT', 'WAITFOR',\n    'KSOURCE_WAKEUP', 'CHKPT', 'SERVER_IDLE_CHECK', 'PREEMPTIVE_XE_DISPATCHER',\n    'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', 'TRACEWRITE'\n)\nORDER BY wait_time_ms DESC;","how_it_works":"wait_time_ms counts time waiting including the small signal portion (time ready to run but waiting for a CPU); a high signal_pct alongside big totals hints at CPU scheduler pressure rather than a resource wait. Dominant wait types map to causes: PAGEIOLATCH to buffer pool misses, LCK_M_ to lock contention, WRITELOG to transaction log latency, CXPACKET/CXCONSUMER to parallelism, RESOURCE_SEMAPHORE to memory grant queuing, PAGELATCH_ to hot-page contention. The DMV is cumulative since the instance started. To measure a specific period, copy it into a table, wait, and diff; DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR) also works but resets the numbers for everyone else watching the instance.","variants":[{"sql":"SELECT wait_event_type, wait_event, COUNT(*) AS sessions\nFROM pg_stat_activity\nWHERE wait_event IS NOT NULL\nGROUP BY wait_event_type, wait_event\nORDER BY sessions DESC;"},{"sql":"SELECT EVENT_NAME, COUNT_STAR,\n       ROUND(SUM_TIMER_WAIT / 1e12, 3) AS total_wait_sec,\n       ROUND(AVG_TIMER_WAIT / 1e9, 3) AS avg_wait_ms\nFROM performance_schema.events_waits_summary_global_by_event_name\nWHERE COUNT_STAR > 0\n  AND EVENT_NAME <> 'idle'\nORDER BY SUM_TIMER_WAIT DESC\nLIMIT 20;"}],"see_also":["deadlock-history","blocking-queries","cache-hit-ratio"],"faqs":[{"question":"I reset the waits and everything shows CXPACKET. Is parallelism bad?","answer":"Not by itself. CXPACKET means parallel plans are running and their threads are waiting on each other; since SQL Server 2016 SP2 and 2017 CU3, the harmless consumer-side part is reported separately as CXCONSUMER. It deserves attention when it dominates on an OLTP server whose queries should not need parallelism, often because bad estimates inflate their cost past cost threshold for parallelism (default 5, which most guidance says is too low). Find which queries go parallel before changing MAXDOP or the threshold."},{"question":"Why exclude those specific wait types from the ranking?","answer":"They belong to background threads that sleep or wait for work by design: the lazy writer, Query Store and Service Broker queues, Extended Events dispatchers, availability group workers. They accumulate time whether the server is busy or idle; on the instance used to test this page they were over 99 percent of all wait time. The list is not exhaustive and new versions add new idle waits, so if an unfamiliar wait with a SLEEP, QUEUE or DISPATCHER flavour tops your results, look it up before chasing it."}]},"source_url":"https://sqlly.app/sql-snippets/wait-events-summary","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/wal-redo-size","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Check WAL volume generated in PostgreSQL","description":"Reads pg_stat_wal for the WAL generated since the last stats reset, measures the pg_wal directory, and shows the SQL Server log-usage equivalent.","body":{"slug":"wal-redo-size","name":"WAL and redo size","h1":"Check WAL volume generated in PostgreSQL","category":"monitoring","lede":"How much WAL is the instance writing, and how much disk is the WAL directory holding? Two queries, two answers.","engine_slug":"postgresql","problem":"Every change PostgreSQL makes is written to WAL first, so WAL volume drives checkpoint frequency, replication traffic, archive storage and point-in-time-recovery restore time. pg_stat_wal (PostgreSQL 14 and later) counts WAL generated since its last reset. pg_ls_waldir() lists the files currently in pg_wal. The first measures the write rate; the second is the disk the directory holds, which grows when something prevents old segments from being removed.","sql":"SELECT wal_records, wal_fpi,\n       pg_size_pretty(wal_bytes) AS wal_generated,\n       wal_bytes, wal_buffers_full,\n       stats_reset\nFROM pg_stat_wal;","how_it_works":"wal_bytes is the WAL the instance has generated since stats_reset; sample it twice and divide by the interval for a rate in bytes per second. wal_fpi counts full-page images: the engine writes one for the first change to each page after a checkpoint, so a large share of them points at checkpoints that come too often (see the checkpoint-warnings recipe). wal_buffers_full counts the times the engine had to flush WAL because wal_buffers was full; a steadily rising value on a busy server suggests raising wal_buffers. pg_ls_waldir() needs superuser or the pg_monitor role. In normal operation pg_wal stays at or somewhat under max_wal_size; much more than that means the instance is retaining segments, the case the first FAQ covers. pg_stat_wal arrived in PostgreSQL 14, so on 13 and older the only instance-level gauge is the pg_current_wal_lsn() delta between two samples.","variants":[{"sql":"SELECT pg_size_pretty(SUM(size)) AS pg_wal_directory_size\nFROM pg_ls_waldir();"},{"sql":"SELECT RTRIM(instance_name) AS database_name,\n       CAST(cntr_value / 1024.0 AS DECIMAL(12,1)) AS log_used_mb\nFROM sys.dm_os_performance_counters\nWHERE object_name LIKE '%:Databases%'\n  AND counter_name = 'Log File(s) Used Size (KB)'\n  AND instance_name NOT IN ('_Total', 'mssqlsystemresource')\nORDER BY cntr_value DESC;"}],"see_also":["checkpoint-warnings","replication-lag","per-database-file-sizes"],"faqs":[{"question":"pg_wal holds 50 GB but pg_stat_wal says little was written. Why?","answer":"pg_stat_wal counts what was written; the directory holds whatever has not been removed yet. The usual causes: a replication slot whose consumer is gone or far behind (check active and restart_lsn in pg_replication_slots; max_slot_wal_keep_size caps how much a slot can hold), archiving that keeps failing (failed_count and last_failed_wal in pg_stat_archiver), or a large wal_keep_size. Once the slot advances or is dropped, or archiving succeeds, the next checkpoint removes or recycles the old segments."},{"question":"How does WAL volume relate to replication lag?","answer":"Directly: a standby must receive and replay every byte the primary writes. A burst that doubles the WAL rate needs twice the network bandwidth and replay speed while it lasts, and a sustained rate above what the standby can replay means lag grows without limit. Full-page images inflate the volume, which is one more reason to keep checkpoints spaced out."}]},"source_url":"https://sqlly.app/sql-snippets/wal-redo-size","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/weekly-buckets-ending-sunday","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Weekly buckets ending Sunday","description":"Bucket orders into weeks that end on Sunday by shifting each date forward to the coming Sunday.","body":{"slug":"weekly-buckets-ending-sunday","name":"Weekly buckets ending Sunday","h1":"Weekly buckets ending Sunday","category":"querying","lede":"date_trunc uses Monday starts; adding a DOW offset gives you Sunday-ending weeks.","engine_slug":"postgresql","problem":"Your reports label each Monday-to-Sunday week by the Sunday it ends on. date_trunc('week') groups the same weeks but labels each one with its Monday.","sql":"SELECT CAST(order_date AS date)\n         + (7 - EXTRACT(DOW FROM order_date)::int) % 7 AS week_ending_sunday,\n       COUNT(*) AS orders,\n       SUM(amount) AS revenue\nFROM orders\nGROUP BY 1\nORDER BY 1;","how_it_works":"EXTRACT(DOW) gives 0 for Sunday through 6 for Saturday in PostgreSQL. Subtracting it from 7 computes how many days remain until the next Sunday, and the modulo keeps a Sunday itself on the same day instead of jumping a week. The cast to date comes first because PostgreSQL can add an integer to a date but not to a timestamp. Group by the shifted date and each bucket is exactly one Monday-to-Sunday week.","variants":[{"sql":"SELECT DATE_TRUNC('week', order_date)::date AS week_starting_monday,\n       COUNT(*) AS orders\nFROM orders\nGROUP BY 1\nORDER BY 1;"},{"sql":"SELECT DATE_ADD(CAST(order_date AS date),\n                INTERVAL (8 - DAYOFWEEK(order_date)) % 7 DAY) AS week_ending_sunday,\n       COUNT(*) AS orders\nFROM orders\nGROUP BY 1\nORDER BY 1;"}],"see_also":["hourly-buckets","cumulative-total-by-month"],"faqs":[{"question":"Why do engines disagree on the week start?","answer":"ISO weeks start Monday, but US convention starts Sunday and MySQL's WEEKDAY/DAYOFWEEK functions disagree with each other. Computing the offset explicitly, as this recipe does, makes the convention visible instead of hidden in a function."}]},"source_url":"https://sqlly.app/sql-snippets/weekly-buckets-ending-sunday","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/weighted-sample","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Weighted random sample","description":"Give big orders a proportionally bigger chance of being picked using the exponential -LOG trick.","body":{"slug":"weighted-sample","name":"Weighted random sample","h1":"Weighted random sample","category":"querying","lede":"Sort by -LN(1 - RANDOM()) / weight: weighted sampling without replacement in one ORDER BY.","engine_slug":"postgresql","problem":"You want to sample orders where a 500-dollar order is ten times as likely to appear as a 50-dollar one, without duplicating rows by hand.","sql":"SELECT id, amount\nFROM orders\nORDER BY -LN(1 - RANDOM()) / amount\nLIMIT 10;","how_it_works":"Each row draws an exponential random variable with rate equal to its weight; sorting by that draw and taking the smallest values samples rows with probability proportional to weight. 1 - RANDOM() keeps the logarithm's argument strictly positive, because PostgreSQL's RANDOM() can return exactly 0 and LN(0) is an error. The weight must be greater than zero; filter out zero and NULL amounts first. The result is a weighted sample without replacement in one sort, no auxiliary tables.","variants":[{"sql":"WITH c AS (\n  SELECT id, amount,\n         SUM(amount) OVER (ORDER BY id) AS cum\n  FROM orders\n),\ntotal AS (\n  SELECT SUM(amount) AS grand FROM orders\n)\nSELECT c.id, c.amount\nFROM c CROSS JOIN total\nWHERE c.cum > RANDOM() * total.grand\nORDER BY c.cum\nLIMIT 1;"}],"see_also":["random-row","shuffled-sample"],"faqs":[{"question":"Does the weight have to be the amount column?","answer":"No, it can be any positive numeric expression, such as a count of purchases or a priority score. Weighted sampling only makes sense when the weights differ, otherwise it reduces to the plain shuffle."}]},"source_url":"https://sqlly.app/sql-snippets/weighted-sample","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/who-blocks-whom","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Show who blocks whom in PostgreSQL","description":"Uses pg_blocking_pids to pair every waiting query with the sessions blocking it, with both queries, the blocker's state and how long the waiter has run.","body":{"slug":"who-blocks-whom","name":"Who blocks whom","h1":"Show who blocks whom in PostgreSQL","category":"monitoring","lede":"PostgreSQL will tell you exactly which pids block a waiting session. This query turns that into one readable line per pair.","engine_slug":"postgresql","problem":"pg_blocking_pids(pid) returns every session whose locks the given pid is waiting for, including across lock queues, where a session can wait behind another waiter that itself waits on a third. Before it existed (PostgreSQL 9.6), answering the same question meant a long self-join of pg_locks that matched lock modes by hand.","sql":"SELECT blocked.pid AS blocked_pid,\n       blocked.usename AS blocked_user,\n       blocked.datname,\n       now() - blocked.query_start AS blocked_for,\n       LEFT(blocked.query, 100) AS blocked_query,\n       blocking.pid AS blocking_pid,\n       blocking.usename AS blocking_user,\n       blocking.state AS blocking_state,\n       LEFT(blocking.query, 100) AS blocking_query\nFROM pg_stat_activity blocked\nJOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS bp(pid) ON true\nJOIN pg_stat_activity blocking ON blocking.pid = bp.pid\nORDER BY blocked_for DESC;","how_it_works":"pg_blocking_pids returns an empty array for a session that is not waiting on a heavyweight lock, so the LATERAL unnest yields rows only for waiters, one per (blocked, blocking) pair. blocking_state shows whether the blocker is running a statement or sitting idle in transaction; the second is the classic forgotten-transaction case. blocked_for is measured from the start of the blocked statement, which is close to the lock wait time for a statement that blocked right away. A pid that appears as a blocker but never as blocked is the head of a chain and the one to deal with. Calling pg_blocking_pids often on a busy server has a cost, because it briefly locks the lock manager's shared state, so do not run this every second from a monitor.","variants":[{"sql":"SELECT r.session_id AS blocked_session,\n       r.blocking_session_id,\n       r.wait_time AS wait_ms,\n       LEFT(bt.text, 100) AS blocker_last_batch\nFROM sys.dm_exec_requests r\nLEFT JOIN sys.dm_exec_connections bc ON bc.session_id = r.blocking_session_id\nOUTER APPLY sys.dm_exec_sql_text(bc.most_recent_sql_handle) bt\nWHERE r.blocking_session_id > 0\nORDER BY r.wait_time DESC;"},{"sql":"SELECT * FROM sys.innodb_lock_waits\nORDER BY wait_age_secs DESC;"}],"see_also":["blocking-queries","idle-in-transaction","kill-query-safely"],"faqs":[{"question":"Can one query have several blockers?","answer":"Yes, which is why pg_blocking_pids returns an array. If three sessions hold ACCESS SHARE locks on a table (plain SELECTs) and a fourth asks for ACCESS EXCLUSIVE to run ALTER TABLE, the fourth is blocked by all three. Anyone who queues behind the ALTER is blocked by it too, even though their own lock would not conflict with the SELECTs. The LATERAL join produces one row per blocker."},{"question":"What is the difference between wait_event_type Lock and LWLock?","answer":"Lock is a heavyweight lock on a table, row, transaction id or similar object, normally held until the owning transaction ends; that is what pg_blocking_pids reports on. LWLock is an internal lightweight lock protecting shared memory structures, usually held for microseconds. Occasional LWLock waits are normal, while many sessions stuck on the same LWLock point to an internal bottleneck such as WAL insertion or buffer mapping, not to another transaction."}]},"source_url":"https://sqlly.app/sql-snippets/who-blocks-whom","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/widen-column-type","corpus":"sql-snippets","engine":"mysql","language":"en","title":"Widen a column type","description":"Grow varchar limits and change int to bigint on each engine, with notes on which widening is metadata-only and which rewrites the table.","body":{"slug":"widen-column-type","name":"Widen a column type","h1":"Widen a column type","category":"schema","lede":"The email fits in 50 characters until someone uses a 60-character address. Widening types is routine, but it is cheap on some engines and a full table rewrite on others.","engine_slug":"mysql","problem":"Inserts are starting to fail with data-too-long errors, so the column has to grow, and it helps to know what that will cost before running it on a production table.","sql":"ALTER TABLE products\n  MODIFY COLUMN name VARCHAR(255) NOT NULL;\n-- restating the whole definition is required, including NOT NULL","how_it_works":"MySQL requires MODIFY COLUMN to restate the complete column definition, so copy it from SHOW CREATE TABLE first, or a missing NOT NULL, DEFAULT or COMMENT is silently dropped. Growing a VARCHAR is in place only while the maximum byte length stays on the same side of 255, because that decides whether InnoDB stores a 1- or 2-byte length prefix. With utf8mb4 (4 bytes per character) VARCHAR(50) to VARCHAR(60) is in place, but VARCHAR(50) to VARCHAR(255) copies the whole table. int to bigint always copies it.","variants":[{"sql":"ALTER TABLE products\n  ALTER COLUMN name TYPE varchar(255);\n-- raising a varchar limit (or removing it) is catalog-only,\n-- but both statements fail while a view uses the column:\n-- drop and recreate the view around them.\n-- int -> bigint rewrites the table and its indexes under\n-- an ACCESS EXCLUSIVE lock:\nALTER TABLE products\n  ALTER COLUMN id TYPE bigint;"},{"sql":"ALTER TABLE dbo.Products\n    ALTER COLUMN Name NVARCHAR(255) NOT NULL;\n-- a longer varchar/nvarchar is metadata-only, even on an indexed\n-- column. int -> bigint updates every row, and indexes or\n-- constraints on the column must be dropped first"},{"sql":"-- SQLite is loosely typed and ignores VARCHAR length limits,\n-- so widening is usually unnecessary; if you must:\n-- rebuild the table (new table, copy, drop, rename)"}],"see_also":["find-columns-by-type","make-column-not-null-safely","change-column-nullable"],"faqs":[{"question":"Should I just use TEXT/NVARCHAR(MAX) everywhere to avoid this?","answer":"On PostgreSQL that is reasonable: varchar(n) and text are stored the same way, and the limit only acts as a check. On SQL Server, NVARCHAR(MAX) columns cannot be index key columns and inflate the memory grants the optimizer requests for sorts, and on MySQL a TEXT column accepts no literal default (only an expression default such as DEFAULT (''), from 8.0.13) and cannot be indexed without a prefix length. On those engines keep bounded lengths and widen when needed."},{"question":"Is widening always metadata-only on PostgreSQL?","answer":"Only within the same type: varchar(50) to varchar(60) updates the catalog, while int to bigint rewrites the whole table, as it does on MySQL and SQL Server too. Compare pg_class.relfilenode before and after if you want proof of which kind you ran."}]},"source_url":"https://sqlly.app/sql-snippets/widen-column-type","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/window-and-groupby-mix","corpus":"sql-snippets","engine":"all","language":"en","title":"Mix window functions with GROUP BY","description":"Aggregate in a CTE, then apply ranking and share-of-total windows over the grouped rows.","body":{"slug":"window-and-groupby-mix","name":"Mix window functions with GROUP BY","h1":"Mix window functions with GROUP BY","category":"querying","lede":"Windows run after GROUP BY; a CTE makes the order explicit and the query readable.","engine_slug":"all","problem":"You want regional revenue totals, each region's percent of all revenue, and a rank by size, all in one result.","sql":"WITH region_totals AS (\n  SELECT c.region, SUM(o.amount) AS total\n  FROM orders o\n  JOIN customers c ON c.id = o.customer_id\n  GROUP BY c.region\n)\nSELECT region, total,\n       ROUND(100.0 * total / SUM(total) OVER (), 1) AS pct_of_all,\n       RANK() OVER (ORDER BY total DESC) AS rank_by_size\nFROM region_totals\nORDER BY total DESC;","how_it_works":"The CTE does the grouping first and hands the window functions a small, already-aggregated row set. The windows then compute across those rows: SUM(total) OVER () is the grand total, RANK orders the regions. You can nest aggregates directly inside windows (SUM(SUM(x)) OVER ...) without a CTE, but the two-step version is easier to read and to debug.","variants":[{"sql":"SELECT c.region,\n       SUM(o.amount) AS total,\n       ROUND(100.0 * SUM(o.amount)\n             / SUM(SUM(o.amount)) OVER (), 1) AS pct_of_all,\n       RANK() OVER (ORDER BY SUM(o.amount) DESC) AS rank_by_size\nFROM orders o\nJOIN customers c ON c.id = o.customer_id\nGROUP BY c.region\nORDER BY total DESC;"}],"see_also":["percentage-of-total","share-of-parent","rank-within-category"],"faqs":[{"question":"Why can't I write RANK() over a raw column next to GROUP BY?","answer":"Because window functions evaluate after grouping, and any column they reference must either be in the GROUP BY or wrapped in an aggregate. SUM(SUM(x)) OVER (...) is legal; RANK() OVER (ORDER BY x) where x is neither grouped nor aggregated is not."}]},"source_url":"https://sqlly.app/sql-snippets/window-and-groupby-mix","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/year-over-year-same-day","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Compare to the same day last year","description":"Join this year's daily totals to last year's by shifting the date exactly one year back.","body":{"slug":"year-over-year-same-day","name":"Same day last year","h1":"Compare to the same day last year","category":"querying","lede":"A self-join on order_date minus one year puts the two years side by side.","engine_slug":"postgresql","problem":"You want this year's daily revenue next to the same calendar day of last year, so you can spot real seasonality instead of week-to-week noise.","sql":"WITH daily AS (\n  SELECT CAST(order_date AS date) AS day, SUM(amount) AS total\n  FROM orders\n  GROUP BY 1\n)\nSELECT d.day, d.total, y.total AS total_last_year,\n       d.total - y.total AS change\nFROM daily d\nLEFT JOIN daily y\n       ON y.day = d.day - INTERVAL '1 year'\nWHERE d.day >= DATE '2026-01-01'\nORDER BY d.day;","how_it_works":"The CTE computes one total per day. Joining it to itself on day minus one year pairs each day with its counterpart from a year earlier; the LEFT JOIN keeps days that had no sales last year, which come back with NULL. The interval syntax is PostgreSQL; SQL Server uses DATEADD(year, -1, d.day) and MySQL uses DATE_SUB(d.day, INTERVAL 1 YEAR).","variants":[{"sql":"WITH daily AS (\n  SELECT CAST(order_date AS date) AS day, SUM(amount) AS total\n  FROM orders\n  GROUP BY CAST(order_date AS date)\n)\nSELECT d.day, d.total, y.total AS total_last_year\nFROM daily d\nLEFT JOIN daily y\n       ON y.day = DATEADD(year, -1, d.day)\nWHERE d.day >= '2026-01-01'\nORDER BY d.day;"},{"sql":"WITH daily AS (\n  SELECT CAST(order_date AS date) AS day, SUM(amount) AS total\n  FROM orders\n  GROUP BY 1\n)\nSELECT d.day, d.total, y.total AS total_same_weekday\nFROM daily d\nLEFT JOIN daily y\n       ON y.day = d.day - INTERVAL '364 days'\nWHERE d.day >= DATE '2026-01-01'\nORDER BY d.day;"}],"see_also":["month-over-month-delta","lag-compare-within-group"],"faqs":[{"question":"What about February 29?","answer":"Both PostgreSQL (d.day - INTERVAL '1 year') and SQL Server (DATEADD(year, -1, ...)) clamp 2028-02-29 to 2027-02-28, so February 28 of last year is matched twice, once by the 28th and once by the 29th. If that double-counts in a summed report, exclude the leap day or map it to NULL explicitly."}]},"source_url":"https://sqlly.app/sql-snippets/year-over-year-same-day","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
{"id":"sql-snippets/z-score-outliers","corpus":"sql-snippets","engine":"postgresql","language":"en","title":"Find outliers with z-scores","description":"Flag rows more than 3 standard deviations from the mean using AVG and STDDEV.","body":{"slug":"z-score-outliers","name":"Z-score outliers","h1":"Find outliers with z-scores","category":"data-quality","lede":"Compute the mean and standard deviation once, then score every row by its distance from the mean in standard deviations.","engine_slug":"postgresql","problem":"Percentile outliers show the tails; z-scores quantify how abnormal each tail value is. Anything beyond three standard deviations from the mean total is worth an audit.","sql":"WITH stats AS (\n  SELECT AVG(total) AS mean_total,\n         STDDEV(total) AS sd_total\n  FROM orders\n)\nSELECT o.id, o.total,\n       (o.total - s.mean_total) / s.sd_total AS z_score\nFROM orders o\nCROSS JOIN stats s\nWHERE s.sd_total > 0\n  AND ABS(o.total - s.mean_total) / s.sd_total > 3\nORDER BY z_score DESC;","how_it_works":"The stats CTE computes the mean and standard deviation over all orders in one pass. CROSS JOIN attaches them to every row, the z-score divides each row's distance from the mean by the deviation, and the WHERE keeps only |z| beyond 3. The sd > 0 guard prevents division by zero on constant columns. The same statement runs on MySQL and Oracle, but STDDEV means different things: PostgreSQL and Oracle return the sample deviation, MySQL the population one. Write STDDEV_SAMP or STDDEV_POP to pin it down. SQL Server spells it STDEV (first variant); SQLite has no standard-deviation function, so compute SQRT(AVG(total * total) - AVG(total) * AVG(total)) yourself.","variants":[{"sql":"WITH stats AS (\n  SELECT AVG(total) AS mean_total, STDEV(total) AS sd_total\n  FROM orders\n)\nSELECT o.id, o.total,\n       (o.total - s.mean_total) / s.sd_total AS z_score\nFROM orders o CROSS JOIN stats s\nWHERE s.sd_total > 0\n  AND ABS(o.total - s.mean_total) / s.sd_total > 3;"},{"sql":"WITH stats AS (\n  SELECT AVG(total) AS mean_total, STDDEV(total) AS sd_total\n  FROM orders\n)\nSELECT o.id, o.total\nFROM orders o CROSS JOIN stats s\nWHERE s.sd_total > 0\n  AND ABS(o.total - s.mean_total) / s.sd_total > 2;"}],"see_also":["percentile-outliers","impossible-dates"],"faqs":[{"question":"When do z-scores mislead?","answer":"When the distribution is heavily skewed, the mean and standard deviation are dragged by the very outliers you are hunting, so mild extremes get missed and wild ones look milder than they are. Skewed money columns are better screened with percentiles; z-scores shine on roughly symmetric data."}]},"source_url":"https://sqlly.app/sql-snippets/z-score-outliers","license":"CC-BY-4.0","code_license":"MIT","last_modified":"2026-11-30"}
