Steering AI to Write Queries
Describe the Result, Not the Query
Bad Ask, Bad Query
"Write me a query for customer sales" leaves the AI to guess. Which sales? Shipped only? What about refunds? Customers who bought nothing? It picks answers, doesn't tell you, and hands you something that runs.
Don't describe the SQL. Describe the result. Five things:
- One row per what? Say it out loud.
- The columns, and how each is calculated.
- What's in and what's out, with exact edges.
- The awkward cases: nothing bought, NULLs, duplicates, orders marked
Cancelled. - The real schema. Paste the
CREATE TABLEscripts with keys and indexes. Don't let it guess column names.
What That Looks Like
SQL Server 2022. Schema is pasted below.
Result: one row per customer. Every customer, even those
who bought nothing.
Columns:
- CustomerId, Name
- Orders: how many different orders
- Revenue: sum of Quantity * UnitPrice over those orders'
lines. 0 if none, never NULL.
Include: Status = 'Shipped', OrderDate from March 1, 2025
up to but not including April 1, 2025.
Don't wrap columns in functions in WHERE or JOIN.
Don't use DISTINCT unless you explain why it's needed.
Before the SQL: list every assumption you're making and
every place two tables join one-to-many.
A Good Answer Looks Like This
SELECT c.CustomerId,
c.Name,
COUNT(DISTINCT o.OrderId) AS Orders,
COALESCE(SUM(l.Quantity * l.UnitPrice), 0) AS Revenue
FROM dbo.Customers AS c
LEFT JOIN dbo.Orders AS o
ON o.CustomerId = c.CustomerId
AND o.Status = 'Shipped'
AND o.OrderDate >= '20250301'
AND o.OrderDate < '20250401'
LEFT JOIN dbo.OrderLines AS l
ON l.OrderId = o.OrderId
GROUP BY c.CustomerId, c.Name;
Now judge it with Module 1. The filters are in the join, so nobody gets dropped. Dates are a clean range. DISTINCT is there for a reason you can say: an order with three lines shows up three times, and it should count once. Revenue isn't doubled, because lines are the only one-to-many thing being summed.
You can say why every line is there. That's the job.
The best line in that prompt is the last one. Making the AI list its assumptions before the SQL turns hidden guesses into a list you can say yes or no to.
What's the most useful thing to give an AI when you need a query?