How do I paginate query results using GORM?

To paginate query results using GORM in Go, you can use the `Limit` and `Offset` methods. This allows you to control the number of results returned and to skip a certain number of records, effectively implementing pagination.

GORM, Go, pagination, database, SQL, Limit, Offset, query results
Learn how to implement pagination in your Go applications using GORM to efficiently handle database queries with large datasets.
package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" "log" ) type User struct { gorm.Model Name string Email string } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { log.Fatal(err) } // Create table db.AutoMigrate(&User{}) // Seed some data for i := 0; i < 100; i++ { db.Create(&User{Name: "User #" + strconv.Itoa(i), Email: "user" + strconv.Itoa(i) + "@example.com"}) } // Pagination setup var users []User page := 1 // Current page number pageSize := 10 // Number of records per page // Fetching paginated results db.Offset((page - 1) * pageSize).Limit(pageSize).Find(&users) // Output the users for _, user := range users { log.Println(user.Name, user.Email) } }

GORM Go pagination database SQL Limit Offset query results