Prompt Engineering for Analysts: Getting Correct SQL From an LLM (and Checking It)

An LLM writes SQL in seconds. Your job is to make sure the seconds it saves do not cost you a wrong number.

By | 10 min read | Level: Intermediate | Category: SQL

Fast, and Sometimes Wrong

An LLM is a genuinely good SQL drafter. Give it a question and it will hand you a query in seconds, with joins wired up and columns named sensibly. That speed is real, and you should use it. The catch is that the same tool produces queries that look correct, read fluently, and return a wrong number with total confidence.

The failures are rarely syntax errors, because syntax errors are easy to catch: the query simply does not run. The dangerous ones run fine and give you a plausible answer. The model joins on the wrong key, double counts revenue through a one-to-many join, silently drops rows where a value is NULL, or answers at the wrong grain, giving you one row per order line when you asked for one row per customer. None of that raises an error. It raises a number, and you paste it into a report.

Why This Matters

The person who ran the query owns the number. If a dashboard says revenue is double what finance recorded, "the AI wrote it" is not an answer anyone accepts. You stay responsible for correctness, so the skill worth building is not prompting faster, it is verifying what comes back.

How to Prompt So the SQL Is Correct

Most wrong queries come from a vague prompt. The model cannot see your database. It guesses table names, column names, and relationships, and a confident guess that happens to be wrong is worse than a question. You cut the guessing by giving it four things: the schema, the exact question with its grain, the dialect, and a small example of the output you expect.

Here is a vague prompt of the kind that produces a good-looking, wrong query:

BAD PROMPT Write me a SQL query for monthly revenue by customer.

The model has to invent every table name, decide what "revenue" means, guess whether you want a date or a month label, and pick a dialect. Compare that with a structured prompt that leaves almost nothing to invent:

GOOD PROMPT Dialect: PostgreSQL. Schema: customers(customer_id PK, customer_name, country) orders(order_id PK, customer_id FK, order_date, status) order_items(order_item_id PK, order_id FK, product_id, quantity, unit_price) Grain notes: - orders has one row per order. - order_items has one row per line item, many per order. - Line revenue = quantity * unit_price. Question: For calendar year 2025, give total revenue per customer per month. One row per (customer, month). Only count orders where status = 'completed'. Expected output columns: customer_id, customer_name, month (YYYY-MM), revenue Show me one example row, e.g.: 42, 'Acme Ltd', '2025-03', 1899.50

The structured prompt states the grain of every table, so the model knows order_items is one-to-many against orders. That single fact is what stops the most common revenue bug, which we will see next. Naming the dialect stops it from reaching for a function your database does not have. The example row tells it the shape you want back, which keeps it from returning one row per line item when you asked for one per customer per month.

The Four Things

Schema (tables, columns, keys, grain), the exact question and the grain of the answer, the SQL dialect, and one example output row. Give all four and the model has little left to guess.

Four inputs of a good SQL promptGive the model four things, the schema with keys and grain, the question and its grain, the SQL dialect, and one example output row, and it returns correct SQL you can verify. Four things a good SQL prompt gives the model 1 Schema: tables, columns, keys, grain 2 The question and its grain 3 The SQL dialect 4 One example output row LLM drafts SQL Correct SQL you can verify
Give the model the schema, the question and its grain, the dialect and an example row, and little is left to guess.

A Worked Example: Monthly Revenue Per Customer

Let us stay with that schema. We have customers, their orders, and the line items on each order. Revenue lives at the line level, one line per product on an order, so the total for an order is the sum of quantity * unit_price across its lines.

-- The tables, and their grain -- customers: one row per customer -- orders: one row per order (many orders per customer) -- order_items: one row per line item (many line items per order)

Ask an LLM for "monthly revenue per customer" without spelling out the grain, and it will very often produce something like this. Read it slowly, because it looks right.

-- WRONG: joins orders to order_items, then sums an order-level column SELECT c.customer_id, c.customer_name, TO_CHAR(o.order_date, 'YYYY-MM') AS month, SUM(o.order_total) AS revenue FROM customers c JOIN orders o ON o.customer_id = c.customer_id JOIN order_items oi ON oi.order_id = o.order_id WHERE o.status = 'completed' AND o.order_date >= '2025-01-01' AND o.order_date < '2026-01-01' GROUP BY c.customer_id, c.customer_name, TO_CHAR(o.order_date, 'YYYY-MM');

There are two problems. The small one is that order_total was never in our schema, so this query assumes a column that may not exist. The large one is the join, which we will pull apart now.

The Fan-Out Join That Doubles Your Revenue

When you join orders to order_items, one order row is repeated once for every line item on that order. An order with three line items becomes three rows. This is a fan-out join, and it is completely normal. The bug is what you do after the fan-out.

If an order-level value like order_total exists and you SUM it after the fan-out, you add that same order total once per line item. A 100 dollar order with three lines gets counted as 300 dollars. The number is not a little off, it is multiplied by the number of lines, and it changes from order to order, so it does not even look like a clean doubling you might spot.

Watch Out!

Any time you join a table to a more detailed child table and then aggregate a column from the parent, you risk multiplying that value by the number of child rows. This is the single most common way an LLM query returns inflated totals.

How a fan-out join inflates a totalJoining one order to its three line items repeats the order-level total once per line, so summing order_total returns 300 dollars instead of 100; building revenue from the line items returns the correct 100. Why SUM after a fan-out inflates revenue THE BUG 1 order order_total 100 JOIN 3 lines 3 joined rows line 1 order_total 100 line 2 order_total 100 line 3 order_total 100 SUM $300 inflated 3x THE FIX 3 line items 40 + 35 + 25 SUM(quantity * unit_price) $100 correct
Summing an order-level value after joining to line items counts it once per line; build revenue from the lines instead.

There are two clean fixes. The first computes revenue from the line items directly, which is where revenue actually lives, so there is no parent column to double:

-- CORRECT: revenue is built from line items at their own grain SELECT c.customer_id, c.customer_name, TO_CHAR(o.order_date, 'YYYY-MM') AS month, SUM(oi.quantity * oi.unit_price) AS revenue FROM customers c JOIN orders o ON o.customer_id = c.customer_id JOIN order_items oi ON oi.order_id = o.order_id WHERE o.status = 'completed' AND o.order_date >= '2025-01-01' AND o.order_date < '2026-01-01' GROUP BY c.customer_id, c.customer_name, TO_CHAR(o.order_date, 'YYYY-MM');

Because we sum quantity * unit_price from order_items, the fan-out is exactly what we want: each line contributes its own revenue once. The second fix aggregates the line items first, so each order carries a single revenue figure before it ever meets the customer table:

-- CORRECT: pre-aggregate line items to one row per order, then join WITH order_revenue AS ( SELECT oi.order_id, SUM(oi.quantity * oi.unit_price) AS order_total FROM order_items oi GROUP BY oi.order_id ) SELECT c.customer_id, c.customer_name, TO_CHAR(o.order_date, 'YYYY-MM') AS month, SUM(orv.order_total) AS revenue FROM customers c JOIN orders o ON o.customer_id = c.customer_id JOIN order_revenue orv ON orv.order_id = o.order_id WHERE o.status = 'completed' AND o.order_date >= '2025-01-01' AND o.order_date < '2026-01-01' GROUP BY c.customer_id, c.customer_name, TO_CHAR(o.order_date, 'YYYY-MM');

Here order_revenue collapses the line items to one row per order, so joining it to orders is one-to-one and there is no fan-out at all. Both queries give the same answer. The pre-aggregated version is often easier to reason about, and it is the pattern you want when the same order gets joined to several child tables at once.

How to Check the Output

You do not have to trust either query. You check it, and the checks take a minute. The point is to confirm the grain is what you asked for and the total matches something you already know.

First, confirm the grain. You asked for one row per customer per month, so that combination should never appear twice. If this returns any rows, the grain is wrong:

-- GRAIN CHECK: this should return zero rows SELECT customer_id, month, COUNT(*) AS n FROM ( -- paste your query here as a subquery SELECT customer_id, month FROM monthly_revenue ) t GROUP BY customer_id, month HAVING COUNT(*) > 1;

Second, compare the grand total against a figure computed a completely different way, straight from the line items with no customer or month grouping. If your report sums to the same number, the joins did not add or drop revenue:

-- TOTAL CHECK: the known-good total for 2025 completed orders SELECT SUM(oi.quantity * oi.unit_price) AS total_revenue_2025 FROM order_items oi JOIN orders o ON o.order_id = oi.order_id WHERE o.status = 'completed' AND o.order_date >= '2025-01-01' AND o.order_date < '2026-01-01'; -- Now sum your report and confirm the two match exactly.

Run the wrong query against that total and it will come out visibly larger, because the fan-out inflated it. Run either correct query and it will match to the cent. That one comparison catches the double-counting bug on its own.

Third, spot-check a single customer by hand. Pick one customer id, list their raw line items for a month, add them up in your head or a calculator, and confirm the report shows the same figure:

-- SPOT CHECK: one customer, one month, from the raw lines SELECT o.order_id, o.order_date, oi.quantity, oi.unit_price, oi.quantity * oi.unit_price AS line_revenue FROM orders o JOIN order_items oi ON oi.order_id = o.order_id WHERE o.customer_id = 42 AND o.status = 'completed' AND o.order_date >= '2025-03-01' AND o.order_date < '2025-04-01' ORDER BY o.order_date;

Add up the line_revenue column and check it against the March 2025 row for customer 42 in your report. If a customer you know well shows a number you can reproduce by hand, your confidence in the whole result goes up fast. It also flags NULL trouble: if a customer with orders is missing from the report, or a completed order is missing from a customer, a join or a filter is dropping rows.

A Verification Checklist

Keep these habits close whenever an LLM hands you a query. They take a couple of minutes and they are the difference between shipping a number and shipping a guess.

Before You Trust the Query

  • Read the joins and name the grain of each table out loud. Any parent column summed after a join to a child table is a fan-out risk.
  • Confirm every column the query references actually exists in your schema.
  • Run the grain check: the key you grouped by should never repeat.
  • Compare the grand total against the same figure computed a different way.
  • Spot-check one row you can reproduce by hand.
  • Check the row count. A total that is far too high often means duplicated rows; far too low often means an INNER JOIN or a filter dropped NULLs.
  • Look for anything compared to NULL with = or != instead of IS NULL, which silently removes rows.

The Skill Is Verification, Not Prompting

An LLM will draft SQL faster than you can, and that is fine. The value you add is not the prompt, it is the judgment to check the result before anyone acts on it. An analyst who verifies is worth more in the AI era, not less, because the tools produce more output that needs a trained pair of eyes. Learn the checks, run them every time, and the speed becomes a real advantage instead of a faster way to be wrong.

Master SQL with EDUSHARK TRAINING

Want to write SQL you can defend, and check the queries a tool hands you? Our Data Analytics program covers SQL from joins and grain to real reporting, with practice on data like the schema in this article.

View Our Data Analytics Program