Skip to main content

Ordering and paging

Ordering takes field pointers, so a request can't inject a column name.

Order by a column​

OrderBy and OrderByDesc start an ordering. ThenBy and ThenByDesc add to it.

users, err := db.Users.OrderBy(&Users.Age).ThenByDesc(&Users.Name).All(ctx)
// SELECT ... FROM "users" ORDER BY "users"."age", "users"."name" DESC

ThenBy without an ordering before it returns ant.ErrThenWithoutOrder.

Order by an expression or place NULLs​

Order takes terms built from expressions, for case-insensitive sorts and NULL placement.

users, err := db.Users.
Order(
ant.Col(&Users.Bio).Asc().NullsLast(),
ant.Lower(&Users.Name).Desc(),
).
All(ctx)
// SELECT ... FROM "users" ORDER BY "users"."bio" NULLS LAST, LOWER("users"."name") DESC

Newest, oldest, random​

newest, err := db.Users.Query().Latest(&Users.CreatedAt).First(ctx)
// SELECT ... FROM "users" ORDER BY "users"."created_at" DESC LIMIT $1

oldest, err := db.Users.Query().Oldest(&Users.CreatedAt).First(ctx)
// SELECT ... FROM "users" ORDER BY "users"."created_at" LIMIT $1

shuffled, err := db.Users.Query().OrderByRandom().All(ctx)
// SELECT ... FROM "users" ORDER BY RANDOM()

ClearOrder removes an ordering.

plain, err := db.Users.OrderBy(&Users.Name).ClearOrder().All(ctx)

Limit and offset​

users, err := db.Users.OrderBy(&Users.Name).Limit(10).Offset(20).All(ctx)
// SELECT ... FROM "users" ORDER BY "users"."name" LIMIT $1 OFFSET $2 -- $1 = 10, $2 = 20

Without an ordering, the database picks which rows Offset skips. A negative Limit or Offset is an error at the terminal call on every database, where SQLite would read LIMIT -1 as no limit.

Page, Chunk and ChunkByKey read inside a Limit and Offset the query already has, so a shared Limit(1000) query chunks those 1000 rows and no more, and Page counts its Total within them too.

Numbered pages​

Page returns the rows plus totals. Pages count from 1. A page past the end has empty Items and the right Total. A page or size below 1 is an error.

page, err := db.Users.OrderBy(&Users.Name).Page(ctx, 2, 10)
// SELECT COUNT(*) FROM "users"
// SELECT ... FROM "users" ORDER BY "users"."name" LIMIT $1 OFFSET $2 -- $1 = 10, $2 = 10
if err != nil {
return err
}

fmt.Println(page.Items) // this page's rows
fmt.Println(page.Total) // rows in all
fmt.Println(page.Pages()) // pages in all
fmt.Println(page.HasNext()) // is there another?

Order the query, or pages may overlap. The count ignores the ordering. Counting and skipping rows gets slow on large tables; use a cursor there.

Cursors for infinite scroll​

After pages by position in the ordering. Every page costs the same however deep it goes, and rows added meanwhile don't shift pages. Pass "" for the first page. Hand Next to the client and take it back as the cursor.

query := db.Users.OrderBy(&Users.Name)

page, err := query.After(ctx, "", 20)
// SELECT ... FROM "users" ORDER BY "users"."name", "users"."id" LIMIT $1 -- $1 = 21

next, err := query.After(ctx, page.Next, 20)
// SELECT ... FROM "users"
// WHERE (("users"."name" > $1) OR ("users"."name" = $2 AND "users"."id" > $3))
// ORDER BY "users"."name", "users"."id" LIMIT $4

After asks for one row more than the page size to detect another page. Next is empty on the last page. The key is added to the ordering as a tie-breaker, so no row is lost at a page boundary. With no ordering it pages by key.

The ordering must use plain columns of this table that cannot hold NULL: no pointer or sql.Null field, unless its column is configured NotNull. Anything else returns ant.ErrCursor before reading a row, because no seek comparison matches NULL and the pages would end where the NULL rows begin. A query with its own Limit or Offset is ant.ErrCursor too, since a cursor has no count of the rows before it, and so is a tampered cursor. After reads the key and the ordering columns even when Column or Omit left them out.

func listUsers(w http.ResponseWriter, r *http.Request) {
page, err := db.Users.OrderByDesc(&Users.CreatedAt).After(r.Context(), r.URL.Query().Get("cursor"), 20)
if errors.Is(err, ant.ErrCursor) {
http.Error(w, "bad cursor", http.StatusBadRequest)

return
}

// write page.Items and page.Next as JSON
}

Process everything in batches​

Chunk reads a large result in groups, holding one in memory at a time. Include works per group, and returning an error stops it. A size below 1 is an error.

err := db.Users.OrderBy(&Users.Name).Chunk(ctx, 500, func(users []*User) error {
return send(users)
})
// SELECT ... FROM "users" ORDER BY "users"."name" LIMIT $1 OFFSET $2 -- 500, 0
// SELECT ... FROM "users" ORDER BY "users"."name" LIMIT $1 OFFSET $2 -- 500, 500
// ... until a group comes back short

On a tracking context, Chunk releases the tracker before it calls your function, so the function can query the same context. See one tracking context, one operation at a time.

Changing rows while you read​

Chunk pages by offset, so deleting rows in the callback makes it skip others. ChunkByKey keeps its place by key, in key order, so the callback can change or delete what it reads.

err := db.Users.Where(ant.Gt(&Users.Age, 100)).ChunkByKey(ctx, 500, func(users []*User) error {
for _, user := range users {
if err := db.Users.DeleteByID(ctx, user.ID); err != nil {
return err
}
}

return nil
})
// SELECT ... FROM "users" WHERE "users"."age" > $1 ORDER BY "users"."id" LIMIT $2
// SELECT ... FROM "users" WHERE "users"."age" > $1 AND "users"."id" > $2 ORDER BY "users"."id" LIMIT $3

ChunkByKey reads the key even when Column or Omit left it out. A composite key is paged by the whole key, as After pages, and a model without a primary key returns ant.ErrNoKey.

Which one​

You needUse
Page numbers in a small tablePage
An infinite scroll or a public APIAfter
To process everything in batchesChunk, or ChunkByKey if you change rows
To stream without batchesEach