Skip to main content

Chapter 21A: Reading the SQL Your Agent Wrote

You wrote the brief. The agent wrote the query. Now the boss is about to read the numbers. Who is the independent path that says the query is correct?

In Chapter 21, you turned a yearly CSV script into a Neon-backed Budget Tracker. The agent wrote the schema. The agent wrote the inserts. The agent wrote the joins. And every time, you verified by reading the output: the row that came back, the count that matched, the error the database threw on a bad reference.

That was the right move while you were learning the substrate. But you are about to hit a wall.

Imagine your boss asks for a report. The agent writes a query, runs it, hands back a clean number. You paste it into a board deck. A week later, finance pulls the same number from the ledger and gets a different answer. You ask the agent why. The agent confidently rewrites the query and gives you a third number.

Asking the same agent that wrote the query whether the query is correct is not independent verification. It is two coats of the same paint.

The fix is not to learn to write SQL. The fix is to learn to read it. A query is short. It is declarative. It says what data to return, not how to compute it. With a small set of patterns and a sharp eye for silent failure modes, you can look at the agent's SQL and tell whether it answers the question the boss actually asked.

This chapter teaches that reading skill. It does not teach you to write queries from scratch. The agent still does the writing. You become the independent path that says go or no-go before the number leaves the room.

Why This Chapter Exists

A context window is transient. A Postgres database is durable. Every fact that matters to the business eventually lands in a system of record, and that system of record is increasingly Postgres. Workers read from it. Workers write to it. Auditors reconstruct what the company did by reading rows.

If the workforce is going to run against that store, somebody on the human side needs to be able to read what gets sent to it. Not the whole production codebase. Just the query the agent generated, the migration the agent proposed, the policy the agent attached to a table. The piece of SQL that decides what the report says.

That is the literacy gap this chapter closes.

What You Will Learn

A reading-level command of the SQL patterns that show up in agent output: SELECT, WHERE, JOIN, GROUP BY, INSERT, UPDATE, DELETE, transactions, constraints, JSONB, vector search, and a glance at EXPLAIN. Not a course. A reading list. Each lesson takes one pattern, shows you the silent failure it produces when the agent gets it wrong, and gives you a verification habit you can apply every time.

Continuity from Chapter 21

Chapter 21 (Substrate)Chapter 21A (Literacy)
Agent builds the databaseAgent writes queries against the database
You verify by reading output rowsYou verify by reading the query and the output
Schema and constraints prevent bad writesReading the query helps you catch wrong reads
Hybrid verification for high stakesReading SQL is a low-cost verification layer for every stake

This chapter does not replace the verification habits from Chapter 21. It adds a second layer above them. You still read output. You still run failure tests. You add a quick read of the query that produced the output, before you trust the number.

Why SQL Is Easier to Read Than You Think

SQL is declarative. You describe what you want, not how to get it. The grammar is small. A surprising amount of business reporting uses the same dozen keywords arranged in slightly different orders. If you can read the sentence "show me all expenses for users in the Food category, grouped by month, ordered by total," you are most of the way to reading the query that produces it.

Reading SQL is closer to reading a recipe than reading a programming language. The keywords name the verbs. The table names name the ingredients. The WHERE clause is the filter at the colander stage. Once you see that, the fog clears fast.

Running Story

You finished the Budget Tracker in Chapter 21. The boss saw the demo and now wants reports. Real ones. Monthly category spend, top spenders, refund anomalies, a quick "who has never logged an expense" cleanup query, and a semantic search across expense descriptions. Each lesson takes one of those requests, asks the agent to write the query, and asks you to read it before approving it.

Same database. Same schema. Same Alice and Bob from Chapter 21. New question every lesson. The job is to be the human who said yes to a correct query and no to a subtly wrong one.

Schema note: Chapter 21 uses normalized category data (category_id linked to categories) and a required description field. When a sample query shows category as a readable value, read it as the report-level category name. If your physical schema stores only category_id, ask the agent to join categories and expose categories.name AS category before running the query. The approval habit is the same: read the filter, scope, join, and meaning before trusting the output.

Chapter Contract

By chapter end, you should be able to answer these five questions:

  1. Why is "ask the agent if its own query is correct" not a verification step?
  2. What are the four silent SQL failures most likely to ship a wrong number to your boss?
  3. What does a LEFT JOIN do that an INNER JOIN does not, and when does that matter?
  4. What is the safe way to read and run an UPDATE or DELETE you are not sure about?
  5. What does a CREATE TABLE statement let you say about the data without writing any application code?

Seven Principles (Compact)

PrincipleChapter 21A Application
P1 Bash is the Keypsql from the terminal to run the query the agent wrote, plus rollback drills
P2 Code as Universal InterfaceSQL is the contract: the same query reads the same rows for every Worker
P3 Verification as Core StepRead the query, predict the rows, run, compare, then approve
P4 Small Reversible DecompositionWrap risky writes in BEGIN; ... ROLLBACK; while you read them
P5 Persisting State in FilesSave approved queries to a reports/ folder so they can be reused safely
P6 Constraints and SafetyThe schema rejects bad writes: read the schema before you trust the read
P7 ObservabilityOutput, row counts, EXPLAIN plans, and your prediction trail

How This Chapter Teaches

Lesson 1 frames the problem and runs a short diagnostic activity. It is not a full PRIMM-AI+ cycle.

Lessons 2 through 7 use the full visible PRIMM-AI+ cycle, adapted for reading queries:

  1. Predict [AI-FREE]: read the query the agent produced and write down which rows you think will come back, plus a confidence score from 1 to 5.
  2. Run: execute the query against your Neon database. Where the query mutates data, wrap it in BEGIN; ... ROLLBACK; so it cannot leave a mark.
  3. Investigate: write your own explanation of why the output matches or differs from your prediction, then ask the agent targeted questions about anything you still cannot account for.
  4. Modify: ask the agent for one small clause change and predict how the output should shift before you run it.
  5. Make [Mastery Gate]: write a business-English brief, ask the agent to produce a query that meets it, then read the query and approve or reject it. You do not write SQL from scratch.

The cycle stays visible. The tasks get sharper.

All examples appear in two tabs where the runtimes differ: Claude Code and OpenCode (with DeepSeek V4 Flash as the cost-friendly default). Everything else, including the queries, the verification steps, and the prediction work, is the same across both.

Lesson Flow

LessonOutcomeFast Visible Win
L1 Why Reading SQL MattersDecide what counts as independent verification of an agent's queryName three silent SQL failures from one paragraph
L2 Reading SELECT and WHERE SafelyRead a filter clause and predict the rows before runningCatch a wrong WHERE on a tenant boundary
L3 Reading JOINs and Spotting Missing RowsTell the difference between an INNER JOIN and a LEFT JOIN by outputFind users who silently vanished from a report
L4 Reading GROUP BY and Aggregate TrapsRead an aggregate query and decide whether the totals mean what they look likeSpot an average that excludes the rows that mattered most
L5 Reading Writes and TransactionsRead an INSERT, UPDATE, or DELETE and rollback-test it before approvingRefuse a destructive UPDATE that is missing a WHERE clause
L6 Reading Constraints and Schema ContractsRead a CREATE TABLE and explain what data the table will refusePredict three bad inserts that the schema will block
L7 Reading Vector Queries and EXPLAIN LightlyRead a JSONB selector, a vector similarity query, and a plan summaryTell the difference between Seq Scan and Index Scan at a glance
L8 Capstone: Approve or Reject the Agent's SQLAct as the human approver across four real reporting requestsApprove two queries, reject two, and write the rejection reasons in plain English

Prerequisites

  • Chapter 21 complete (Neon database, Budget Tracker schema, sample data loaded)
  • Terminal access with psql available, or your Neon SQL Editor open in the browser
  • Your AI coding agent (Claude Code or OpenCode with DeepSeek V4 Flash)
  • No SQL writing experience required: the agent does all the writing

No-Regression Rules

No simplification is allowed to remove:

  • Predict before run on every cycle. If you cannot say what the query should return, you cannot say whether the output is correct.
  • Rollback wrapping for any mutation during practice. BEGIN; ... ROLLBACK; is the seatbelt.
  • Independent reading of the query. You do not let the same agent that wrote the query also be the one that vouches for it.
  • Tenant and date boundary checks on every read. If a query touches a multi-user table, you confirm the filter that scopes the rows.

If a rewrite makes content shorter but drops any of these, it is a regression.

What This Chapter Is Not

This chapter is not a SQL writing course. There are excellent ones already, and the AI handles the writing better than a beginner ever will. This chapter is also not the full System of Record implementation surface. It stops at reading and approval. System-of-record discipline is a separate operating surface: outbox tables, idempotency keys, run-state tables, and Row Level Security policies that make a Postgres database safe to point a fleet of Workers at.

21A gives you the eyes. System-of-record work uses those eyes on more serious database artifacts.

After Chapter 21A

When you finish this chapter, three things change:

  1. You stop accepting agent-produced queries at face value. You read them.
  2. You can read a CREATE TABLE statement and say, in business terms, what the database will and will not accept.
  3. You can tell a destructive UPDATE from a safe one before you run it, and you know how to make the unsafe ones safe.

Start with Lesson 1: Why Reading SQL Matters.