SQL snippets library
250 recipes for everyday database work: find the duplicate rows, see who is blocking whom, generate the DDL for the indexes you are missing. Each one gives you a statement you can run, a plain-language walkthrough and the variations people ask for next.
Data quality
Duplicates, orphans, gaps and the rows that break the rules. 50 recipes
-
Find duplicate rows across all columns
Spot exact duplicate rows in a table with no primary key, using GROUP BY and HAVING over every column.
All engines -
Find duplicates on a key column
List every repeated value in a key column with its occurrence count, worst first.
All engines -
Delete duplicates keeping one row
Remove duplicate rows with DELETE plus ROW_NUMBER, keeping one row per key. Always SELECT the doomed rows first.
All engines -
Find rows orphaned from their parent
Find child rows whose parent id no longer matches any row in the parent table, with a LEFT JOIN anti-join.
All engines -
Find missing parent references, both ways
One query that lists children with no usable parent and parents that nothing points at, labeled per side.
All engines -
Find rows violating a business rule
Encode each business rule as a predicate and list, or count, every row that breaks one.
All engines -
Count NULLs per column (NULL skew)
One-row-per-table NULL audit: SUM(CASE WHEN col IS NULL) per column reveals skew at a glance.
All engines -
Profile a column: min, max, distinct
A one-query column profile: row count, min, max, average and distinct values for the columns that matter.
All engines -
Detect gaps in an id sequence
Find gaps between consecutive ids with LEAD: each row reports the next id and how many are missing.
All engines -
List missing values in an id sequence
Generate every id between MIN and MAX and keep the ones the table does not have.
PostgreSQL +1 engine -
Detect missing days in date data
Generate every day between the first and last date and report the days with no rows: the gaps in time-series data.
PostgreSQL +2 engines -
Detect overlapping date ranges
Self-join a range table on the classic overlap condition to find subscriptions or bookings that collide.
All engines -
Audit all foreign keys in both directions
One labeled result set counting orphans per foreign-key relationship across the whole schema.
All engines -
Find rows that differ between two tables
Symmetric difference of two tables with UNION ALL plus GROUP BY: rows in one table only, either direction.
All engines -
Compare row counts across tables
Stack COUNT(*) per table with UNION ALL for a one-query census, or a before/after migration diff.
All engines -
Compute a checksum over a table
Hash every row's concatenated values and aggregate the hashes into one checksum per table.
PostgreSQL +1 engine -
Find rows changed since yesterday
Use an updated_at timestamp to list everything modified in the last 24 hours, newest first.
PostgreSQL +2 engines -
Report on last-modified staleness
Bucket rows by how long ago they were touched: never updated, over a year, over 90 days, recent.
PostgreSQL +1 engine -
Find blank strings mixed with NULLs
Count NULL, empty and whitespace-only values per column to expose the mixed-blank anti-pattern.
All engines -
Find duplicates hiding behind whitespace
Group by TRIM(col) to expose values that differ only by leading or trailing spaces.
All engines -
Find duplicate emails ignoring case
Group by LOWER(col) so [email protected] and [email protected] count as one, and list the stored variants.
PostgreSQL +1 engine -
Trim whitespace then remove duplicates
A three-step recipe: preview padded rows, UPDATE the column with TRIM, then delete the duplicates the merge creates.
All engines -
Find values truncated at the max length
Flag strings sitting exactly at the column's max length, the signature of silent truncation.
PostgreSQL +1 engine -
Find outliers with percentiles
Use NTILE to bucket ordered values and inspect the extreme tiles, or percentile_cont for a true percentile cut.
All engines -
Find outliers with z-scores
Flag rows more than 3 standard deviations from the mean using AVG and STDDEV.
PostgreSQL +1 engine -
Validate impossible dates
Catch future dates, pre-epoch junk, and impossible orderings such as shipping before ordering.
PostgreSQL +2 engines -
Validate email address shape
A portable LIKE test for the minimum shape of an email: something, an @, something, a dot, something.
All engines -
Validate phone number shape
A regex that allows the shapes a phone number legitimately takes and rejects everything else.
PostgreSQL +1 engine -
Find candidate key columns
Measure distinct-value counts per column against the row count: a full match marks a candidate key.
All engines -
Distribution of foreign-key values
Join the child table to its parent and rank by row count to see skew and spot hot parents.
PostgreSQL +1 engine -
Dominant-value frequency table
Count each value, compute its share of the table with a window sum, and rank the most common values.
All engines -
Build a value-distribution histogram
Bucket numeric values into fixed-width bins with FLOOR and count rows per bin for a text-free histogram.
All engines -
Count rows bucketed by time period
Extract year and month (or week) from a date and GROUP BY it for row counts per period.
PostgreSQL +1 engine -
Compute per-column fill rate
COUNT(col) over COUNT(*) per column gives the share of populated values, all columns in one row.
All engines -
Duplicate natural keys with different ids
Composite natural keys duplicated across different surrogate ids: the merge-candidate list.
All engines -
Find conflicting facts across tables
Join tables that should agree (order vs invoice total) and list every pair that disagrees.
All engines -
Orphan sweep across multiple parents
Check every foreign key of one child table in a single UNION ALL and list the exact missing values.
All engines -
Preview what a delete would cascade
Before deleting a parent, count the children and grandchildren a cascading delete would remove.
All engines -
Audit soft-deleted rows
Count live vs soft-deleted rows and catch rows touched after their deletion timestamp.
All engines -
List soft-deleted rows that can be restored
Rows with a deleted_at still inside the retention window: the undo list for soft deletes.
PostgreSQL +1 engine -
Preview rows failing a CHECK constraint
SELECT the rows a planned CHECK constraint would reject. Run it before the ALTER TABLE.
All engines -
Preview a migration diff between tables
Before cutover, list rows present in only one of old and new, plus rows whose values changed.
All engines -
Preview an id remap before running it
Join a staging old-to-new id map against the child table and list every foreign key the remap would rewrite.
All engines -
Dedupe with window functions
Rank rows per key with ROW_NUMBER and keep rn = 1, the standard window-function dedupe pattern.
All engines -
Keep the newest row per key
ROW_NUMBER ordered by updated_at DESC keeps the latest row per key: the latest-state view.
All engines -
Keep the oldest row per key
ROW_NUMBER ordered by created_at ASC keeps the original row per key: the first-ever-state view.
All engines -
Merge duplicate rows by re-parenting children
Move the children of duplicate parents onto the surviving parent, folding lines that would collide into one, then retire the duplicates.
PostgreSQL -
Anonymize email addresses in SQL
Replace real addresses with a deterministic placeholder built from the row id, inside a transaction.
PostgreSQL +2 engines -
Mask names in query results
Keep the first letter and asterisk out the rest at SELECT time, masking without touching stored data.
PostgreSQL +1 engine -
Find rows containing control characters
A regex over ASCII control ranges catches tabs, newlines and invisible characters hiding in text columns.
PostgreSQL +1 engine
Querying
Everyday SELECT work: ranking, diffing, paging and top-n per group. 54 recipes
-
Top-N rows per group
Get the three most recent orders per customer with ROW_NUMBER instead of a correlated subquery per row.
All engines -
Top-N with ties per group
Keep every product tied at the top of its category with RANK, so equal prices are never silently dropped.
All engines -
Second-highest value
Find the second-highest order amount overall or per customer, with duplicates handled correctly.
All engines -
累計
Add a cumulative sum of order amounts with the SUM window function, ordered row by row.
All engines -
Running count
Count how many orders have happened so far, next to every row, with a windowed COUNT.
All engines -
Moving average
Smooth a series with a trailing 7-row average using a window frame, no self-joins.
All engines -
Cumulative total by month
Aggregate orders per month, then grow a running sum across the months with one window function.
PostgreSQL +1 engine -
Month-over-month delta
Compare each month's revenue to the previous month with LAG, including a percentage change.
PostgreSQL -
Compare to the same day last year
Join this year's daily totals to last year's by shifting the date exactly one year back.
PostgreSQL +1 engine -
Rank rows within a category
Give every product a rank inside its own category with PARTITION BY, and size each group in the same pass.
All engines -
Pivot rows to columns with CASE
Turn one row per order status into one row per customer with a column per status, using plain CASE expressions.
All engines -
Unpivot columns to rows
Flip several total columns back into status/amount rows with UNION ALL, portable on every engine.
All engines -
Cross-tab with row and column totals
A status-by-customer matrix whose ROLLUP row carries the column totals, with NULL rows labelled 'All'.
PostgreSQL +2 engines -
Latest row per customer
Fetch each customer's most recent order with all its columns, using ROW_NUMBER or DISTINCT ON.
All engines -
Earliest row per key
Get each customer's first order with ROW_NUMBER over an ascending sort, or a NOT EXISTS anti-join.
All engines -
First and last value in a partition
Carry each customer's first and last order amount onto every row with FIRST_VALUE and LAST_VALUE.
All engines -
Fill gaps with a calendar spine
LEFT JOIN daily totals onto generate_series dates so empty days show as zero instead of vanishing.
PostgreSQL +2 engines -
Group rows into hourly buckets
Truncate order timestamps to the hour and count or sum per bucket for time-of-day analysis.
PostgreSQL +3 engines -
Weekly buckets ending Sunday
Bucket orders into weeks that end on Sunday by shifting each date forward to the coming Sunday.
PostgreSQL +1 engine -
Consume a FIFO queue
Claim the oldest pending jobs safely with ORDER BY, LIMIT and FOR UPDATE SKIP LOCKED.
PostgreSQL +2 engines -
Reserve the next job id
Insert the job and read back its generated id in one statement with RETURNING.
PostgreSQL +2 engines -
Keyset (seek) pagination
Fetch the next page by remembering the last row seen, with a WHERE clause instead of OFFSET.
PostgreSQL +4 engines -
Offset pagination pitfalls
Why LIMIT OFFSET gets slower with every page and can duplicate or skip rows while you browse.
PostgreSQL -
Pick a random row
Sort by a random value and take the first row, with the per-engine functions and a faster big-table option.
PostgreSQL +2 engines -
Shuffled sample of rows
Take N rows in random order with ORDER BY RANDOM() and LIMIT, and know when to use TABLESAMPLE instead.
PostgreSQL -
Weighted random sample
Give big orders a proportionally bigger chance of being picked using the exponential -LOG trick.
PostgreSQL -
Deduplicate SELECT output
Collapse repeated rows with DISTINCT, or keep one whole row per business key with ROW_NUMBER.
All engines -
Rows common to two queries (INTERSECT)
Find the values both result sets share with INTERSECT, which deduplicates automatically.
All engines -
Rows in one query but not another (EXCEPT)
Use EXCEPT to find values present in the first result set and absent from the second.
All engines -
Full outer compare of two result sets
FULL OUTER JOIN two result sets on the key and surface rows that exist on only one side.
PostgreSQL +1 engine -
Self-join pairs (and mutual pairs)
Join a table to itself to pair rows, with a.id < b.id to keep each pair once and skip self-pairs.
All engines -
Transitive closure with a recursive CTE
Reach every node that is directly or indirectly linked from a starting node, with UNION to stop cycles.
PostgreSQL +2 engines -
Walk an org chart
List a manager's whole subtree with a recursive CTE, one row per employee with a depth column.
PostgreSQL +2 engines -
Walk a bill of materials
Explode an assembly into all its parts, multiplying quantities along the way, with a recursive CTE.
PostgreSQL +2 engines -
Stop infinite loops in recursive CTEs
Carry a visited-ids array through a recursive CTE and refuse to revisit a node, so cycles cannot loop forever.
PostgreSQL +2 engines -
Aggregate rows into JSON
Build one JSON array of order objects per customer with JSON_AGG and JSON_BUILD_OBJECT.
PostgreSQL +2 engines -
Aggregate children into one row per parent
LEFT JOIN plus GROUP BY gives every customer a row with their order count and total, including zeros.
All engines -
Conditional counts (COUNT IF)
Count only the rows matching a condition inside a grouped query, with CASE so one scan answers many questions.
All engines -
Conditional sums (SUM IF)
Sum a column only for the rows that match each condition, several conditions per query, one table scan.
All engines -
Distinct counts per group
COUNT(DISTINCT ...) inside a GROUP BY answers how many different values each group has.
PostgreSQL -
Percentage of total
Show each customer's share of grand total revenue with a window over the grouped sum.
All engines -
Share of parent
Give each product its percent share of its own category's revenue with a partitioned window over aggregates.
All engines -
Median per group
Compute the median order amount per customer portably with ROW_NUMBER and COUNT, no PERCENTILE_CONT needed.
All engines -
Percentile buckets
Label each order low/medium/high/top by comparing it to the 25th, 50th and 75th percentiles of all amounts.
PostgreSQL -
Deciles with NTILE
Split orders into ten equal-size buckets by amount with NTILE, and grab the top decile in one more step.
All engines -
Lag compare within a group
Show each order next to the previous one for the same customer, plus the change since the customer's first order.
All engines -
Exists flag in SELECT
Add a 1/0 column per row saying whether a related row exists, without a join or a GROUP BY.
All engines -
Rank by several conditions
Build a priority from a CASE ladder over status, then order the queue by it in a window function.
All engines -
Stable ordering with tiebreaks
Add a unique final column to every ORDER BY so equal rows keep one order across runs, pages and window functions.
All engines -
Mix window functions with GROUP BY
Aggregate in a CTE, then apply ranking and share-of-total windows over the grouped rows.
All engines -
Bucket timestamps into 5-minute windows in SQL
Group event timestamps into fixed 5-minute buckets for time-series charts and rollups.
PostgreSQL +2 engines -
Check whether two date ranges overlap in SQL
Detect booking conflicts with the two-comparison overlap test, or the && range operator on PostgreSQL.
All engines -
Find rows expiring within N days in SQL
Label subscriptions and certificates as expired, expiring in the next 30 days, active or never-expiring in one CASE.
PostgreSQL +2 engines -
Round timestamps to the nearest minute or hour in SQL
Truncate timestamps to clean boundaries, or round to the nearest minute or hour, with per-engine one-liners.
PostgreSQL +2 engines
Text & dates
Cleaning strings and doing arithmetic on dates and times. 45 recipes
-
Normalize whitespace in SQL
Collapse runs of spaces into one and trim the ends, with a portable triple-REPLACE trick that runs on every engine.
All engines -
Remove all whitespace from a string in SQL
Strip every space, tab and line break out of a value such as a phone number or account code.
All engines -
Remove non-printable and control characters in SQL
Delete control characters and other unprintable bytes that ride along with pasted or imported text.
PostgreSQL +2 engines -
Strip diacritics and accents in SQL
Turn 'José' into 'Jose'. What each engine can do, and where it falls short.
PostgreSQL +2 engines -
Title-case names in SQL (INITCAP and friends)
Capitalize the first letter of each word in a name, the way INITCAP does on PostgreSQL and Oracle.
PostgreSQL +2 engines -
Capitalize only the first letter of a value in SQL
Turn 'london' into 'London' without touching the rest of the word, per engine.
SQL Server +2 engines -
Pad numbers with leading zeros in SQL
Render 7 as 00000007 for account numbers, invoice keys and fixed-width exports.
PostgreSQL +3 engines -
Format money and currency values as strings in SQL
Render 1234.5 as '$1,234.50' with the engine's own currency formatting functions.
SQL Server +3 engines -
Split a full name into first and last name in SQL
Pull 'Ann' and 'Smith' out of 'Ann Smith' with string splitting instead of two manual substring calls.
PostgreSQL +2 engines -
Split a comma-separated field into rows in SQL
Turn one row with 'a,b,c' into three rows, one per value, with STRING_SPLIT or a set-returning function.
SQL Server +2 engines -
Join child rows into a comma-separated list in SQL
Aggregate many child rows into one 'ORD-1, ORD-2, ORD-3' string per parent with STRING_AGG and its cousins.
PostgreSQL +3 engines -
Safely convert strings to numbers in SQL
Convert '12.5' to a decimal without the whole query dying on 'N/A', using TRY_CAST or a validation check.
SQL Server +2 engines -
Safely convert strings to dates in SQL
Convert text like '2026-03-01' to a real date while sending garbage to NULL instead of an error.
SQL Server +2 engines -
Extract the domain from an email address in SQL
Get 'example.com' out of '[email protected]' and group by it to find free-mail vs company accounts.
PostgreSQL +2 engines -
Mask payment card numbers in SQL (show last 4)
Display '************4242' by hiding everything except the last four digits of a card or account number.
PostgreSQL +3 engines -
Mask an email address in SQL for display
Turn '[email protected]' into 'j***@example.com' so support staff see the shape without the address.
PostgreSQL +2 engines -
Compute MD5 or SHA-256 hashes of values in SQL
Produce hex digests like dedupe keys or fingerprint tokens with each engine's hash functions.
MySQL +3 engines -
Truncate text on a word boundary in SQL
Cut a blurb to 120 characters without slicing a word in half: 'first line of the...' not 'first line of the pr...'.
PostgreSQL +1 engine -
Ellipsize long text with a trailing ellipsis in SQL
Shorten to a hard cap and append '...' only when the text was actually cut.
SQL Server +2 engines -
Count how many times a substring appears in SQL
Count 'error' hits in a log line with the length-difference trick, portable across engines.
PostgreSQL +1 engine -
Find the position of the nth occurrence of a substring in SQL
Locate the third comma or second hyphen with INSTR and REGEXP_INSTR instead of nested CHARINDEX calls.
Oracle +2 engines -
Replace multiple patterns in one SQL expression
Clean '(555) 010-0111' to '5550100111' by nesting REPLACE, or use TRANSLATE for single-character maps.
All engines -
Remove emojis and symbol characters in SQL
Strip emoji ranges out of user text on PostgreSQL with Unicode-aware regex patterns.
PostgreSQL +2 engines -
Compare strings ignoring case and accents in SQL
Make 'JOSE' match 'José' and 'garcia' match 'García' with collations instead of rewriting the text.
SQL Server +2 engines -
Natural sort strings with numbers in SQL
Order file names and codes the way humans expect by sorting the numeric tail numerically, not alphabetically.
PostgreSQL +1 engine -
Extract leading digits from a string in SQL
Pull the numeric prefix out of codes like '123-ABC' with a regex substring or PATINDEX.
PostgreSQL +2 engines -
Extract trailing digits from a string in SQL
Get the number off the end of 'Invoice-2026-047' for sorting and version comparison.
PostgreSQL +2 engines -
Test whether a string starts or ends with a value in SQL
Match SKUs beginning with 'AB-' or codes ending in '-XY' with LIKE and index-friendly range scans.
All engines -
Fuzzy match strings with Levenshtein distance in SQL
Match 'Jon Smith' to 'John Smyth' by edit distance, and what each engine ships for it (often nothing).
PostgreSQL +2 engines -
Count business days between two dates in SQL
Count Monday-to-Friday days between two dates, weekends excluded, holidays on top if you supply a table.
SQL Server +1 engine -
Add N business days to a date in SQL
Compute a ship date of five working days after the order, skipping weekends (and holidays via a table).
PostgreSQL +1 engine -
Compute age in years, months and days in SQL
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.
PostgreSQL +2 engines -
Find the next anniversary of a date in SQL
Work out each employee's next work anniversary or each customer's next renewal, this year or next.
SQL Server +1 engine -
Get the first and last day of the week in SQL
Round any date down to its Monday and up to its Sunday for weekly reporting buckets.
PostgreSQL +2 engines -
Get the first and last day of the month in SQL
Bucket a date to its month boundaries with EOMONTH, date_trunc, LAST_DAY or TRUNC.
SQL Server +3 engines -
Get the first and last day of the quarter in SQL
Snap any date to its quarter boundaries (Jan 1, Apr 1, Jul 1, Oct 1 and friends).
SQL Server +1 engine -
Get the first and last day of the year in SQL
Build Jan 1 and Dec 31 of a date's year, leap years included, with one expression per boundary.
PostgreSQL +2 engines -
Get the same day in the previous month in SQL
Subtract one month from any date, and what happens when the target month has no 31st.
PostgreSQL +2 engines -
Get the ISO week number of a date in SQL
Number the weeks of the year per ISO 8601 (weeks start Monday; week 1 holds the first Thursday).
SQL Server +3 engines -
Map a calendar date to a fiscal year in SQL
Assign every date to the fiscal year it belongs to, for fiscal years that start in any month.
PostgreSQL +1 engine -
Get the number of days in a month in SQL
Return 28, 29, 30 or 31 for any date's month, leap years handled by the engine.
SQL Server +3 engines -
Normalize stored timestamps to UTC in SQL
Tag naive timestamps stored as UTC, then convert them to any zone for display, the two-step AT TIME ZONE way.
PostgreSQL +1 engine -
Convert local wall time to UTC in SQL
Turn wall-clock times captured in a local zone into UTC instants, DST-aware, before storing them.
SQL Server +1 engine -
Do DST-safe day arithmetic on timestamps in SQL
Add days to a zoned timestamp without the local time drifting an hour across a DST boundary.
PostgreSQL +1 engine -
Convert between Unix epoch and timestamps in SQL
Turn timestamps into epoch seconds and back, per engine, without letting a session time zone shift the result.
PostgreSQL +2 engines
スキーマ
Tables, columns, constraints and the metadata to inspect them. 50 recipes
-
List all tables with sizes
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.
PostgreSQL +3 engines -
Describe a table: columns, types and defaults
The equivalent of psql's \d or MySQL's DESCRIBE, written as a query: column names, data types, nullability and defaults for one table.
PostgreSQL +3 engines -
List columns of a table from system catalogs
List one table's columns from the engine's own catalogs (sys.columns on SQL Server, pg_attribute on PostgreSQL) instead of INFORMATION_SCHEMA.
SQL Server +2 engines -
List primary keys and their columns
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.
PostgreSQL +2 engines -
List foreign keys and the tables/columns they point at
Every foreign key with its source table/column and the referenced table/column, so you can map the dependency graph or plan load order.
PostgreSQL +2 engines -
Find tables without a primary key
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.
PostgreSQL +2 engines -
Find tables without any index
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.
MySQL +2 engines -
List indexes of a table with their columns
All indexes on one table with the columns they cover and their definitions, across the four engines' native index catalogs.
PostgreSQL +3 engines -
Find unused index candidates
Indexes the engine's usage counters say have never been scanned, listed with their size so you know what dropping each one would reclaim.
PostgreSQL +2 engines -
Find duplicate index candidates
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.
PostgreSQL +2 engines -
List views and their definitions
Every view in a schema with the SQL that defines it, so you can see which business logic lives in the database layer.
PostgreSQL +3 engines -
List sequences and their current values
All sequences in a database with their last value, increment and limit, so you can spot integer keys that are running out of room.
PostgreSQL +3 engines -
List triggers on a table
All triggers attached to one table with their firing conditions and source, so mysterious row changes stop being mysterious.
PostgreSQL +3 engines -
List check constraints
Every check constraint with the expression it enforces, so the business rules baked into the schema are visible and reviewable.
SQL Server +2 engines -
List enum types and their values
All enum types in a schema with the values they allow, the columns that use them, and PostgreSQL domains with their CHECK rules.
PostgreSQL +1 engine -
Row counts of every table
Approximate row counts for every table in one query, read from each engine's maintained statistics instead of running COUNT(*) per table.
PostgreSQL +3 engines -
Find every table that has a given column
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.
MySQL +3 engines -
Find columns by data type
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.
PostgreSQL +2 engines -
List schemas
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.
PostgreSQL +2 engines -
Database size summary
Total database size with a per-schema breakdown, so you know where the space went before you start vacuuming or archiving.
PostgreSQL +3 engines -
Table bloat estimate
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.
PostgreSQL +1 engine -
Table dependency order for load and dump
Which tables each table's foreign keys point at, the input for sorting tables so parents load before children and get emptied after them.
PostgreSQL +2 engines -
Generate DROP TABLE statements
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.
MySQL +3 engines -
Truncate all tables in safe order
Empty every table in a schema without tripping over foreign keys, using each engine's way around dependency order.
PostgreSQL +2 engines -
Add a column if it does not exist
Idempotent add-column migrations: IF NOT EXISTS where supported, and the guarded equivalent on engines that lack it.
PostgreSQL +3 engines -
Rename a column if it exists
Guarded column renames: check the metadata first so re-running the migration is a no-op instead of an error.
SQL Server +3 engines -
Add a foreign key if it does not exist
Idempotent FK creation guarded by constraint name, plus the NOT VALID pattern for adding the check to big tables without a long lock.
PostgreSQL +2 engines -
CREATE TABLE IF NOT EXISTS variants
Idempotent table creation: native IF NOT EXISTS where the engine has it, and an OBJECT_ID guard on SQL Server, which rejects the clause.
SQLite +3 engines -
Comment a column and its table
Attach descriptions to columns and tables so the schema documents itself: COMMENT ON in PostgreSQL, COMMENT clauses in MySQL, extended properties in SQL Server.
PostgreSQL +2 engines -
Set a column default
Add a default to an existing column on each engine, including SQL Server, where a default is a separate named constraint.
PostgreSQL +3 engines -
Remove a column default
Drop a default from a column: one statement on MySQL and PostgreSQL, a constraint lookup first on SQL Server, where defaults are named objects.
PostgreSQL +3 engines -
Make a column NOT NULL safely
Check for NULLs, backfill them, then enforce NOT NULL, plus the CHECK-constraint route that avoids a long exclusive lock on big PostgreSQL tables.
PostgreSQL +2 engines -
Widen a column type
Grow varchar limits and change int to bigint on each engine, with notes on which widening is metadata-only and which rewrites the table.
MySQL +3 engines -
Change a column to nullable
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.
PostgreSQL +3 engines -
Move a table between schemas
Relocate a table to another schema in one statement (SET SCHEMA on PostgreSQL, ALTER SCHEMA ... TRANSFER on SQL Server), and what moves with it.
PostgreSQL +1 engine -
Copy a table's structure only
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.
MySQL +3 engines -
Copy a table with its data
Full-table clone with CREATE TABLE AS SELECT and its per-engine equivalents, and which constraints and indexes the copy loses.
PostgreSQL +3 engines -
Create an empty table like another table
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.
PostgreSQL +2 engines -
Swap two table names
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.
PostgreSQL +3 engines -
Archive old rows to a history table
Move expired rows out of a hot table into an archive in one statement (DELETE ... RETURNING on PostgreSQL, OUTPUT on SQL Server), plus batching.
PostgreSQL +2 engines -
Rotate a table partition
Add next month's partition and detach an expired one, which replaces a huge archive DELETE with two catalog operations.
PostgreSQL +1 engine -
Grant SELECT on all tables
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.
PostgreSQL +2 engines -
Revoke all privileges
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.
PostgreSQL +2 engines -
List a user's privileges
See what a role has been granted: table privileges from information_schema, SHOW GRANTS on MySQL, sys.database_permissions on SQL Server.
PostgreSQL +3 engines -
Default privileges for future tables
Make grants apply to tables that do not exist yet with ALTER DEFAULT PRIVILEGES, which is keyed to the role that creates the tables.
PostgreSQL +2 engines -
List materialized views and refresh times
Every PostgreSQL materialized view with its populated flag and size, plus a refresh-log table, since PostgreSQL keeps no last-refresh time.
PostgreSQL +1 engine -
Schema version table recipe
A tiny table recording which schema version the database is at, so scripts can check before running and drift between environments becomes visible.
PostgreSQL +2 engines -
Migration lock row recipe
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.
PostgreSQL +2 engines -
Find auto-increment and identity columns
Every auto-generated key column in a schema (identity, serial or AUTO_INCREMENT), the list you need before moving int keys to bigint.
PostgreSQL +3 engines -
Rename a table safely
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.
PostgreSQL +3 engines
Indexes & performance
Finding missing indexes, unused ones and the queries that hurt. 14 recipes
-
Generate DDL for missing foreign-key indexes in SQL Server
Finds foreign keys whose leading column starts no index and prints a CREATE INDEX statement for each one, ready to review and run.
SQL Server +1 engine -
Generate CREATE INDEX statements from SQL Server's missing index DMVs
Ranks the optimizer's missing index suggestions by estimated benefit and builds a CREATE INDEX for each: equality columns, then inequality, then INCLUDE.
SQL Server +2 engines -
Find unused indexes in PostgreSQL
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.
PostgreSQL -
Find duplicate indexes in PostgreSQL
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.
PostgreSQL -
Find indexes never scanned in SQL Server
Lists nonclustered indexes with zero user seeks, scans and lookups but ongoing write maintenance since the instance last started.
SQL Server -
Find the largest indexes in PostgreSQL
Ranks every index by its on-disk size so you can spot bloated or oversized ones and target maintenance where the bytes actually are.
PostgreSQL +1 engine -
Find redundant indexes that are a prefix of another index in MySQL
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.
MySQL -
Detect recent sequential scans in PostgreSQL
Ranks tables by seq_scan and rows read sequentially, to find the tables where a missing or unused index hurts the most.
PostgreSQL -
Find the most-read tables in PostgreSQL
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.
PostgreSQL +1 engine -
Compute index usage ratio per table in PostgreSQL
Shows for each table what percentage of accesses went through an index versus a full scan, to catch tables drifting toward unindexed access.
PostgreSQL -
Find foreign keys without a supporting index in PostgreSQL
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.
PostgreSQL +1 engine -
Estimate index bloat in PostgreSQL
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.
PostgreSQL -
Find queries that put functions on indexed columns in PostgreSQL
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.
PostgreSQL +2 engines -
Read EXPLAIN QUERY PLAN output in SQLite
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.
SQLite
Monitoring & admin
Blocking, sizes, sessions and the health of the instance. 37 recipes
-
Find queries spilling to temp in PostgreSQL
Ranks pg_stat_statements by temp blocks written to catch sorts, hashes and CTEs that overflow work_mem to disk.
PostgreSQL +2 engines -
Find the most expensive queries in PostgreSQL
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.
PostgreSQL +3 engines -
Find the longest-running queries right now in PostgreSQL
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.
PostgreSQL +1 engine -
Find queries with high logical reads in SQL Server
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.
SQL Server -
Find sort-heavy queries in MySQL
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.
MySQL -
Check the buffer cache hit ratio in PostgreSQL
Computes the percentage of page reads served from cache versus disk, per database, with the SQL Server buffer pool equivalent.
PostgreSQL +1 engine -
Check the parse ratio and prepared statement cache in Oracle
Compares hard parses, total parses and executions in v$sysstat to see whether statements are reusing cursors or re-parsing on every run.
Oracle -
Find blocking chains in SQL Server
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.
SQL Server -
Show who blocks whom in PostgreSQL
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.
PostgreSQL +2 engines -
Find long-running transactions in PostgreSQL
Lists every session inside a transaction, oldest first, to catch the open transactions that hold locks and stop vacuum from cleaning up dead rows.
PostgreSQL +1 engine -
Find idle-in-transaction sessions in PostgreSQL
Lists sessions holding an open transaction while executing nothing, with how long they have been idle and what they last ran.
PostgreSQL -
Find recent deadlocks in SQL Server
Reads deadlock reports from the system_health Extended Events files, with the victim's session id and last statement, no tracing setup required.
SQL Server +1 engine -
Summarize current lock waits in MySQL
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.
MySQL -
Count connections by state, database and user in PostgreSQL
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.
PostgreSQL +1 engine -
Check connection saturation against max_connections in PostgreSQL
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.
PostgreSQL +2 engines -
Find sessions holding large query memory grants in SQL Server
Lists the requests currently holding memory grants with granted versus used memory, to spot over-granted queries starving the resource semaphore.
SQL Server -
Find the largest tables and indexes in PostgreSQL
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.
PostgreSQL +1 engine -
Track database growth by month from backup history in SQL Server
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.
SQL Server -
Check autovacuum status and dead-tuple backlog in PostgreSQL
Shows dead tuples, dead-tuple percentage and the last autovacuum per table, so you can see whether vacuum is keeping up or falling behind.
PostgreSQL -
Find stale planner statistics in PostgreSQL
Ranks tables by rows modified since the last ANALYZE, manual or automatic, to find tables whose planner statistics no longer describe the data.
PostgreSQL +1 engine -
Find the last ANALYZE time per table in PostgreSQL
Lists every table ordered by how long ago its statistics were last collected, never-analyzed tables first.
PostgreSQL -
Find plan regressions with Query Store in SQL Server
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.
SQL Server -
Summarize wait types in SQL Server
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.
SQL Server +2 engines -
Read recent slow queries from the MySQL slow log table
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.
MySQL +1 engine -
Cancel a long-running query in PostgreSQL
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.
PostgreSQL +1 engine -
Terminate a session in PostgreSQL
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.
PostgreSQL +1 engine -
Set statement timeout per session and role in PostgreSQL
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.
PostgreSQL -
Track COPY and import progress in PostgreSQL
Joins pg_stat_progress_copy with pg_stat_activity to show live COPY operations with bytes processed, total and percent done.
PostgreSQL -
Measure replication lag in PostgreSQL
Shows per-standby WAL replay lag in bytes and time from pg_stat_replication, with the standby-side seconds-behind check.
PostgreSQL +1 engine -
Check for checkpoint pressure in PostgreSQL
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.
PostgreSQL +1 engine -
Check WAL volume generated in PostgreSQL
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.
PostgreSQL +1 engine -
See what is in the SQL Server buffer pool
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.
SQL Server -
Find single-use ad-hoc plans wasting plan cache memory in SQL Server
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.
SQL Server -
List data and log file sizes per database in SQL Server
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.
SQL Server +2 engines -
Find the sessions doing the most I/O in Oracle
Ranks live Oracle sessions by physical reads and consistent gets from v$sess_io, joined to v$session for user and current SQL context.
Oracle +1 engine -
Find the most expensive stored procedures in SQL Server
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.
SQL Server -
Find the sessions consuming tempdb space in SQL Server
Ranks live sessions by tempdb pages allocated for user and internal objects; internal pages are the signature of sort and hash spills.
SQL Server +1 engine
No snippet matches that
Try a shorter word such as duplicate, size または ロック, or switch the engine filter back to Any engine.
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.