Install GORM and a database driver
Install the GORM core library:Then install a driver for your database. This quickstart uses SQLite, which requires no server to run.
SQLite is ideal for local development and testing. For production workloads, use MySQL, PostgreSQL, or SQL Server. See Connecting to a database for driver-specific DSN formats and configuration.
Define a model
A GORM model is a Go struct whose fields map to database columns. Embed GORM uses the struct name to derive the table name (
gorm.Model to automatically get ID, CreatedAt, UpdatedAt, and DeletedAt fields.products for Product) and uses conventional field names for primary keys and timestamps.Connect to a database
Use
gorm.Open to initialize a database connection. Pass a dialector and an optional *gorm.Config.gorm.Open returns a *gorm.DB instance and an error. The *gorm.DB is safe for concurrent use and should be shared across your application — do not create a new instance per request.Run AutoMigrate
AutoMigrate creates the table if it does not exist, and adds any missing columns or indexes. It never drops columns or modifies existing column types.AutoMigrate is designed for development and CI environments. For production schema changes, prefer versioned migration tools such as golang-migrate or Atlas.Create records
Pass a pointer to your model to To insert multiple records in one call, pass a slice:
db.Create. GORM sets the primary key and timestamps on the struct after the insert.Read records
Find the first record ordered by primary key:Find all records matching a condition:
First raises gorm.ErrRecordNotFound when no record matches. Use errors.Is(result.Error, gorm.ErrRecordNotFound) to check. Find does not return an error for empty results — it returns an empty slice.Update records
Update a single column with Update multiple columns with
Update:Updates. Pass a struct (only non-zero fields are updated) or a map[string]interface{} (all keys are updated):Complete working example
The following program ties all the steps together and runs against a local SQLite file:Next steps
Connecting to a database
Configure MySQL, PostgreSQL, SQLite, and SQL Server with real DSN examples and connection pool settings.
Declaring models
Define models with custom column names, data types, constraints, and embedded structs.
CRUD: Create
Batch inserts, upserts, hooks, and creating with associations.
CRUD: Query
Where conditions, ordering, pagination, preloading associations, and raw SQL.