Nov 19, 20268 min read

GORM vs sqlc: Which Go Database Library to Use

How GORM and sqlc model tables, write queries, handle migrations and transactions, and where each one fits in a Go backend on Postgres.

Illustration for GORM vs sqlc: Which Go Database Library to Use

GORM and sqlc are the two Go database libraries that come up most when a Postgres service needs a data layer, and they start from opposite ends. GORM maps Go structs to tables and builds SQL at runtime, while sqlc generates typed Go functions from the SQL you wrote.

The difference shows once the app grows past CRUD, where GORM can produce SQL you only see in logs and sqlc turns optional filters into nullable parameters or near-identical queries.

GORM vs sqlc at a glance

GORMsqlc
ApproachORM: structs and a query builder, SQL generated at runtimeCode generator: SQL files in, typed Go out
Where queries liveGo method chains.sql files with -- name: annotations
Type checkingAt runtime, when the query runsAt generate time, against the schema
Dynamic filtersChain Where calls as neededNullable parameters or separate queries
AssociationsPreload, Joins, hooksWrite the join yourself
MigrationsAutoMigrate for development, or an external toolNone; reads your migration files
DriversPostgres driver built on pgx, plus other SQL dialectsdatabase/sql or native pgx/v5
Learning curveGORM's API and conventionsSQL plus a small YAML config

Versions used here are GORM v1.31 with gorm.io/driver/postgres v1.6 and sqlc v1.31, on Go 1.24 or later.

How does GORM model and query data?

GORM

GORM reads struct fields and tags to decide table and column names, so the model is the schema description. Associations are fields too: an Order with Items []Item gets the items through a foreign key named OrderID by convention.

type Order struct { ID int64 `gorm:"primaryKey"` CustomerID string `gorm:"not null;index:orders_customer_idx,priority:1"` Status string `gorm:"not null;default:pending"` TotalCents int64 `gorm:"not null"` CreatedAt time.Time `gorm:"index:orders_customer_idx,priority:2,sort:desc"` Items []Item } type Item struct { ID int64 `gorm:"primaryKey"` OrderID int64 `gorm:"not null;index"` SKU string Quantity int }

Queries are method chains on *gorm.DB. Creating an order with its items is one call, a conditional update reports how many rows it touched, and Preload fetches the items in a second query rather than one per order:

db, err := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), &gorm.Config{}) if err != nil { log.Fatal(err) } o := Order{CustomerID: "cus_42", TotalCents: 1999, Items: []Item{{SKU: "mug", Quantity: 2}}} if err := db.Create(&o).Error; err != nil { log.Fatal(err) } // Only a pending order becomes paid; RowsAffected is 0 on a second call. res := db.Model(&Order{}). Where("id = ? AND status = ?", o.ID, "pending"). Update("status", "paid") var recent []Order err = db.Preload("Items"). Where("customer_id = ?", "cus_42"). Order("created_at DESC"). Limit(10). Find(&recent).Error

The strength is the filter you do not know in advance. An admin search with optional status, date range and customer fields is a few if statements that add Where calls, and GORM writes one query from whatever was added.

With the SQL decided at runtime, a typo in a column name inside a Where string compiles fine and fails when the query runs, and an association loaded without Preload inside a loop becomes one query per row. AutoMigrate creates missing tables, columns and indexes but does not drop unused columns, which makes it a development convenience, with versioned migrations doing the work in production.

Best fit: CRUD-heavy services with related models and admin screens that filter on many optional fields.

How does sqlc generate Go from SQL?

sqlc

sqlc starts from the schema and the queries, both in SQL. The schema can be the migrations directory you already have, since sqlc parses migration files from golang-migrate, goose and similar tools and ignores the down migrations:

-- migrations/1_create_orders.up.sql CREATE TABLE orders ( id BIGSERIAL PRIMARY KEY, customer_id TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', total_cents BIGINT NOT NULL CHECK (total_cents >= 0), created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX orders_customer_idx ON orders (customer_id, created_at DESC);

Each query gets a name and a result shape, where :one returns a single row, :many a slice and :execrows the number of affected rows:

-- queries.sql -- name: CreateOrder :one INSERT INTO orders (customer_id, total_cents) VALUES ($1, $2) RETURNING *; -- name: ListCustomerOrders :many SELECT * FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT $2; -- name: MarkPaid :execrows UPDATE orders SET status = 'paid' WHERE id = $1 AND status = 'pending';

The config points sqlc at both and picks the driver. With sql_package: "pgx/v5" the generated code runs on a pgx pool directly; leave it out to generate code for database/sql:

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

sqlc generate writes a Queries type with one method per query and a struct per parameter list, and the calling code reads like any other Go:

pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL")) if err != nil { log.Fatal(err) } defer pool.Close() q := db.New(pool) o, err := q.CreateOrder(ctx, db.CreateOrderParams{CustomerID: "cus_42", TotalCents: 1999}) if err != nil { log.Fatal(err) } n, err := q.MarkPaid(ctx, o.ID) // n is 1, and 0 on a second call

A misspelled column or a parameter of the wrong type fails at sqlc generate, before anything compiles, and the SQL that runs in production is exactly the SQL in the file. Optional filters are the weak spot: sqlc has no query builder, so you either use sqlc.narg with WHERE (sqlc.narg('status')::text IS NULL OR status = sqlc.narg('status')) patterns or write one query per filter combination. Joins also come back as flat row structs rather than nested objects.

Best fit: services where queries matter, such as reports, ledgers and hot paths, and teams that would rather review SQL than ORM chains.

How do GORM and sqlc compare on performance?

sqlc adds almost nothing at runtime, since the generated code is a direct call to the driver and a Scan into a struct. GORM builds SQL and maps results through reflection on each call, which costs some CPU and allocations per query; for most APIs the database round trip still dominates. The bigger performance risk with GORM is query shape rather than overhead: missing Preload, SELECT * on wide tables and accidental full updates. With sqlc the query shape is visible in review.

How do migrations and transactions work in each?

Neither tool needs to own the schema, and a common setup keeps numbered SQL migrations, applied by a tool such as golang-migrate or Atlas, and lets sqlc read them while GORM models only describe the tables they touch.

Transactions look similar in both: GORM wraps a function with db.Transaction(func(tx *gorm.DB) error { ... }) and commits when it returns nil. sqlc generates WithTx, which binds the same query methods to a transaction you began yourself:

tx, err := pool.Begin(ctx) if err != nil { return err } defer tx.Rollback(ctx) // no-op after Commit if _, err := q.WithTx(tx).MarkPaid(ctx, orderID); err != nil { return err } return tx.Commit(ctx)

How do you run GORM or sqlc on a managed Postgres?

Encore

Both libraries stop at the query layer, so the database itself, its migrations and its connection settings still have to come from somewhere. Encore is a backend framework with built-in infrastructure, and either library sits on top of the database it provisions: encore run starts Postgres locally and applies the migrations, and a deploy creates RDS or Cloud SQL in your own AWS or GCP account.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create shop --example=hello-world$ cd shop && mkdir -p orders/migrations

For sqlc, point schema at the service's migrations directory and keep the default database/sql output. The database's Stdlib() method returns a *sql.DB, which satisfies the generated DBTX interface:

// orders/orders.go package orders import ( "context" "encore.app/orders/db" "encore.dev/storage/sqldb" ) var ordersDB = sqldb.NewDatabase("orders", sqldb.DatabaseConfig{ Migrations: "./migrations", }) // queries wraps the generated sqlc code around Encore's *sql.DB. var queries = db.New(ordersDB.Stdlib()) type PayResponse struct { Updated bool `json:"updated"` } // Payment status changes stay private: call this from a verified provider // webhook, not from a public checkout route. //encore:api private method=POST path=/orders/:id/pay func Pay(ctx context.Context, id int64) (*PayResponse, error) { n, err := queries.MarkPaid(ctx, id) if err != nil { return nil, err } return &PayResponse{Updated: n == 1}, nil }

For GORM, the same handle goes into the Postgres driver's Conn field inside a service struct, which is the setup the GORM guide uses:

// catalog/catalog.go package catalog import ( "encore.dev/storage/sqldb" "gorm.io/driver/postgres" "gorm.io/gorm" ) var catalogDB = sqldb.NewDatabase("catalog", sqldb.DatabaseConfig{ Migrations: "./migrations", }) //encore:service type Service struct { db *gorm.DB } func initService() (*Service, error) { db, err := gorm.Open(postgres.New(postgres.Config{ Conn: catalogDB.Stdlib(), }), &gorm.Config{}) if err != nil { return nil, err } return &Service{db: db}, nil }

The migrations stay plain SQL files that Encore applies on startup and on deploy, so sqlc reads the schema from the same place the database is built from. Each query also appears in the local trace for the request that made it, which shows the SQL GORM generated.

A coding agent that adds a table writes the migration, regenerates the sqlc code and calls the endpoint against the local Postgres in one change, with the cloud database created from the same declaration on the next deploy.

Best fit: Go services that want GORM or sqlc for queries and a Postgres that runs locally and in their own AWS or GCP account from one declaration.

How to choose between GORM and sqlc

Pick sqlc when the SQL is the part you care about: reporting queries, ledger updates, anything a reviewer should be able to read as SQL, and teams that want schema drift caught before compile. Pick GORM when most of the code is CRUD over related models, admin filters are built at runtime and associations save code. Using both on one *sql.DB is common and works well, with sqlc for the queries that matter and GORM for the long tail.

Frequently asked questions

Is sqlc better than GORM?

No. Neither is better in general. sqlc is the better fit when you want to write plain SQL and have type-safe Go generated from it, with compile-time checks against your schema. GORM is the better fit when most queries are CRUD on related models and you want associations, hooks and a query builder for filters chosen at runtime.

Can I use GORM and sqlc in the same project?

Yes. Both accept a database/sql connection, so one *sql.DB can serve sqlc for hot paths and reports and GORM for admin CRUD. Keep the schema in one place, ideally SQL migration files, so neither tool owns it on its own.

Does sqlc run migrations?

No. sqlc reads your schema, including migration directories written for golang-migrate, goose or dbmate, to type-check queries, but it never applies them. You run migrations with a separate tool or let your platform apply them on deploy.

How do I use sqlc with Encore?

Point sqlc's schema setting at the service's migrations directory, generate code with the default database/sql package, and pass the database's Stdlib() handle to the generated constructor, for example var queries = db.New(ordersDB.Stdlib()). Encore applies the migrations locally under encore run and on deploy.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders