Domdhi logoDOMDHI.OS
BACK_TO_COURSE

Steering AI to Write Queries

Check the Query Before You Trust It

Six Checks, a Few Minutes

Never trust a query because it ran. Running proves the spelling. Here's what proves the answer, using the customer query from the last lesson. Save its output into a temp table first: add INTO #Result on the line above FROM dbo.Customers.

1. Right number of rows? One row per customer, every customer. So the counts must match.

SELECT (SELECT COUNT(*) FROM #Result)       AS ResultRows,
       (SELECT COUNT(*) FROM dbo.Customers) AS Customers;
-- 10000, 10000

2. Any duplicates? This should return nothing.

SELECT CustomerId, COUNT(*) AS Copies
FROM #Result
GROUP BY CustomerId
HAVING COUNT(*) > 1;

3. Does the total match a simpler query? Get the same number another way, with fewer joins.

SELECT SUM(Revenue) AS Total FROM #Result;

SELECT SUM(l.Quantity * l.UnitPrice) AS Total
FROM dbo.OrderLines AS l
WHERE EXISTS (
    SELECT 1 FROM dbo.Orders AS o
    WHERE o.OrderId = l.OrderId
      AND o.Status = 'Shipped'
      AND o.OrderDate >= '20250301'
      AND o.OrderDate <  '20250401'
);
-- both: 2973189.00

4. One row by hand. Pick one customer. Pull their raw rows. Add it up yourself.

5. The edges. The last day, the first minute, a customer with nothing. Here's why. This looks right and isn't:

-- WRONG: stops at midnight, the START of March 31
WHERE OrderDate BETWEEN '20250301' AND '20250331'

It found 10,260 orders. The right answer is 10,602. It threw away 342 orders, all of them on March 31.

6. Rewriting an old query? Compare both ways. Run each into a temp table. Both of these should come back empty, and the row counts should match:

SELECT * FROM #Old EXCEPT SELECT * FROM #New;
SELECT * FROM #New EXCEPT SELECT * FROM #Old;

Check the counts too, because EXCEPT ignores duplicate rows.

Changing Data? Rehearse It

A bad SELECT gives you a bad number. A bad UPDATE gives you a bad week. Do it inside a transaction that undoes itself:

SET XACT_ABORT ON;
BEGIN TRANSACTION;

UPDATE dbo.Orders
SET Status = 'Cancelled'
WHERE Status = 'Open' AND OrderDate < '20230101';

SELECT @@ROWCOUNT AS RowsChanged;

ROLLBACK TRANSACTION;

Know how many rows it should be before you run it. If the count matches, change ROLLBACK to COMMIT. If it doesn't, nothing happened. Run it on a copy first when you can: until it finishes, it holds locks other people may be waiting on.

WARNING

Give AI a read-only login to anything that matters. If it can't change data, it can't change data by mistake. The write statements go through you.

QUIZ

A report filters a datetime column with BETWEEN '20250301' AND '20250331'. What's wrong?

Sign in to track lesson progress and earn a certificate.SIGN IN TO SAVE PROGRESS