runtime
70 / 88

lesson 70 Performance & query plans · advanced

Review AI-generated SQL with evidence

Check generated SQL against real results and requirements.

the idea

Use assistance to explain or propose alternatives, then verify against the schema, metric definition, edge cases, and real execution plan. A confident answer can still double-count rows or omit zero-activity users. This lesson is a deterministic review exercise; no live AI service is connected.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

ai_accounts4 columns · 6 rows
idinteger · keyplantextregiontextsigned_up_attext
1proUS2025-01-01
2freeUS2025-01-02
3teamEU2025-01-02
4proIN2025-01-03
5freeEU2025-01-04

showing 5 of 6 rows

ai_requests7 columns · 12 rows
idinteger · keyaccount_idintegermodeltextrequested_attextinput_tokensintegeroutput_tokensintegerstatustext
11swift2025-01-01 10:00:001000200success
21reason2025-01-02 11:00:002000600success
32swift2025-01-02 12:00:005000error
43reason2025-01-02 13:00:0080002000success
53swift2025-01-03 14:00:0040001000success

showing 5 of 12 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
-- Review claim: COUNT(*) after LEFT JOIN counts each account’s requests.
 -- Counterexample: accounts with no requests get one preserved row.

SELECT a.id,COUNT(r.id) AS request_count
FROM ai_accounts a
LEFT JOIN ai_requests r ON r.account_id=a.id
GROUP BY a.id;

Watch for: Inspect plans before claiming an optimization; this app does not invoke ChatGPT or another model.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Read the accounts before trusting a query. Check who is in the table, including accounts that may have no requests. A plan does not prove the metric.

    step-1.sql
    SELECT id, plan, region
    FROM ai_accounts;
  2. Run the reference. Use assistance to explain or propose alternatives, then verify against the schema, metric definition, edge cases, and real execution plan. A confident answer can still double-count rows or omit zero-activity users. This lesson is a deterministic review exercise; no live AI service is connected.

    step-2.sql
    -- Review claim: COUNT(*) after LEFT JOIN counts each account’s requests.
     -- Counterexample: accounts with no requests get one preserved row.
    
    SELECT a.id,COUNT(r.id) AS request_count
    FROM ai_accounts a
    LEFT JOIN ai_requests r ON r.account_id=a.id
    GROUP BY a.id;

challenge 1

Fix the proposed COUNT(*) LEFT JOIN query. Return id and request_count for every account, including zero-request accounts.

Return idrequest_countany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.