Short answer: write the prompt in four parts. Role: "You write T-SQL for SQL Server." Task: the question in business words. Context: the table definitions, keys and what a row means. Format: one query, with the columns you want back and their order. Add one example of a query you like, and the AI copies its style. Then run it on a small sample and check one number by hand.
Asking an AI for SQL without the schema is asking it to guess your table names. Asking without the dialect gets you LIMIT on a SQL Server that wants TOP. The four parts close both gaps.
What goes into each part?
- Rolethe database and dialect: "You write T-SQL for SQL Server 2022"
- Taskthe question: "the 10 customers with the highest revenue in 2026, with their country"
- ContextCREATE TABLE lines, keys, and what one row means ("one row per order line")
- Format"one query, columns CustomerName, Country, Revenue, sorted by Revenue, no comments"
What does a full prompt look like?
You write T-SQL for SQL Server 2022.
Task: the 10 customers with the highest revenue in 2026, with their country.
Tables:
Sales(OrderID, OrderDate, CustomerID, Amount) -- one row per order line
Customer(CustomerID, CustomerName, Country)
Return one query with the columns CustomerName, Country, Revenue, sorted by Revenue descending.
Example of the style I want:
SELECT TOP (5) p.ProductName, SUM(s.Amount) AS Revenue
FROM Sales AS s JOIN Product AS p ON p.ProductID = s.ProductID
GROUP BY p.ProductName ORDER BY Revenue DESC;The example teaches more than a paragraph of rules: aliases, TOP in brackets, the join style, the sort.
How do you check the query?
- Run it on a sample or a test copy, never first on production.
- Check one row by hand: pick the top customer and sum their 2026 orders yourself.
- Read the joins: a join on the wrong key repeats rows and inflates every total.
- Look at the dates:
OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01'keeps the whole last day;BETWEENwith a datetime can lose it.
What goes wrong?
- No dialect. You get
LIMIT 10on SQL Server, orTOPon PostgreSQL. - No row meaning. "Amount" per order or per order line changes every sum.
- Real customer data in the prompt. Send the schema and made-up rows, not the data itself, unless your company allows it.
Where can you check this?
Where do you start?
The same four parts work for DAX: see how to prompt an AI to write a DAX measure. For queries with running totals and ranks, read SQL window functions explained first, so you can check what the AI writes.