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 · key | plantext | regiontext | signed_up_attext |
|---|---|---|---|
| 1 | pro | US | 2025-01-01 |
| 2 | free | US | 2025-01-02 |
| 3 | team | EU | 2025-01-02 |
| 4 | pro | IN | 2025-01-03 |
| 5 | free | EU | 2025-01-04 |
showing 5 of 6 rows
ai_requests7 columns · 12 rows
| idinteger · key | account_idinteger | modeltext | requested_attext | input_tokensinteger | output_tokensinteger | statustext |
|---|---|---|---|---|---|---|
| 1 | 1 | swift | 2025-01-01 10:00:00 | 1000 | 200 | success |
| 2 | 1 | reason | 2025-01-02 11:00:00 | 2000 | 600 | success |
| 3 | 2 | swift | 2025-01-02 12:00:00 | 500 | 0 | error |
| 4 | 3 | reason | 2025-01-02 13:00:00 | 8000 | 2000 | success |
| 5 | 3 | swift | 2025-01-03 14:00:00 | 4000 | 1000 | success |
showing 5 of 12 rows
example
The idea in one query. Press Run to see what it returns; running examples never affects your progress.
-- 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.
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.sqlSELECT id, plan, region FROM ai_accounts;
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;