Go sqlc vs GORM: Which Should You Use?

Updated 9 min read
Go sqlc vs GORM featured image: cards for sqlc, GORM and choosing between them

Go sqlc vs GORM is one of the first big choices you face when a Go service needs a database. In this post, you will learn how each tool works and what code you write with it. Also, you will see where each one shines. Then we will build the same small book store twice, so you can compare them side by side.

This lesson builds directly on Go PostgreSQL with pgx, where we wrote every query by hand. It also uses the schema from Go database migrations. So if those feel new, read them first.

What Is the Go sqlc vs GORM Choice About?

Both tools save you from writing the same database code again and again. However, they come from opposite directions, which is why the Go sqlc vs GORM debate never ends.

In short, sqlc is a code generator. So you write plain SQL queries, and then sqlc generates type-safe Go functions from them. GORM, on the other hand, is an ORM, which means Object Relational Mapper. Instead of SQL, you work with Go structs and methods, while GORM writes the SQL for you at run time.

For example, think of ordering at a restaurant. With sqlc, you write the exact recipe, and a helper turns it into a neat order card. With GORM, you point at a picture on the menu, and the kitchen decides how to cook it. Both get you dinner. Still, the level of control is very different.

Why the Go sqlc vs GORM Decision Matters

In fact, your data layer touches almost every feature. As a result, changing tools later is expensive. Specifically, here is what the choice affects.

  • Speed of writing code: one tool needs less typing for simple CRUD.
  • Performance: one tool runs exactly your SQL, while the other builds SQL for you.
  • Safety: one tool catches query mistakes at build time instead of in production.
  • Team skills: SQL experts and ORM fans feel at home with different tools.
  • Hard queries: reports, joins and window functions are easier in one of them.

In short, the Go sqlc vs GORM decision shapes how you write, test and debug data access for years.

Go sqlc vs GORM: How sqlc Works

First, you write schema.sql and query.sql files. Next, you add a short name and a result type to each query as a comment. Then you run sqlc generate. Finally, sqlc writes Go structs and methods that call your exact SQL.

Go sqlc vs GORM diagram showing sqlc generating code at build time and GORM building SQL at run time
sqlc reads your schema and SQL queries at build time and generates type-safe Go code, while GORM builds SQL from your structs at run time.

Because sqlc checks your queries against the schema, a typo such as a wrong column name fails during sqlc generate. So the mistake never reaches production.

Go sqlc vs GORM: How GORM Works

By contrast, GORM works the other way round. First, you describe a table as a Go struct. Then you call methods such as Create, First and Where. Finally, GORM turns each call into SQL at run time and fills your structs with the results.

Also, GORM can create tables from your structs with AutoMigrate. That is handy for demos. However, for real projects we still prefer the SQL migrations from the previous post.

Key Parts of Each Tool

For example, this table lists the parts you work with every day in each tool.

PartsqlcGORM
Where queries livequery.sql filesGo method calls
How tables are describedschema.sql or migrationsGo structs with tags
Main commandsqlc generateNone, it is a library
Result typesGenerated structsYour own structs
Not found errorpgx.ErrNoRowsgorm.ErrRecordNotFound

Go sqlc vs GORM at a Glance

Now for the most important table, which compares the two tools directly.

FeaturesqlcGORM
You writePlain SQLGo method chains
SQL errors caughtAt generate timeAt run time
PerformanceSame as hand-written SQLSmall overhead from reflection
Simple CRUD speedMore files to writeVery fast to write
Complex queriesEasy, it is just SQLPossible, but often raw SQL anyway
Learning curveNeed to know SQL wellNeed to learn GORM rules
Go sqlc vs GORM diagram comparing how you write queries, errors, performance and learning curve
sqlc favours control, compile-time checks and raw speed, while GORM favours quick CRUD and less SQL to write.

So when should you use which? Choose sqlc when your team is comfortable with SQL and you care about performance and safety. On the other hand, choose GORM for quick prototypes or admin tools with mostly simple CRUD.

Hands-On: The Book Store with sqlc

Let’s start the Go sqlc vs GORM test with sqlc. We use the books table from the migrations post, with id, title, author and price columns.

Step 1: Configure sqlc

First, install sqlc with go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest. Then create sqlc.yaml in the project root.

version: "2"
sql:
  - engine: "postgresql"
    schema: "db/migrations"
    queries: "query.sql"
    gen:
      go:
        package: "db"
        out: "internal/db"
        sql_package: "pgx/v5"

Here, schema points at the migrations folder, so sqlc always sees the real tables. Also, sql_package: "pgx/v5" makes the generated code use pgx, just like our previous lessons.

Step 2: Write the Queries

Next, write query.sql. Here, each comment gives the method name and how many rows it returns.

-- name: CreateBook :one
INSERT INTO books (title, author, price)
VALUES ($1, $2, $3)
RETURNING *;

-- name: GetBook :one
SELECT * FROM books WHERE id = $1;

-- name: ListBooksByAuthor :many
SELECT * FROM books WHERE author = $1 ORDER BY id;

-- name: DeleteBook :exec
DELETE FROM books WHERE id = $1;

Here, :one returns one row, :many returns a slice and :exec returns only an error. Then run sqlc generate, and the folder internal/db appears with a Book struct and one method per query.

Step 3: Use the Generated Code

As a result, the Go code is short, and every argument has the right type.

pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
	log.Fatal(err)
}
defer pool.Close()
q := db.New(pool)

book, err := q.CreateBook(ctx, db.CreateBookParams{
	Title: "Go Basics", Author: "Asha", Price: 499,
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("created:", book.ID, book.Title)

books, err := q.ListBooksByAuthor(ctx, "Asha")
if err != nil {
	log.Fatal(err)
}
fmt.Println("Asha has", len(books), "book(s)")

_, err = q.GetBook(ctx, 99)
if errors.Is(err, pgx.ErrNoRows) {
	fmt.Println("book 99 not found")
}

So on an empty table, the program prints the following.

created: 1 Go Basics
Asha has 1 book(s)
book 99 not found

Look at db.CreateBookParams closely. Because sqlc made it from the three $ placeholders, you cannot pass the wrong number of values. Also, the INTEGER price column becomes int32 in the generated struct.

Hands-On: The Same Store with GORM

Now let’s build the same thing with GORM, the other side of Go sqlc vs GORM. First, add it with go get gorm.io/gorm gorm.io/driver/postgres.

type Book struct {
	ID     uint `gorm:"primaryKey"`
	Title  string
	Author string
	Price  int
}

func main() {
	db, err := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}

	book := Book{Title: "Go Basics", Author: "Asha", Price: 499}
	if err := db.Create(&book).Error; err != nil {
		log.Fatal(err)
	}
	fmt.Println("created:", book.ID, book.Title)

	var books []Book
	db.Where("author = ?", "Asha").Order("id").Find(&books)
	fmt.Println("Asha has", len(books), "book(s)")

	var missing Book
	err = db.First(&missing, 99).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		fmt.Println("book 99 not found")
	}
}

The output is the same three lines as the sqlc version, so for simple cases the Go sqlc vs GORM result is identical. However, notice the differences. Create fills book.ID for you after the insert. Also, GORM uses ? placeholders and converts them to $1 for PostgreSQL behind the scenes. Finally, the table name books comes from the struct name Book, because GORM turns it into a plural, lowercase name.

Performance in Practice

sqlc adds almost nothing at run time. Its generated functions call pgx directly with your exact SQL, so they run as fast as hand-written code. Meanwhile, GORM uses reflection to read your structs and builds SQL strings on every call. Therefore, GORM adds a small cost to each query.

For most web apps, that cost is tiny compared with the database round trip itself. However, GORM can hide bigger problems. For example, a loop that loads related records one by one sends many small queries, often called the “N+1” problem. GORM’s Preload fixes it, but you must know to use it. With sqlc, you simply write one SQL query with a JOIN, so the cost is visible in the file.

How to Choose: Go sqlc vs GORM Checklist

Answer these questions honestly, and the right tool usually becomes clear.

  • Is your team comfortable with SQL? If yes, sqlc will feel natural and safe.
  • Do you write many reports or complex joins? Then sqlc wins, because it is just SQL.
  • Is this a quick prototype or an internal admin tool? Then GORM gets you moving faster.
  • Do you care about every millisecond? In that case, prefer sqlc with pgx.
  • Will many beginners touch the code? GORM’s methods may feel friendlier at first.

In short, many Go teams choose sqlc for core services and keep GORM for small side tools.

Common Mistakes in the Go sqlc vs GORM Decision

  • Picking GORM to avoid learning SQL: complex queries still need SQL, and debugging gets harder. So learn basic SQL either way.
  • Forgetting to regenerate with sqlc: Go code then calls old query versions. Run sqlc generate in CI and fail on changes.
  • Ignoring GORM errors: GORM returns errors in .Error, which is easy to skip. Always check it.
  • Using AutoMigrate in production: it never drops or renames columns. Use real migrations instead.
  • Mixing both tools for the same tables: two sources of truth confuse the team. Pick one per service.

Best Practices for Either Tool

  • Keep schema changes in migrations, because both tools then read the same truth.
  • Pass a context to every call, since timeouts protect your service in both tools.
  • Log slow queries, as GORM can hide expensive SQL behind a simple method.
  • Wrap the data layer in an interface, so you can test handlers with fakes, as in Go mocking with interfaces.
  • Review generated SQL or code in pull requests, so surprises surface early.

Practice Task

To feel the Go sqlc vs GORM difference yourself, add an UpdateBookPrice :exec query to query.sql, run sqlc generate and call it. Then do the same change in GORM with db.Model(&book).Update("price", 549).

Hint: compare how many lines each version needs and which one caught your typos first.

Official Resources

These pages are the official docs for both tools, so check them before you decide.

Quick Recap

  • sqlc generates type-safe Go code from SQL you write.
  • GORM is an ORM that builds SQL from Go structs at run time.
  • The Go sqlc vs GORM choice is control and safety versus speed of writing.
  • sqlc catches query mistakes at generate time, while GORM finds them at run time.
  • Both tools work with PostgreSQL and your existing migrations.
  • Pick one tool per service and keep schema changes in migrations.

What’s Next?

However, both tools still hit the database for every request. Next, we will make reads much faster by caching results in Redis.

Next lesson: Go Redis Caching: Speed Up Your API