ByeBuy.ai
BUILD YOUR ESCAPE ROUTE · ✦ CURSOR · HOST IT · ◫ SUPABASE · CONNECT IT · ↯ RELAY · BUILD YOUR ESCAPE ROUTE · ✦ CURSOR · HOST IT · ◫ SUPABASE · CONNECT IT · ↯ RELAY ·
← BYEBUY NOTES

September 12, 2026

LET AI DRAFT SQL, BUT YOU OWN THE QUESTION AND THE SAFETY CHECK

Let AI Draft SQL, But You Own the Question and the Safety Check

You now know how to read a query, summarize with counts and groups, and join tables. An AI assistant can draft all of that syntax in seconds — which raises the question this lesson answers: what should you let it do unsupervised, and what must stay behind a human decision?

The short version: investigation is safe, modification is not.

SQL has two modes with different risk

Mode 1 — read-only: SELECT. A SELECT query inspects data and returns a result set. Run it ten times and the database is unchanged. Every exercise in Lessons 21.1–21.3 lived here deliberately: it is the safe practice ground where mistakes cost confusion, not data.

Mode 2 — changes everything else. These statements modify the database, and each carries a different blast radius:

StatementWhat it doesBeginner risk
INSERTAdds rowsDuplicates, wrong table, bad values
UPDATEChanges existing rowsA missing WHERE rewrites the whole table
DELETERemoves rowsDeleted rows do not come back without a backup
Schema changes (ALTER TABLE, DROP TABLE)Redefines or removes structureBreaks the app and every saved query
MigrationsVersioned scripts that apply schema changesApplied to the wrong database, hard to undo

The nightmare one-liner is real: DELETE FROM research_reports; with no WHERE deletes every report. No confirmation dialog, no recycle bin. That asymmetry — reads are forgiving, writes are permanent — is why Part VI demands read-only examples before any write path.

Learn to recognize the vocabulary at a glance: INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, or CREATE means a change, and the workflow below applies.

The safe prompt pattern

When asking AI for SQL, make safety part of the request rather than an afterthought:

Business question: Which energy-sector reports from 2026
are still rated Hold?
Tables and fields: research_reports(company_name,
report_date, sector, rating, rating_score),
companies(id, name, sector).
Write a read-only SELECT query with a LIMIT first.
Explain in plain English what it returns, describe the
expected result shape (columns and approximate row count),
and run nothing that changes data. Tell me what you would
check before any write.

Five elements, each earning its place: business question, real tables/fields, SELECT first, explanation plus expected shape, safe environment.

Keep your source map from Class 19 next to this prompt: it is where the table and field names come from. An agent working from your documented schema drafts far better SQL than one guessing from memory.

Copy-paste template — fill the brackets, change nothing else:

Business question: [one sentence — filters, sort, and LIMIT stated]
Tables and fields: [exact table names and columns from your schema/source map]
Write a read-only SELECT query with a LIMIT first.
Explain in plain English what it returns, describe the
expected result shape (columns and approximate row count),
and run nothing that changes data. Tell me what you would
check before any write.
Do not write INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, or CREATE.

The dangerous pattern: "clean up the duplicates"

Contrast the safe prompt with a request builders actually type:

Clean up the duplicate reports in the database.

No backup. No definition of "duplicate." No preview of affected rows. No environment. An eager agent may draft a DELETE that matches too broadly and run it against production. Even syntactically perfect SQL cannot fix a question that was never defined.

Any change request missing these four answers is not ready: which exact rows, what "correct" means in writing, where a copy lives, and how we verify afterward. If any is missing, keep investigating — do not write.

The change workflow: from question to verified write

When a change is genuinely needed, walk this sequence — each step is a gate.

1. SELECT candidates → 2. inspect count + sample →
3. write transaction or migration → 4. test in development →
5. verify → 6. apply deliberately

1. SELECT the candidates. The read-only query showing exactly the rows the change would touch *is* the definition of the change.

2. Inspect count and sample. Does the count match expectation? Read five rows by eye. Surprises here are cheap; after the write they are expensive.

3. Write a transaction or migration. A *transaction* groups statements so they succeed or roll back together; a *migration* is a versioned, reviewable schema-change script. Ask the AI to draft either and explain each line.

4. Test in development. Run against a development or branched database, never production first.

5. Verify. Re-run the candidate SELECT — it should return zero rows or corrected values. Check related join counts for side effects.

6. Apply deliberately. With backup confirmed and a human decision recorded, run the change where it matters — and keep the migration file.

Why the CLI connection raises the stakes

From Part V you know an authenticated CLI lets an agent act on a real project. That is why instructions must get *clearer* when real SQL is in reach. Three non-negotiables: a confirmed backup or branch, a safe default database (development; production needs a separate human step), and a human decision on every write — the agent proposes, you dispose.

And hold the principle: AI writes syntax quickly; the builder defines the fact, the expected outcome, and the review boundary. Drafting speed is never evidence of correctness.

Visual: green investigation lane, amber change lane

GREEN LANE (read-only)              AMBER LANE (changes)
Question → SELECT → sample          Question → SELECT candidates
   ↓                                   ↓
Explain + result shape              Count + sample review
   ↓                                   ↓
Run in dev, compare rows            Transaction / migration draft
   ↓                                   ↓
Done. Repeat freely.                Test in dev → verify →
                                    backup confirmed → human
                                    decision → apply

Nothing in the green lane can destroy data; everything in the amber lane waits at gates. If you are ever unsure which lane a query belongs in, scan for the change vocabulary — its presence means amber.

Practical exercise: write a QUERY-PLAN.md

Create a QUERY-PLAN.md for one real question about your data. Include:

1. Plain-English question — one sentence, with the filter, sort, and limit stated. 2. Tables and fields — exact names from your schema or source map. 3. Read-only SELECT — AI-drafted is fine, with a LIMIT, plus its one-sentence explanation. 4. Expected shape — columns, approximate row count, and one sample row sketched by hand. 5. Pre-write review — the sentence "No write query exists yet." plus what must be true before one could: candidate SELECT reviewed, count matches expectation, backup or branch confirmed, development test passed, human approval recorded.

Filled example for one Sonariq question — copy this shape:

# QUERY-PLAN — Energy Holds, 2026

## 1. Plain-English question
Which energy-sector reports from 2026 are still rated Hold, newest first, 20 at most?

## 2. Tables and fields
research_reports(company_name, report_date, sector, rating)

## 3. Read-only SELECT (AI-drafted, read before running)
SELECT company_name, report_date, rating
FROM research_reports
WHERE sector = 'Energy'
  AND rating = 'Hold'
  AND report_date >= '2026-01-01'
ORDER BY report_date DESC
LIMIT 20;
Explanation: returns 2026 Energy reports rated Hold, newest first, up to 20 rows.

## 4. Expected shape
Columns: company_name, report_date, rating. Rows: ~6 (fewer than 20).
Sample row (hand-sketched): Acme Corp | 2026-08-14 | Hold

## 5. Pre-write review
No write query exists yet.
Before any INSERT/UPDATE/DELETE: see the pre-write review gate below —
all five checks must pass first.

Pre-write review gate — who checks what before any INSERT/UPDATE/DELETE

No write query may be written or run until every row below is checked. You (the builder) own rows 1–2; a human approver (you in a separate deliberate pass, or a teammate) owns rows 3–5. AI proposes syntax only — it approves nothing.

# | Check                              | Who              | What to confirm
--+------------------------------------+------------------+------------------------------------------
1 | Candidate SELECT reviewed          | Builder (you)    | SELECT shows exactly the rows the change
  |                                    |                  | would touch; every filter matches the
  |                                    |                  | written definition of "correct."
2 | Count + 5-row sample matches       | Builder (you)    | Row count matches expectation; 5 rows read
  | expectation                        |                  | by eye with no surprises.
3 | Backup or branch confirmed         | Human approver   | Named backup/branch exists and is restorable.
  |                                    |                  | No backup = no write.
4 | Development test passed            | Human approver   | Same statement run in dev/branch first;
  |                                    |                  | post-run SELECT verifies the fix, join counts
  |                                    |                  | show no side effects.
5 | Human decision recorded            | Human approver   | Approver name, date, and exact statement filed
  |                                    |                  | with the migration. Agent never self-approves.

Blocked if any check fails: stay in the green lane (SELECT only). In particular: missing WHERE on an UPDATE/DELETE, unwritten definition of "correct," no backup, or production-first execution each block the write on their own.

Finish line: a QUERY-PLAN.md with all five sections, the review section explicitly blocking any write.

Verify: hand the plan to a fresh AI session — can it reconstruct your question and predict the result shape? If not, the plan is vaguer than you think.

Common failure mode: writing the SELECT and the DELETE in the same session "to save time," letting the write inherit an unreviewed filter. One artifact, one lane: this file stays green until a separate, reviewed change document exists.

Check your understanding

1. Which SQL keywords mark a query as a change rather than a read? 2. What five elements belong in a safe AI SQL prompt, and why does each matter? 3. Why is "clean up the duplicates" dangerous even if the generated SQL runs without errors? 4. Name the six steps of the change workflow in order.

ARTICLE DISCUSSION

JOIN THE
CONVERSATION.

0 COMMENTS

BYEBUY ACCOUNT ACCESS

Sign in

Use your account to save routes and make the catalogue yours.

Enter your email and we’ll send a secure sign-in link and code.

NEW ROUTES ADDED WEEKLY · 9,235 CATALOGUE ENTRIES · BUILD · DEPLOY · QUERY · STACK · SAY BYE TO BUY · NEW ROUTES ADDED WEEKLY · 9,235 CATALOGUE ENTRIES · BUILD · DEPLOY · QUERY · STACK · SAY BYE TO BUY ·