0Pricing
Go Academy · Lesson

CRUD Operations

Create, read, update, delete.

CRUD Operations is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

CRUD with GORM

GORM turns the four basic operations, Create, Read, Update, Delete, into method calls on *gorm.DB. You pass pointers to structs and GORM builds the SQL.

Create

Create inserts a record. After it runs, GORM fills the structs primary key and timestamps from the database.

user := User{Name: "Ada", Email: "ada@example.com"}
result := db.Create(&user)
fmt.Println(user.ID, result.RowsAffected)

Read with First

First fetches the first matching record ordered by primary key. Pass a pointer to receive the result; conditions go as extra arguments.

var user User
db.First(&user, 1)               // by primary key
db.First(&user, "email = ?", "ada@example.com")

Read Many with Find

Find loads multiple rows into a slice. Without conditions it returns all rows; with Where it filters.

var users []User
db.Where("age > ?", 18).Find(&users)

Update

Save updates all fields of a record. Update and Updates change specific columns, which avoids overwriting fields you did not intend to.

db.Model(&user).Update("name", "Ada L.")
db.Model(&user).Updates(User{Name: "Ada", Age: 36})

Zero Value Gotcha

When updating with a struct, GORM ignores zero-value fields (0, false, ""). To update a column to a zero value, pass a map instead of a struct.

db.Model(&user).Updates(map[string]interface{}{"age": 0, "active": false})

Delete

Delete removes a record. If the model has a DeletedAt field, this is a soft delete, setting the timestamp rather than removing the row.

db.Delete(&user, 1)

A Runnable CRUD Simulation

GORM needs a real database, so this runnable example models create, read, update, delete over an in-memory slice to show the lifecycle.

package main

import "fmt"

type User struct {
    ID   int
    Name string
}

func main() {
    var users []User
    next := 1
    // Create
    u := User{ID: next, Name: "Ada"}
    users = append(users, u)
    next++
    // Read
    fmt.Println("read:", users[0])
    // Update
    users[0].Name = "Ada L."
    fmt.Println("updated:", users[0])
    // Delete
    users = users[:0]
    fmt.Println("count after delete:", len(users))
}

Checking Errors

Every GORM call returns a *gorm.DB whose Error field holds any failure. A missing record yields gorm.ErrRecordNotFound on First.

if err := db.First(&user, 99).Error; err == gorm.ErrRecordNotFound {
    fmt.Println("no such user")
}

Method Chaining

GORM uses a chainable builder: db.Where(...).Order(...).Limit(...).Find(&users). Each method narrows the query, and the final method (Find, First) executes it.

Batch Insert

Pass a slice to Create to insert many rows in one statement. CreateInBatches splits very large slices into chunks to stay within limits.

db.Create(&[]User{{Name: "A"}, {Name: "B"}})

Quick Check

Test your CRUD knowledge.

Recap

You learned CRUD operations:

  • Create inserts and back-fills the primary key
  • First and Find read single and multiple rows
  • Save, Update, Updates modify; maps force zero values
  • Delete soft-deletes when DeletedAt exists
  • Check the Error field; chain methods for complex queries

Frequently asked questions

Is the “CRUD Operations” lesson free?

Yes — the full text of “CRUD Operations” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “CRUD Operations”?

Create, read, update, delete. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “CRUD Operations” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Models and AutoMigrate
  2. CRUD Operations
  3. Associations
  4. Hooks and Scopes
← Back to Go Academy