review-sql
Separate "is this query correct" from "is this safe to run here", because a correct query can still take a hot table offline.
Save as .claude/skills/review-sql/SKILL.md in a repository, or under ~/.claude/skills/review-sql/SKILL.md to have it everywhere. The copy button takes the whole file, frontmatter included.
--- name: review-sql description: Review a SQL query or migration for correctness, performance and safety before it runs against real data. Use when asked to check a query, review a migration, explain why a query is slow, or approve schema changes. --- # Review SQL A SQL review has two jobs that people routinely merge and should not: is the query **correct**, and is it **safe to run here**. A correct query can still take a production table offline. Read the query once for intent before commenting. If you cannot tell what it is supposed to return, say that first; a review of a query you have not understood is noise. ## 1. Correctness ### NULL is where most wrong answers live Three-valued logic breaks intuitions that hold everywhere else in programming: - `NULL = NULL` is not true. It is unknown. Use `IS NULL` / `IS DISTINCT FROM`. - `WHERE col NOT IN (subquery)` returns **no rows** if the subquery yields a single NULL. This is silent and it is a classic. Prefer `NOT EXISTS`. - `COUNT(col)` skips NULLs; `COUNT(*)` does not. A changed count after refactoring is often this. - Aggregates ignore NULLs, so `AVG` over a column with missing values averages the present ones, which may or may not be what was meant. ### Joins - Check the join key is actually unique on the side you assume. A join to a table with duplicate keys multiplies rows, and a `SUM` over the result is then wrong rather than merely slow. This is the single most common cause of "the numbers do not match the dashboard". - A `LEFT JOIN` with a condition on the right table in `WHERE` rather than `ON` silently becomes an inner join. - Confirm the grain of the result: one row per what. State it in the review. ### Other correctness checks - `GROUP BY` lists every non-aggregated selected column. - Filtering on a window function needs a subquery or a `QUALIFY`; `WHERE` evaluates before windows. - Date ranges: `BETWEEN '2026-01-01' AND '2026-01-31'` on a timestamp column excludes most of 31 January. Use half-open ranges, `>= start AND < end`. - Timezone: is the column `timestamptz` or `timestamp`, and whose day boundary is the query using. - Integer division. `count_a / count_b` on integers truncates in most engines. ## 2. Performance Never assert a query is slow or fast without a plan. Ask for `EXPLAIN ANALYZE` output, or say you are reasoning without one. What actually matters, in order: - **A sequential scan on a large table in a hot path.** Look at whether a predicate can use an index at all. - **A predicate that defeats an index**: a function on the column (`WHERE lower(email) = …` without a matching expression index), a leading wildcard `LIKE '%foo'`, an implicit type cast between the column and the parameter. - **Row estimates far from actual** in the plan. The planner is choosing badly because statistics are stale or a correlation is not modelled. More indexes will not fix this. - **Nested loop over a large outer input.** Usually a missing index on the inner side. - `SELECT *` in application code, which breaks index-only scans and ships columns nobody reads. - `OFFSET` pagination at depth. `OFFSET 100000` reads and discards 100,000 rows. Keyset pagination instead. Resist recommending an index per slow query. Each one costs write throughput and storage, and a composite index in the wrong column order serves neither query. Check whether an existing index would serve with a reordered predicate. ## 3. Safety, for anything that writes This is the part that gets skipped and the part that causes incidents. - **An `UPDATE` or `DELETE` with no `WHERE`.** State it as a blocker, every time, regardless of how obvious it looks. - Does the `WHERE` select what the author thinks? Ask for the output of the equivalent `SELECT COUNT(*)` first. - Is it wrapped in a transaction, and is the rollback plan written down. - **Lock duration.** `ALTER TABLE` taking an exclusive lock on a large hot table blocks every reader and writer for the duration. In PostgreSQL, adding a column with a non-volatile default is cheap; adding a `NOT NULL` constraint or changing a type rewrites the table. Know which one this is. - Creating an index without `CONCURRENTLY` locks writes for the build. - A migration that is not reversible needs the reverse path stated explicitly, even if it is "restore from backup". - Batch large deletes. A single `DELETE` of ten million rows holds a long transaction, bloats the table, and may never finish inside a deploy window. ## 4. Injection and permissions - Any query built by string concatenation with user input is a finding, not a nit. Parameterised queries are the only acceptable answer; escaping is not. - Dynamic identifiers (a table or column name from input) cannot be parameterised. They must be validated against an allowlist. - Does the role running this need the privileges it has. A reporting query running as the owner is a finding. ## Reporting Order findings by consequence: data loss and incorrect results first, performance second, style last. For each one say what is wrong, what happens if it ships, and the smallest change that fixes it. Mark confidence. "This join will multiply rows if `order_items.order_id` is not unique" is a finding; "this might be slow" is a guess. Say which you are offering, and say plainly when you need the plan or the schema to be sure.
what it needs
Nothing. This skill is instructions only, so it works in any agent that reads SKILL.md with nothing installed and no account. Save the file and it is live in the next session.
the instructions, in full
Review SQL
A SQL review has two jobs that people routinely merge and should not: is the query correct, and is it safe to run here. A correct query can still take a production table offline.
Read the query once for intent before commenting. If you cannot tell what it is supposed to return, say that first; a review of a query you have not understood is noise.
1. Correctness
NULL is where most wrong answers live
Three-valued logic breaks intuitions that hold everywhere else in programming:
NULL = NULLis not true. It is unknown. UseIS NULL/IS DISTINCT FROM.WHERE col NOT IN (subquery)returns no rows if the subquery yields a single NULL. This is silent and it is a classic. PreferNOT EXISTS.COUNT(col)skips NULLs;COUNT(*)does not. A changed count after refactoring is often this.- Aggregates ignore NULLs, so
AVGover a column with missing values averages the present ones, which may or may not be what was meant.
Joins
- Check the join key is actually unique on the side you assume. A join to a
table with duplicate keys multiplies rows, and a
SUMover the result is then wrong rather than merely slow. This is the single most common cause of "the numbers do not match the dashboard". - A
LEFT JOINwith a condition on the right table inWHERErather thanONsilently becomes an inner join. - Confirm the grain of the result: one row per what. State it in the review.
Other correctness checks
GROUP BYlists every non-aggregated selected column.- Filtering on a window function needs a subquery or a
QUALIFY;WHEREevaluates before windows. - Date ranges:
BETWEEN '2026-01-01' AND '2026-01-31'on a timestamp column excludes most of 31 January. Use half-open ranges,>= start AND < end. - Timezone: is the column
timestamptzortimestamp, and whose day boundary is the query using. - Integer division.
count_a / count_bon integers truncates in most engines.
2. Performance
Never assert a query is slow or fast without a plan. Ask for EXPLAIN ANALYZE
output, or say you are reasoning without one.
What actually matters, in order:
- A sequential scan on a large table in a hot path. Look at whether a predicate can use an index at all.
- A predicate that defeats an index: a function on the column
(
WHERE lower(email) = …without a matching expression index), a leading wildcardLIKE '%foo', an implicit type cast between the column and the parameter. - Row estimates far from actual in the plan. The planner is choosing badly because statistics are stale or a correlation is not modelled. More indexes will not fix this.
- Nested loop over a large outer input. Usually a missing index on the inner side.
SELECT *in application code, which breaks index-only scans and ships columns nobody reads.OFFSETpagination at depth.OFFSET 100000reads and discards 100,000 rows. Keyset pagination instead.
Resist recommending an index per slow query. Each one costs write throughput and storage, and a composite index in the wrong column order serves neither query. Check whether an existing index would serve with a reordered predicate.
3. Safety, for anything that writes
This is the part that gets skipped and the part that causes incidents.
- An
UPDATEorDELETEwith noWHERE. State it as a blocker, every time, regardless of how obvious it looks. - Does the
WHEREselect what the author thinks? Ask for the output of the equivalentSELECT COUNT(*)first. - Is it wrapped in a transaction, and is the rollback plan written down.
- Lock duration.
ALTER TABLEtaking an exclusive lock on a large hot table blocks every reader and writer for the duration. In PostgreSQL, adding a column with a non-volatile default is cheap; adding aNOT NULLconstraint or changing a type rewrites the table. Know which one this is. - Creating an index without
CONCURRENTLYlocks writes for the build. - A migration that is not reversible needs the reverse path stated explicitly, even if it is "restore from backup".
- Batch large deletes. A single
DELETEof ten million rows holds a long transaction, bloats the table, and may never finish inside a deploy window.
4. Injection and permissions
- Any query built by string concatenation with user input is a finding, not a nit. Parameterised queries are the only acceptable answer; escaping is not.
- Dynamic identifiers (a table or column name from input) cannot be parameterised. They must be validated against an allowlist.
- Does the role running this need the privileges it has. A reporting query running as the owner is a finding.
Reporting
Order findings by consequence: data loss and incorrect results first, performance second, style last. For each one say what is wrong, what happens if it ships, and the smallest change that fixes it.
Mark confidence. "This join will multiply rows if order_items.order_id is not
unique" is a finding; "this might be slow" is a guess. Say which you are
offering, and say plainly when you need the plan or the schema to be sure.
check its answers by hand
A skill that reasons well about wrong data is still wrong. For the first few cases, run the same question through a tool that cannot be mistaken.