Skip to content
mentoor

Topic 5 of 5 · 5 min read

Reviewing SQL an assistant wrote

Goal: Find the wrong join key, missing filter or unparameterized input in an AI-written query and test the fix against rows with known answers.

Treat a query from Copilot, Cursor, Claude or ChatGPT as an untested draft: check the join keys, the filters it should have added, how input reaches the string, and run it against rows whose right answer you already know.

Check yourself · 1 of 3

An assistant writes a query that runs without errors. What does that prove?

Choose one answer

Why it matters

An assistant writes fluent SQL that runs on the first try. That is the danger: "it runs" is the only check it has. It does not know that your orders.customer_id and customers.id are different kinds of ids, or that every query in your app must filter by tenant. The result is a table of plausible numbers.

How to review it

  1. Read it against the request. Write what the result should hold: one row per what, filtered how.
  2. Check every join key. Names that look alike can be wrong: users.id = orders.id is valid SQL. Confirm that each key is the foreign key from the schema.
  3. Look for the filters it forgot. Tenant or account id, soft-deleted rows (deleted_at IS NULL), the date range, the status.
  4. Check input handling. User values must be parameters ($1, ?, named binds), never built into the string with concatenation or f-strings.
  5. Test with known rows. Make three customers: one with no orders, one with two orders, one in another tenant. Write the expected output first, then run.
  6. Check cost. Run EXPLAIN on realistic volume.

Before and after

The request: "total paid revenue for the current tenant in a month."

# AI draft
query = f"SELECT SUM(o.total) FROM orders o JOIN order_items i ON i.order_id = o.id WHERE o.status = 'paid' AND o.month = '{month}'"

It has three defects: the join to items multiplies each order total, there is no tenant filter, and month is pasted into the string.

cur.execute(
    "SELECT SUM(total) FROM orders WHERE tenant_id = %s AND status = 'paid' AND created_at >= %s AND created_at < %s",
    (tenant_id, start, end),
)

What goes wrong

  • Trusting a plausible total. A revenue number that is 2.6 times too high still looks like money.
  • No tenant filter. The query works in testing with one tenant and leaks other customers' data in production.
  • String-built SQL. The assistant copies the pattern it sees in your code. Injection follows.
  • Passing review because the test used the assistant's own sample data. Tests written by the same tool share its misunderstanding.

Examples

The wrong join key that still runs

SELECT c.name, count(*)
FROM customers c
JOIN orders o ON o.id = c.id
GROUP BY c.name;

The assistant joined order id to customer id. The query runs and returns counts, but customer 5 is matched with order 5. The fix is o.customer_id = c.id. A test with one customer who has three orders shows the count of 1 at once.

A test set with known answers

Insert: customer A (no orders), customer B (two paid orders of 10 and 20), customer C in another tenant (one paid order of 99).

For the tenant of A and B, the expected revenue is 30 and A appears with 0 orders. If the query returns 129, the tenant filter is missing. If it returns 60 or more, a join is repeating rows.

Key points

  • A query that runs is not a query that is right; write down the expected result before you read the SQL.
  • Check every join key against the real foreign keys; similar names can be wrong.
  • Look for missing filters: tenant id, soft-deleted rows, date range and status.
  • User input must reach the database as parameters, never through string concatenation or f-strings.
  • Test against a few rows you built yourself, including a customer with no orders and a row from another tenant.

Common mistakes

  • Accepting the query because it ran without an error and returned numbers.
  • Letting the assistant also write the test data, so a shared misunderstanding passes.
  • Missing that a tenant or soft-delete filter is absent, because the test database has one tenant.
  • Leaving a value concatenated into the SQL string because it comes from an internal service.

Check yourself · 2 of 3

A multi-tenant app uses the query SELECT * FROM invoices WHERE status = 'open', written by an assistant. What is the main problem?

Choose one answer

Check yourself · 3 of 3

The draft is cur.execute(f"SELECT * FROM users WHERE email = '{email}'"). What is the best fix?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic