Skip to Content
fusion-orm
Querying

Order, Limit & Offset

Ordering, pagination, and row locking with golden SQL output.

The chainables

// Order appends an ORDER BY expression (e.g. "name DESC").
func (db *DB) Order(value string) *DB {
	tx := db.getInstance()
	prev, _ := tx.Statement.Clause("order").(clause.OrderBy)
	cols := append(append([]string(nil), prev.Columns...), strings.Split(value, ",")...)
	tx.Statement.AddClause(clause.OrderBy{Columns: cols})
	return tx
}
// Limit caps the number of rows.
func (db *DB) Limit(n int) *DB
// Offset skips rows.
func (db *DB) Offset(n int) *DB
// Locking adds FOR UPDATE when enabled.
func (db *DB) Locking(enabled bool) *DB

Order is additive: each call appends its (comma-split) expressions after whatever is already there, so Order("name").Order("id DESC") sorts by name, then id.

Golden SQL

The canonical example from the test suite chains all three:

fn := func(tx *DB) *DB {
	return tx.Model(&crudUser{}).Where("age > ?", 18).Order("id DESC").Limit(5).Find(&[]crudUser{})
}
first := db.ToSQL(fn)
second := db.ToSQL(fn)
want := `SELECT * FROM "crud_users" WHERE age > 18 ORDER BY id DESC LIMIT 5`
SELECT * FROM "crud_users" WHERE age > 18 ORDER BY id DESC LIMIT 5

The test also asserts first == second: ToSQL is byte-identical across calls, which is what keeps the prepared-statement cache hit rate high.

Pagination

Offset-based pagination composes naturally:

db.Model(&crudUser{}).Order("id").Limit(20).Offset(40).Find(&page)

Both LIMIT and OFFSET bind as variables in the built statement — the rendered SQL is LIMIT ? / OFFSET ? on SQLite and LIMIT $1 / OFFSET $2 on PostgreSQL:

func (l Limit) Build(b Builder) {
	if l.N < 0 {
		return
	}
	b.WriteString("LIMIT ")
	b.AddVar(l.N)
}

Two suppression rules fall out of the builders:

  • Limit with a negative N renders nothing (no LIMIT clause).
  • Offset with N <= 0 renders nothing (no OFFSET clause).

Row locking

Locking(true) appends FOR UPDATE:

FOR UPDATE

The clause has no dialect feature gate — it renders verbatim on both — so only enable it against databases that support row-level locking.

First and Last order for you

First and Last add their own primary-key ordering (ascending and descending respectively) so a single row is deterministic — including on composite primary keys. See the finisher reference for details.

Count strips ORDER BY

ORDER BY is invalid next to COUNT(*) on PostgreSQL (the ordering column must appear in GROUP BY), so Count drops the order clause before building — whatever you or a scope put there:

// ORDER BY is invalid next to COUNT(*) on PostgreSQL (the ordering
// column must appear in GROUP BY); drop whatever the caller or a scope
// provided. GROUP BY/HAVING are left intact. GORM #7516.
tx.Statement.RemoveClause("order")
func TestAuditCountStripsOrderBy(t *testing.T) {
	db := openTestDB(t)
	var n int64
	tx := db.Session(&Session{DryRun: true}).
		Model(&auditPlainUser{}).Order("name").Count(&n)
	sql := string(tx.Statement.SQL)
	if strings.Contains(sql, "ORDER BY") {
		t.Errorf("Count kept ORDER BY (invalid on PG): %s", sql)
	}
}

Raw clause structs

The chainables are thin wrappers over pure clause builders, which you can also register directly via Clauses:

// OrderBy renders ORDER BY columns (each may carry " DESC" / " ASC").
type OrderBy struct {
	Columns []string
}
// Limit renders LIMIT n.
type Limit struct {
	N int
}
// Offset renders OFFSET n.
type Offset struct {
	N int
}
// Locking renders FOR UPDATE when enabled.
type Locking struct {
	Enabled bool
}

OrderBy.Columns entries are written verbatim — direction suffixes like "name DESC" are part of the string. See Raw clauses for Clauses usage and Clause types for the full catalog.

Next

On this page