One thing I've been exploring after GopherCon Africa 2026 is how Go developers work with databases. That's where I came across sqlc, a tool that makes writing database code in Go a little more interesting.
So, what does it actually do?
What is sqlc?
When building an application, you might write SQL queries to fetch or insert data into a database. You then need Go code to execute those queries and work with the results.
Usually, this means writing some extra code to connect the two.
sqlc generates Go code from your SQL queries, allowing you to write the SQL yourself while getting generated Go functions with defined types.
In simple terms, you write the query, and sqlc helps handle the Go code around it.
How does it work?
Imagine we're building an application that stores information about farmers.
We might have a farmers table and want to retrieve a farmer using their ID.
First, we write the SQL query:
-- name: GetFarmer :one
SELECT id, name
FROM farmers
WHERE id = ?;
The comment tells sqlc how to name the generated function and indicates that the query should return one row.
After configuring sqlc and running its code-generation command, it generates Go code that lets us call the query through a function rather than writing all the database-access code ourselves.
For example, the generated function might be used like this:
farmer, err := queries.GetFarmer(ctx, farmerID)
if err != nil {
return err
}
fmt.Println(farmer.Name)
This is an illustrative usage example; the exact function signature depends on your database driver and sqlc configuration.
Why would you use it?
A few things make sqlc useful:
Type safety: Generated code uses Go types for query parameters and results, helping catch certain mistakes at compile time.
Less repetitive code: You can spend less time manually writing code to scan database results into Go values.
SQL stays readable: You write and maintain your queries directly instead of hiding them behind an abstraction.
Of course, sqlc doesn't eliminate every possible database error. A query can still fail at runtime, and you still need to design your database and write correct SQL.
My takeaway
What I find interesting about tools like sqlc is how they help connect two things developers work with regularly: SQL and Go.
Instead of choosing between writing SQL yourself and having convenient Go code to work with its results, sqlc lets you do both.
I'm still exploring the Go ecosystem, and it's interesting discovering the tools that make everyday development a little easier.
Have you ever used sqlc in a Go project, or do you prefer writing your database-access code manually?
Top comments (0)