sqlc: SQL first, Go generated
Write SQL, generate typed Go: the sqlc config, query annotations, sqlc.arg and sqlc.slice, the types it picks, WithTx, and wiring handler, service and queries without a framework.
Learning outcomes
- Configure sqlc to read the golang-migrate files and generate internal/db.
- Annotate queries with :one, :many and :exec, and name parameters with sqlc.arg.
- Pass a variable-length list of ids with sqlc.slice.
- Predict the Go types sqlc picks, including DECIMAL as string.
- Split a feature into handler and service, inject the queries through a narrow interface, and wire it in main.go.
Why SQL-first development?
In the previous lesson, you learned how Go communicates with MySQL through database/sql. You now have a connection pool, understand how to execute queries, and know how to manage contexts and timeouts.
However, writing every SQL query manually inside Go code introduces a problem: your database schema and application code can gradually become inconsistent.
Consider a restaurant listing query. You write SQL, manually create a struct for its results, scan every column, handle nullable values, and keep the Go types aligned with the database.
Now imagine changing a column or adding another query. You have to maintain all of that mapping yourself.
sqlc automates this repetitive work.
It takes your SQL queries and database schema as input and generates type-safe Go code for executing those queries.
The philosophy is simple:
You write SQL. sqlc generates the Go code. You own the query logic, while the generator handles the repetitive database access code.
This is particularly useful for your food-ordering backend because its queries involve multiple related tables, filters, pagination, and response assembly.
How sqlc works
sqlc uses two main inputs:
- Your database schema, describing tables, columns, keys and relationships.
- Your query files, containing named SQL queries.
It analyses both and generates Go methods with appropriate parameter and result types.
For example, suppose you write:
-- name: GetRestaurant :one
SELECT id, name, lat, lng
FROM restaurants
WHERE id = ?;sqlc understands that:
- The query expects one restaurant ID.
- The result contains an ID, name, latitude and longitude.
- The query returns at most one row.
It generates a Go method that accepts a context and an identifier and returns a typed restaurant structure.
You don't write the corresponding QueryRowContext and Scan code yourself.
Your sqlc configuration
You're using sqlc v1.31.1.
The configuration lives at:
backend/sqlc.yaml
version: "2"
sql:
- engine: "mysql"
schema: "db/migrations"
queries: "db/queries"
gen:
go:
package: "db"
out: "internal/db"
emit_json_tags: true
emit_interface: true
emit_empty_slices: trueLet's understand each setting.
| Setting | Purpose |
|---|---|
version: "2" | Uses sqlc's version 2 configuration format |
engine: "mysql" | Parses queries using MySQL SQL semantics |
schema | Directory containing your schema migrations |
queries | Directory containing your SQL query files |
package | Name of the generated Go package |
out | Output directory for generated code |
emit_json_tags | Adds JSON tags to generated structs |
emit_interface | Generates a Querier interface |
emit_empty_slices | Returns initialized empty slices rather than nil slices for empty list results |
An important detail is that sqlc reads the schema from your migration files.
It understands golang-migrate's .up.sql files and ignores .down.sql files.
You don't need a separate manually maintained schema definition.
This gives you one source of truth for the database structure: the migrations you wrote in module 1.
Generated file structure
After running sqlc generate, your output looks like:
backend/db/migrations/0001_restaurants.up.sql
backend/db/migrations/0001_restaurants.down.sql
backend/db/queries/restaurants.sql
backend/db/queries/menu.sql
backend/internal/db/db.go
backend/internal/db/models.go
backend/internal/db/querier.go
backend/internal/db/restaurants.sql.go
backend/internal/db/menu.sql.go
backend/sqlc.yamlThe generated files have different responsibilities.
db.go
Contains:
- The
DBTXinterface. New(db DBTX) *Queries.- The
Queriesstructure. WithTxfor binding queries to a transaction.
models.go
Contains generated Go structures corresponding to your database tables.
For example, you get structures representing:
- Restaurant.
- Item.
- ItemSize.
- OptionGroup.
- Option.
- OptionPrice.
querier.go
Contains the generated Querier interface.
Because emit_interface is enabled, sqlc generates an interface describing the available query methods.
restaurants.sql.go
Contains the generated Go implementations for queries defined in restaurants.sql.
Each query file produces its corresponding generated Go file.
Understanding generated Go types
One of the biggest advantages of sqlc is that it understands the schema and maps database types to Go types.
For your Week 2 schema, sqlc v1.31.1 produces these mappings:
| MySQL type | Generated Go type |
|---|---|
| BIGINT UNSIGNED | uint64 |
| DECIMAL(9,6) | string |
| TINYINT(1) | bool |
| INT UNSIGNED | uint32 |
| VARCHAR | string |
| DATETIME(3) | time.Time |
| Nullable VARCHAR | sql.NullString |
| Nullable BIGINT | sql.NullInt64 |
These mappings are important because you don't have to manually decide how every database value should be scanned.
Why does DECIMAL become string?
Notice that DECIMAL(9,6) becomes a Go string, not float64.
This is intentional.
A floating-point number cannot represent every decimal fraction exactly. Converting a database decimal into a floating-point value can introduce rounding differences.
Returning it as a string preserves its exact decimal representation.
For example:
Database: 12.935200
Generated Go value: "12.935200"If you need to perform approximate geographic calculations, you can convert it explicitly:
lat, err := strconv.ParseFloat(restaurant.Lat, 64)
if err != nil {
return err
}The conversion makes the precision trade-off explicit rather than silently introducing floating-point behaviour into every database operation.
Nullable columns
Suppose a database column allows NULL:
restaurant_id BIGINT UNSIGNED NULLA query returning this column needs a Go representation capable of expressing both an integer value and the absence of a value.
sqlc can generate sql.NullInt64 or another suitable nullable type depending on the schema and query.
For example:
if restaurant.RestaurantID.Valid {
id := restaurant.RestaurantID.Int64
}Don't assume that a nullable database field will always map to an ordinary Go integer or string.
Writing queries with sqlc
Your SQL belongs in backend/db/queries.
Start with restaurant queries in:
backend/db/queries/restaurants.sql
Named queries
Every query needs a sqlc annotation describing its name and expected result.
The syntax is:
-- name: QueryName :resultTypeThere are four commonly used result types:
| Annotation | Meaning |
|---|---|
:one | Returns one row |
:many | Returns multiple rows |
:exec | Executes a statement without returning a result |
:execresult | Executes a statement and returns sql.Result information |
For example:
-- name: GetRestaurant :one
SELECT id, name, lat, lng
FROM restaurants
WHERE id = ?;
-- name: ListRestaurants :many
SELECT id, name, lat, lng
FROM restaurants
WHERE is_active = 1
ORDER BY id;
-- name: DeleteRestaurant :exec
DELETE FROM restaurants
WHERE id = ?;
-- name: CreateRestaurant :execresult
INSERT INTO restaurants (name, lat, lng)
VALUES (?, ?, ?);sqlc uses these annotations to generate appropriately typed Go methods.
Notice that you still write ordinary SQL. sqlc does not hide the query behind a custom query builder.
Named arguments with sqlc.arg
Positional placeholders are useful, but queries with multiple filters can become difficult to read.
Consider your restaurant-listing endpoint.
You need a minimum and maximum latitude, minimum and maximum longitude, a cursor, and a limit.
You can assign meaningful names to parameters using sqlc.arg.
-- name: ListRestaurantsNear :many
SELECT id, name, lat, lng
FROM restaurants
WHERE is_active = 1
AND lat BETWEEN sqlc.arg(min_lat) AND sqlc.arg(max_lat)
AND lng BETWEEN sqlc.arg(min_lng) AND sqlc.arg(max_lng)
AND id > sqlc.arg(after_id)
ORDER BY id
LIMIT ?;Each named argument becomes a field in a generated parameter structure.
sqlc v1.31.1 generates:
type ListRestaurantsNearParams struct {
MinLat string
MaxLat string
MinLng string
MaxLng string
AfterID uint64
Limit int32
}It also generates a method equivalent to:
func (q *Queries) ListRestaurantsNear(
ctx context.Context,
arg ListRestaurantsNearParams,
) ([]ListRestaurantsNearRow, error)You can now call the query using an explicitly typed parameter object:
restaurants, err := queries.ListRestaurantsNear(
ctx,
db.ListRestaurantsNearParams{
MinLat: "12.900000",
MaxLat: "13.100000",
MinLng: "77.500000",
MaxLng: "77.800000",
AfterID: 100,
Limit: 20,
},
)The generated method handles parameter binding, row iteration and scanning.
You don't need to write those operations manually.
Handling IN clauses with sqlc.slice
A common problem with SQL queries is selecting rows using a variable-length list of IDs.
Suppose you need the sizes of multiple menu items.
You might have:
itemIDs := []uint64{10, 11, 12}A single SQL placeholder does not automatically expand this slice into multiple values.
sqlc provides sqlc.slice for this purpose.
-- name: ListSizesByItemIDs :many
SELECT item_id, size, price_paise
FROM item_sizes
WHERE item_id IN (sqlc.slice(item_ids));This generates a method with the signature:
func (q *Queries) ListSizesByItemIDs(
ctx context.Context,
itemIds []uint64,
) ([]ItemSize, error)At runtime, sqlc expands the slice into the required number of placeholders and supplies the corresponding values.
For three IDs, the resulting SQL uses the equivalent of:
WHERE item_id IN (?, ?, ?)You still get parameterized SQL rather than interpolating values into the query string.
An empty IN () is a syntax error in MySQL, so sqlc handles that case too: with an empty slice it rewrites the clause to IN (NULL), which matches nothing, and you get an empty result. It still costs a round trip, so when a restaurant has no items, skip the follow-up queries in your service instead of sending queries that cannot match.
Understanding DBTX and WithTx
Open the generated internal/db/db.go.
You'll find an interface called DBTX.
Conceptually, it describes the database operations that generated queries need:
type DBTX interface {
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
PrepareContext(context.Context, string) (*sql.Stmt, error)
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
}Both *sql.DB and *sql.Tx implement this interface.
This is what makes the generated query layer flexible.
When you construct your application:
queries := db.New(sqlDB)The generated Queries object uses the connection pool.
When you need transactional queries, the same query set can be bound to a transaction:
tx, err := sqlDB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
txQueries := queries.WithTx(tx)You can now execute generated query methods using txQueries.
Because its underlying DBTX is the transaction, the operations participate in the same database transaction.
After all operations succeed, commit the transaction.
This means you don't need a separate implementation of your SQL queries just because they need to execute inside a transaction.
The transaction lifecycle will become particularly important when implementing order creation in Week 3.
Package layout and dependency injection
Now that sqlc generates your database layer, you need to decide how the rest of the application should use it.
Avoid putting all your SQL queries, HTTP handlers, validation logic and business rules into main.go.
Instead, organise the application around features.
For example:
backend/cmd/api/main.go
backend/db/migrations/
backend/db/queries/
backend/internal/db/db.go
backend/internal/db/models.go
backend/internal/db/querier.go
backend/internal/db/restaurants.sql.go
backend/internal/restaurant/handler.go
backend/internal/restaurant/service.goThe responsibilities are:
internal/db
Generated database code. It knows how to execute SQL and map results to Go types.
internal/restaurant/handler.go
HTTP responsibilities:
- Parse route parameters and query parameters.
- Validate incoming requests.
- Call the service.
- Map errors to HTTP status codes.
- Write JSON responses.
internal/restaurant/service.go
Application logic:
- Decide which database operations are needed.
- Coordinate multiple queries.
- Apply business rules.
- Return results or meaningful errors.
cmd/api/main.go
Application composition:
- Initialise MySQL.
- Construct sqlc queries.
- Construct services and handlers.
- Register routes.
- Start the HTTP server.
What is dependency injection?
Dependency injection means providing a component with the dependencies it needs instead of letting it create or discover those dependencies itself.
For example, your restaurant service needs database queries.
Instead of opening its own MySQL connection, it receives an interface describing the queries it needs.
package restaurant
import (
"context"
"github.com/yashdagar/zomato-prep/backend/internal/db"
)
type queryStore interface {
ListRestaurantsNear(
context.Context,
db.ListRestaurantsNearParams,
) ([]db.ListRestaurantsNearRow, error)
}
type Service struct {
queries queryStore
}
func NewService(queries queryStore) *Service {
return &Service{queries: queries}
}Notice that the interface contains only the query this service needs.
You don't need to depend on every generated query in the application.
Because Go interfaces are satisfied implicitly, *db.Queries automatically satisfies this interface as long as it provides the required method.
You can also create a fake implementation in tests that returns predetermined results without connecting to MySQL.
This makes the service easier to test in isolation.
The HTTP handler then receives the service:
type Handler struct {
service *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{service: service}
}The handler does not need to know whether the service uses sqlc, a fake implementation, or some other data source.
Wiring everything in main.go
Your main.go becomes the place where dependencies are constructed and connected.
sqlDB, err := database.Open(ctx, os.Getenv("MYSQL_DSN"))
if err != nil {
log.Fatal(err)
}
defer sqlDB.Close()
queries := db.New(sqlDB)
restaurantService := restaurant.NewService(queries)
restaurantHandler := restaurant.NewHandler(restaurantService)Finally, mount the routes:
r.Route("/v1/restaurants", func(r chi.Router) {
r.Get("/", restaurantHandler.List)
r.Get("/{id}", restaurantHandler.Get)
})The dependency graph is:


There is no need for a dependency-injection framework.
Go constructors and interfaces are sufficient for this application.
Also remember the context convention from Lesson 2.4: functions performing I/O receive context.Context as their first parameter. Never store a request context inside a service, handler or repository struct.
Keeping generated code in sync
You will commit generated code into the repository.
This is deliberate.
Someone cloning the project should be able to build it without independently installing sqlc and regenerating files before every build.
However, committing generated files introduces a consistency requirement.
Whenever you modify a migration or query file, regenerate the code:
sqlc generateYou should also run:
sqlc compile
sqlc vetsqlc compile checks that the schema and every query parse and type-check, without writing any files, so it is the quick check after editing a query.
sqlc vet runs lint rules that you add under a rules section in sqlc.yaml; with no rules configured it only does the same parsing as compile. This course does not add rules.
CI drift detection
Your CI must ensure that committed generated files correspond to the current schema and query files.
The process is:
- Check out the repository.
- Install the pinned sqlc version, v1.31.1.
- Run
sqlc generate. - Check whether Git reports any changes.
The important command is:
git diff --exit-codeIf regeneration changes committed files, the command exits unsuccessfully.
This means someone changed a query or migration but forgot to commit the resulting generated code.
Knowledge assessment
Why does sqlc generate typed Go methods from SQL files instead of requiring developers to construct queries through a Go query builder?
Practical applications
Exercise 2.6: Generate the restaurant and menu queries
You'll create the SQL query files for restaurants, items, sizes, option groups, options and option prices.
You'll configure sqlc using the existing MySQL migrations, generate the Go package, and inspect the generated types, parameter structures, query methods and interfaces.
You'll also verify that queries use the expected types and that generated code remains up to date.
Exercise 2.7: Seed 50 restaurants and one full menu
You'll write a seed command that fills the restaurant and menu tables with database/sql directly, inside one transaction. Inserts like these do not need generated queries; the read queries from 2.6 are what the API uses.
This will give you realistic data for subsequent API exercises.
Modules 3 and 4: Restaurant and menu endpoints
Your HTTP handlers will call feature services, which will coordinate generated sqlc queries.
The restaurant listing endpoint will reuse the generated pagination query, while the menu endpoint will retrieve related menu data using generated methods.
Later, the same query architecture will support order creation, order history, and transactional state transitions.
By the end of this module, you should understand the entire path from SQL written by you to typed Go methods called by your application.
References
Everything above is explained on this page; these are where it comes from (sqlc v1.31.1, MySQL 8.4).