Skip to navigation

sqlc Query Annotations: Align SQL and Generated Types With Claude Code

In short: Find how sqlc query annotations shape generated APIs before Claude Code changes SQL or output settings.

Published 20 min read
On this page

Direct answer

sqlc reads your SQL queries and schema and generates language-specific database code, and query annotations plus configuration decide the shape of what it emits: function names, argument order, result types, and which engine the code targets. A generated function is a function of recorded inputs, so a change to the emitted API belongs in the query, the schema, the annotation, or the emit setting. Editing the generated file is the failure mode this post prevents, because the next generation replaces it. The concrete win is a generated database API you can trace query by query: this function came from that annotation, those parameters came from that SQL. The concrete loss is that generated types compiling is not proof the query behaves correctly against the live database, and an annotation change can reshape the API without any SQL changing at all.

Read the query and its annotation before reading the generated function. The generated code is the last thing to review.

Why a hand-edited query file costs a regeneration

A generated query function has a tempting failure mode. The parameter order looks wrong, or a result type is awkward, and the fastest fix is to edit the emitted file. The edit compiles, tests pass, and it ships. Then someone adds a query and runs generation, and the edit is gone along with whatever reasoning produced it.

Three costs follow. Review time doubles because the hand edit has to be rediscovered after every generation. Correctness risk goes up because an edited generated function can diverge from the SQL it claims to run. Ownership gets blurry because nobody can say whether the generated package is source or output.

Reading the query first reverses all three. The generated function becomes a consequence to confirm rather than a file to patch. The official sqlc documentation describes generation of language-specific database code from SQL queries and schema, and this post stays on the query-to-generated contract. Nothing here turns annotation review into database migration coverage.

What sqlc Generates

sqlc generates functions, argument structs where needed, and row types from the SQL it reads. Each named query in a .sql file becomes a generated function. The package layout, the language, and the database engine are configuration decisions, not per-query ones.

Generated artifact Comes from Shaped by
Query functions Named queries in .sql files Query name, parameters, result columns
Argument parameters Placeholder values in the SQL Column order and types in the query
Result row types Selected columns Column types and nullability
Package structure Configuration Language, output path, engine

Official, F053: sqlc documents generation of language-specific database code from SQL queries and schema, with configuration and query annotations shaping the output. The sqlc pages were not fetched in this pass, so current annotation names and emit options should be verified against the current documentation before relying on a fine detail.

The table works as input map. Every generated artifact traces to a query, a schema, or a configuration value. The trace is the whole review discipline, and it makes a hand edit to generated output visible as a mistake rather than a fix.

Read the sqlc Configuration

Configuration decides the language, the package paths, the database engine, and the emit options. Configuration is the layer that applies to every query at once, which makes it the broadest-reaching and highest-blast-radius input.

bash
version: "2"
sql:
- engine: postgresql
  queries: ./db/queries
  schema: ./db/schema
  gen:
    go:
      package: db
      out: ./db/gen

The review question for configuration is scope. A change here reshapes every generated function, not just the one you are working on. Recording the engine and emit target is part of any review, because the same queries generate different code for different engines.

Config field Decides Blast radius
engine Which SQL dialect the code targets Every query
queries Which files are read Every query in them
schema Which schema defines the types Every generated type
gen.<language>.out Where generated code lands Every generated file path
gen.<language>.package Generated package identity Every file header

Use the table as scope map. The Go module compatibility guide makes the same point for Go modules: a change to a shared surface is a compatibility event for every consumer, and the blast radius is the reason to name it in review.

Inventory Query Annotations

A query annotation is a comment above a named query that tells sqlc how to generate it. The name comes from the annotation, and the generated function signature follows from the query plus the annotation. Because the annotation pages were not fetched in this pass, this post describes the annotation as an input layer and verifies names against the query annotations reference rather than enumerating them as fixed.

bash
-- name: GetOrder :one
SELECT id, status, note FROM orders WHERE id = $1;

-- name: ListOrders :many
SELECT id, status, note FROM orders ORDER BY id;

-- name: UpdateStatus :exec
UPDATE orders SET status = $2 WHERE id = $1;

Each annotation names the query and declares a result shape: one row, many rows, or no rows returned. The generated function follows that declaration. A :one query returns a single row type. A :many query returns a slice. An :exec query returns only an error.

Annotation intent Generated return Review question
Return one row A single row struct and an error Does the query really return at most one?
Return many rows A slice of row structs and an error Is the caller ready for an empty slice?
Execute with no return An error only Does any caller expect rows back?
Custom name The named function Does the name describe the operation?

Derived, F054: Separating query and schema edits from generated output and recording the selected database engine and emit target is an editorial review method. It is a recommendation built on sqlc’s input model, and it is not evidence that generated queries match runtime database behavior.

Every row of the table is per-query contract check. Each row is a decision someone made in a comment. The annotation is the cheapest place to record intent, and it is the layer a reviewer should read before the generated function.

Map SQL Parameters and Results

Parameters and results are where SQL meets the type system. Placeholder values become function arguments in the order they appear, and selected columns become the fields of the result struct. Both mappings are mechanical, which is the point: the generated API is readable if the SQL is readable.

bash
-- name: SearchOrders :many
SELECT id, status FROM orders
WHERE status = $1 AND created_at > $2
ORDER BY created_at DESC
LIMIT $3 OFFSET $4;

The generated function takes four arguments in placeholder order and returns a slice of rows with id and status. The mapping is predictable, and the review question is whether the SQL expresses what the caller needs in the order the caller expects.

SQL element Generated shape Review question
$1, $2, … placeholders Positional function arguments Is argument order obvious at call sites?
Selected columns Result struct fields Are column names readable as field names?
Nullable columns Pointer or optional field Does the caller handle null?
Repeated column names Potential ambiguity Does the row type stay unambiguous?

Approach the table as readability check. A query with eight positional placeholders generates a function with eight positional arguments, and call sites become hard to review. Naming parameters or restructuring the query is the fix that belongs in the SQL, not in the generated function signature. The TypeScript project references guide applies the same rule to build boundaries: fix the input that produces the surface, not the surface.

Review Emit Targets

Emit options decide what the generator writes and how. They are configuration, not per-query decisions, and they shape the generated package as a whole.

Emit concern What it controls Review question
Output package Package identity and import path Do consumers import the expected path?
Generated file set Which files the generator writes Is the generated set what reviewers expect?
Type mappings How column types become language types Are the mappings documented?
Overrides Per-column or per-type replacements Are overrides recorded with reasons?

Type overrides are the emit-side mechanism for the awkward cases. A column that maps to an unhelpful language type can be overridden per column or per type, and the override is a recorded decision rather than a hand edit. The overriding types how-to is the reference for the mechanism, and the datatypes mapping reference documents the default column-type mapping.

Override target What it replaces Review action
A column type The generated field type for that column Confirm the override is intentional
A full type The generated type wherever it appears Confirm every consumer expects it
An import The package a generated file imports Confirm the import resolves

Read the table as a decision inventory. An override is a decision the configuration records, which is what makes it preferable to editing generated output. The NuGet central package management guide makes the same trade for package versions: centralizing a decision makes it visible, and visibility is what makes it reviewable.

Separate Queries from Generated Files

The queries directory is source. The generated package is output. Keeping that separation visible in the repository is what makes generation safe to run.

Path Status Change policy
db/queries/*.sql Source Reviewed like code
db/schema/*.sql Source Reviewed like code
sqlc.yaml Source Reviewed like code
db/gen/ Generated Do not edit; regenerate

The generated directory should read as output at a glance. A package comment, a path convention, or a CI check that fails on hand edits are all ways to make the boundary real. The exact mechanism is a project decision; the boundary is not.

Claude Code’s best practices state the generated-code rule directly: do not edit generated output. The same rule covers generated query functions. The fix for a wrong function is in the query, the annotation, the schema, or the configuration. The C# source generators guide applies the identical discipline to compiler output, and the OpenAPI generator customization guide applies it to generated clients.

Evaluate an Annotation Change

An annotation change is a contract change for the callers of the generated function. Changing a result shape from one row to many, or renaming a query, changes the function signature that call sites compile against.

bash
-- name: GetOrder :many
SELECT id, status FROM orders WHERE id = $1;
# changing :one to :many changes every caller's return handling

The review question is who calls the function. A rename changes every call site. A result-shape change changes how every caller handles the return. Neither is a local edit, and the annotation is where both are recorded.

Annotation change Caller effect Review action
Rename the query Every call site changes Search callers before merging
:one to :many Callers handle a slice Confirm callers updated
:exec to :one Callers gain a return value Confirm callers use it
Parameter added Every call site adds an argument Confirm the SQL needs it

The table works as caller-impact map. A green generation is not the pass condition. The pass condition is that every caller compiles and handles the new shape correctly, and the Claude Code verification guide covers what to ask before accepting that claim.

Query annotation to generated API map

A map of annotations to generated functions is the artifact worth keeping from a review. The map turns a generated-API question into a lookup and makes the query-to-function trace explicit.

Query name Annotation shape Generated function Parameters Returns
GetOrder one GetOrder id one row, error
ListOrders many ListOrders none slice, error
UpdateStatus exec UpdateStatus id, status error
SearchOrders many SearchOrders status, since, limit, offset slice, error

Use the map as a generated-API index. Each row is a query someone can open and read, and the generated function is predictable from the row. The map is also the cheapest way to spot the awkward cases: a function with six positional parameters, or a :one query whose SQL has no uniqueness constraint, both show up as rows worth a second look before they become call-site bugs. Recording the map alongside the schema also makes the engine visible. The same queries generate different code for PostgreSQL and for MySQL, and the engine is a configuration value rather than a per-query one. A map that records the engine records the reason a generated function looks the way it does.

When a query change is really a schema change

A query edit sometimes hides a schema decision. A new column in the SELECT needs a column in the schema. A new placeholder needs a type the schema defines. A result that changes shape may reflect a table that changed, and the generated diff is where that dependency shows up.

Three signals point at a schema change behind a query change. A generated field appears whose type comes from a column the query did not select before. A parameter type changes because the underlying column type changed. A query stops generating because a column it referenced no longer exists. Each is a query symptom with a schema cause.

Query symptom Schema cause Where to fix
New generated field A column the query newly selects Confirm the schema has the column
Parameter type changed The column type changed Fix the schema, then regenerate
Query stops generating A referenced column is gone Fix the schema or the query
Result shape widened A join added a table Confirm the join is intended

Reading the table as a triage aid keeps the schema and the query in one review. A query change that touches the schema is a two-input change, and attributing both halves is what keeps the generated diff honest. The Claude Code database migration safety guide covers the destructive-change risks on the schema side, which annotation review alone does not reach.

Reading a generated function signature

A generated function signature is readable once you know the mapping. Parameters come from placeholders in placeholder order. Results come from the annotation shape and the selected columns. The signature is a projection, and reading it against the query is the check that confirms the projection is faithful.

Three parts of a signature are worth reading deliberately. The parameter list tells you what the caller must supply, in the order the SQL asked for it. The return type tells you what the caller gets back, and whether an empty result is a slice, a zero value, or an error. The error return tells you that the query can fail, which every generated function can.

Signature part Source Reading question
Parameter list Placeholders in the SQL Is the order obvious at call sites?
Return type Annotation shape plus selected columns Does the caller handle the empty case?
Error return The query can fail Does the caller check it?
Package name Configuration Is the import path what consumers expect?

Reading the table as a signature key makes a generated function readable without opening the SQL, which is the point of generating it. The reading questions are also the review questions: a signature that is hard to read at a call site is usually a query that is hard to read, and the fix belongs in the SQL. The Python TypedDict boundaries guide applies the same reading discipline to dictionary-shaped data in Python, where the shape at a boundary is the review unit rather than the individual annotation.

The concrete win, loss, and implication

The concrete win is a generated database API you can trace. When a reviewer asks why a function takes four positional arguments, the answer is a named query with four placeholders and a recorded annotation. An answer like that survives regeneration, because the reasoning lives in the SQL rather than in an emitted file.

The concrete loss is that generated types are a projection of the schema, not a proof of behavior. A query that compiles against the schema and generates cleanly can still be slow, return unexpected rows, or interact badly with transactions. Generated types describe structure. Behavior needs its own evidence.

The practical implication is that the SQL file is the source of truth for the generated API. Teams that review queries and annotations before the generated diff spend less time re-applying lost edits. Teams that patch generated query files keep paying the same cost every time a query is added.

Working with Claude Code on a query change

Give the agent three inputs: the query or annotation you want to change, the commands it may run, and the definition of done. The definition of done excludes editing generated files. Ask for a regeneration against the current queries and a diff review that attributes each change to a query, annotation, schema, or config input.

bash
sqlc generate
# ask for a clean regeneration before reviewing any diff
git diff --stat db/gen
# ask for the generated diff shape, then trace each change

Review the agent’s attribution claim. The agent can read the SQL accurately and still propose editing a generated file, because that is the shortest path to a passing build. Deciding whether a change belongs in the query, the annotation, or the configuration is a design decision, and the reviewer owns it. The Claude Code common workflows cover iterating an edit against a command, and generation is exactly that loop.

A query change that turns into a wide generated diff is worth pausing on. The Claude Code overengineering guide describes that pattern, and a configuration change is one of its triggers. Where the change touches stored schema, the Claude Code database migration safety guide covers the destructive-change risks that annotation review does not.

Evidence map showing that a generated function is a function of the query, its annotation, the schema, and the emit configuration.
Editorial evidence map based on F053 and F054. A sqlc output change should be traced to a query, schema, annotation, or emit setting before the generated file is touched.

Checklist before you accept a generated query diff

Check Pass condition If it fails
Engine recorded The configured engine is named Read the configuration
Emit target recorded Language and output path named Read the gen section
Query change identified The changed query is named Read the queries diff
Annotation change identified Any annotation change is named Read the annotation lines
Schema change identified Any schema change is named Read the schema diff
Config change identified Any emit or override change is named Read the configuration diff
No generated edits Generated directory clean of hand edits Regenerate cleanly
Callers compile Every caller of a changed function type-checks Fix at the query, not the output
No behavior claim Nobody claims generated types prove SQL behavior Add a query test if behavior matters
Workflow from reading the configuration and query annotations through regenerating from committed inputs and attributing each generated change to an input.
Editorial workflow based on F054. The sequence is a review routine; exact annotation names and emit options depend on the sqlc version and engine.

Data gap and future update

The sqlc configuration, query annotations, overriding types, and datatypes references are the sources used here, and the exact annotation names and emit options should be verified against the current documentation before relying on a fine detail. F053 is official in its broad claim and F054 is derived and labeled as an editorial review method.

No query performance measurement, generation-time number, or correctness rate is reported here, because none was measured. A future update quantifying how a query annotation change affects generated file size or compile time for a specific project would need a fixed sqlc version and a measured pass. No such data was collected.

Engine-specific behavior is out of scope beyond what the configuration documents. Whether a given engine supports a SQL construct the same way another does is a property of that engine, and this post does not generalize from one engine’s generated output to another’s. The sqlc datatypes reference is the reference for the column-type mapping per engine.

Tradeoff between a readable generated API traced to queries and annotations and the maintenance cost of keeping annotations and configuration current as queries change.
Editorial tradeoff diagram based on F053 and F054. A recorded annotation makes the generated API predictable; the trade is keeping annotations and config current as the query set grows.

Generated output is a recurring boundary in this batch. OpenAPI Generator Customization, GraphQL Code Generator Client Presets, C# Source Generators, and Protocol Buffer Reserved Fields cover the same input-to-output discipline for other generators.

Schema and compatibility boundaries appear in Go Module Compatibility, TypeScript Project References, and Conan CMakeDeps. Dependency selection appears in pnpm Peer Diagnostics, Gradle Constraints vs Dependencies, and Maven Optional Dependencies.

More from this batch

One AI API Key option for OpenAI-format agents

Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.

OpenAI-format agents have a separate route: One AI API Key offers https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. Free IDs are a different client and request format, not a workaround for Claude Code authentication. Check the free model list before choosing an agent route, or read the quickstart for the request shape.

FAQ

Can I fix an awkward generated function by editing the generated file?

No. The generated file is sqlc output, and the next generation replaces it. The fix belongs in the query, the annotation, the schema, or the configuration that produced the function. Editing the output hides the input problem until regeneration erases the edit.

Does a query that generates cleanly prove the SQL is correct?

No. Generated code compiles against the schema you gave sqlc. Whether the query returns the right rows, performs acceptably, and behaves correctly in a transaction are runtime questions that need their own evidence. Generated types describe structure, not behavior.

How do I tell whether a generated change came from a config change or a query change?

Config changes produce cross-cutting patterns: every function’s package, path, or mapping shifts. Query changes produce local changes tied to one function or one row type. Match the pattern to the input area before proposing a fix.

I renamed a query and half the package stopped compiling. Is that a bug?

Generated code is the consequence. The annotation names the generated function, so a rename changes the function every caller compiles against. Search the call sites and update them, or keep the old name and add the new query alongside it while callers migrate.

What proves an annotation change is complete?

Three conditions. Every generated change traces to a named input, the generated directory contains no hand edits, and every caller of a changed function compiles and handles the new shape. A green generation command alone is not a pass.

More Claude Code troubleshooting

Sources

Control checklist covering engine and emit recording, query and annotation attribution, clean regeneration, and caller compilation.
Editorial control checklist derived from F053 and F054. Passing the checklist shows the generated diff was attributed honestly; it does not prove the query behaves correctly against the live database.
Verdict that reviewing the query and annotation before the generated function keeps the SQL-to-generated-code contract traceable.
Editorial verdict based on F053 and F054. The SQL file is the source of truth for the generated API. Review it first.
More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
Claim $10 credit →