Validated ORDER BY
On this page
On MySQL:
- The SQL carries no ORDER BY; the generated method appends one from the allow-list
- Without an ORDER BY, InnoDB happens to return the rows in primary key order, which MySQL does not promise
A list page often lets the user choose the order: by name, by price, newest first. The column name cannot be a bound parameter, because placeholders carry values, not identifiers, so the usual fix is to paste the column into the SQL text, which is exactly where injection comes from. sgl.sortable gives you a sort the caller can choose without that risk. You list the columns that may be sorted on, and the generated method adds an ORDER BY only for a column on that list.
This example lists a regatta's entries in whatever order the caller asks for.
The query
db/queries/entries.sql
-- sgl.query(ListEntries, many)
-- sgl.sortable(order_by, [boat, crew, finish_seconds])
SELECT id, boat, crew, finish_seconds FROM entries
sgl.sortable(order_by, [boat, crew, finish_seconds]) names the sort and lists the columns it allows. It is a header of its own and binds no placeholder, and the query carries no ORDER BY: the generated method adds one.
What sgl generates
internal/store
type ListEntriesParams struct {
OrderBy ListEntriesOrderBy
OrderByDirection OrderDirection
}
type ListEntriesRow struct {
ID int64 `json:"id"`
Boat string `json:"boat"`
Crew int32 `json:"crew"`
FinishSeconds int32 `json:"finish_seconds"`
}
type ListEntriesOrderBy string
type OrderDirection string
func (queries *Queries) ListEntries(ctx context.Context, params ListEntriesParams) ([]ListEntriesRow, error) {
query := listEntriesSQL
switch string(params.OrderBy) {
case "boat", "crew", "finish_seconds":
query = query + (" ORDER BY " + string(params.OrderBy))
switch params.OrderByDirection {
case OrderAsc, OrderDesc:
query = query + (" " + string(params.OrderByDirection))
}
}
rows, err := queries.reader.QueryContext(ctx, query)
if err != nil {
return nil, err
}
defer rows.Close()
var results []ListEntriesRow
if rows.Next() {
var row ListEntriesRow
scanArgs := []any{&row.ID, &row.Boat, &row.Crew, &row.FinishSeconds}
for more := true; more; more = rows.Next() {
row = ListEntriesRow{}
if err := rows.Scan(scanArgs...); err != nil {
return nil, err
}
results = append(results, row)
}
}
if err := rows.Err(); err != nil {
return nil, err
}
return results, nil
}
The Params struct gains an OrderBy field, named after the directive, and an OrderByDirection. OrderBy has its own type, ListEntriesOrderBy, with one constant per allowed column, and the direction is an OrderDirection, either OrderAsc or OrderDesc. The constants are what callers are meant to use, and a misspelt constant does not compile.
The method checks the field against the allowed columns with a switch, and only a listed column is ever added to the SQL. The direction is checked the same way.
A value that is not on the list
ListEntriesOrderBy is a string type, so any string converts to it, including text taken straight from a request. Such a value is not an error. It is ignored: the method adds no ORDER BY at all, and the query runs unsorted. A direction other than OrderAsc or OrderDesc is dropped in the same way, and the column is kept. Nothing from outside the list can reach the SQL.
If an unknown value should fail instead, check it yourself before calling the method.
Using it
The program enters four boats and lists them four ways: by finishing time, by name, by crew size largest first, and with a piece of raw text as the column, which is ignored.
example.go
package main
import (
"context"
"database/sql"
"fmt"
"io"
"time"
"seagull.sh/seagull/examples/mysql/012_sortable/internal/store"
)
// run lists a regatta's entries in four orders. sgl.sortable(order_by, [boat, crew,
// finish_seconds]) has no placeholder: it gives ListEntriesParams an OrderBy field, typed
// with one constant per allowed column, and an OrderByDirection. The method appends ORDER
// BY only when OrderBy is one of the allowed columns, so a value that is not, such as raw
// text from a request, adds nothing to the SQL and the rows come back unsorted. A
// sortable column the query does not select makes sgl vet report Q011.
//
// Takes database (*sql.DB) which is a migrated database.
// Takes output (io.Writer) which receives each listing.
//
// Returns error when a query fails.
func run(ctx context.Context, database *sql.DB, output io.Writer) error {
queries := store.New(database)
entries := []store.EnterBoatParams{
{Boat: "Kittiwake", Crew: 4, FinishSeconds: 3725},
{Boat: "Salty Chip", Crew: 3, FinishSeconds: 3410},
{Boat: "Gull Wing", Crew: 5, FinishSeconds: 3990},
{Boat: "Driftwood", Crew: 2, FinishSeconds: 3588},
}
for _, entry := range entries {
if err := queries.EnterBoat(ctx, entry); err != nil {
return fmt.Errorf("entering %s: %w", entry.Boat, err)
}
}
orders := []struct {
label string
parameters store.ListEntriesParams
}{
{label: "results", parameters: store.ListEntriesParams{OrderBy: store.ListEntriesOrderByFinishSeconds, OrderByDirection: store.OrderAsc}},
{label: "by boat", parameters: store.ListEntriesParams{OrderBy: store.ListEntriesOrderByBoat, OrderByDirection: store.OrderAsc}},
{label: "largest crew first", parameters: store.ListEntriesParams{OrderBy: store.ListEntriesOrderByCrew, OrderByDirection: store.OrderDesc}},
{label: "raw text, ignored", parameters: store.ListEntriesParams{OrderBy: "boat; DROP TABLE entries", OrderByDirection: store.OrderAsc}},
}
for _, order := range orders {
listed, err := queries.ListEntries(ctx, order.parameters)
if err != nil {
return fmt.Errorf("listing entries %s: %w", order.label, err)
}
fmt.Fprintf(output, "%s:\n", order.label)
for _, entry := range listed {
finish := time.Duration(entry.FinishSeconds) * time.Second
fmt.Fprintf(output, " %-10s crew %d %s\n", entry.Boat, entry.Crew, finish)
}
}
return nil
}
What it prints
The last listing has no ORDER BY. InnoDB happens to return the rows in primary key order, which here is the order they were entered, but MySQL does not promise it.
results:
Salty Chip crew 3 56m50s
Driftwood crew 2 59m48s
Kittiwake crew 4 1h2m5s
Gull Wing crew 5 1h6m30s
by boat:
Driftwood crew 2 59m48s
Gull Wing crew 5 1h6m30s
Kittiwake crew 4 1h2m5s
Salty Chip crew 3 56m50s
largest crew first:
Gull Wing crew 5 1h6m30s
Kittiwake crew 4 1h2m5s
Salty Chip crew 3 56m50s
Driftwood crew 2 59m48s
raw text, ignored:
Kittiwake crew 4 1h2m5s
Salty Chip crew 3 56m50s
Gull Wing crew 5 1h6m30s
Driftwood crew 2 59m48s
Try it
Add a column the query does not select, such as entered_at, to the sortable list and run sgl vet. It reports Q011: the list should only name columns the result carries.
Across engines
Only these Go types of ListEntries differ between engines; the rest are the same everywhere.
| MySQL | SQLite | PostgreSQL | DuckDB | ClickHouse | |
|---|---|---|---|---|---|
id column | int64 | int64 | int64 | int64 | uint64 |
crew column | int32 | int64 | int64 | int32 | uint8 |
finish_seconds column | int32 | int64 | int64 | int32 | uint32 |
MariaDB runs the MySQL version unchanged.
CockroachDB and TimescaleDB run the PostgreSQL version unchanged.
Compare the whole example side by side with SQLite, PostgreSQL, DuckDB and ClickHouse.
Run it locally
From the directory you cloned the Seagull repository into:
cd seagull/examples/mysql && go run ./012_sortable
Its test runs it too, and checks what it prints against output.txt:
cd seagull/examples/mysql && SGL_EXAMPLE_DSN="$DATABASE_URL" go test ./012_sortable
Needs a running MySQL server: set DATABASE_URL, or pass -dsn, to the address of an empty database.
The files
Every file of the example, as it is in the Seagull repository.
sgl.yaml
# Copyright 2026 PolitePixels Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This project stands against fascism, authoritarianism, and all forms of
# oppression. We built this to empower people, not to enable those who would
# strip others of their rights and dignity.
version: 1
databases:
- name: regatta
dialect: mysql
migrations: db/migrations
queries: db/queries
go:
package: store
out: internal/store
db/migrations/0001_entries.up.sql
CREATE TABLE entries (
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
boat VARCHAR(50) NOT NULL,
crew INT NOT NULL,
finish_seconds INT NOT NULL
);
db/migrations/0001_entries.down.sql
DROP TABLE entries;
db/queries/entries.sql
-- sgl.query(EnterBoat, exec)
INSERT INTO entries (boat, crew, finish_seconds) VALUES (?, ?, ?);
-- sgl.query(ListEntries, many)
-- sgl.sortable(order_by, [boat, crew, finish_seconds])
SELECT id, boat, crew, finish_seconds FROM entries
example.go
package main
import (
"context"
"database/sql"
"fmt"
"io"
"time"
"seagull.sh/seagull/examples/mysql/012_sortable/internal/store"
)
// run lists a regatta's entries in four orders. sgl.sortable(order_by, [boat, crew,
// finish_seconds]) has no placeholder: it gives ListEntriesParams an OrderBy field, typed
// with one constant per allowed column, and an OrderByDirection. The method appends ORDER
// BY only when OrderBy is one of the allowed columns, so a value that is not, such as raw
// text from a request, adds nothing to the SQL and the rows come back unsorted. A
// sortable column the query does not select makes sgl vet report Q011.
//
// Takes database (*sql.DB) which is a migrated database.
// Takes output (io.Writer) which receives each listing.
//
// Returns error when a query fails.
func run(ctx context.Context, database *sql.DB, output io.Writer) error {
queries := store.New(database)
entries := []store.EnterBoatParams{
{Boat: "Kittiwake", Crew: 4, FinishSeconds: 3725},
{Boat: "Salty Chip", Crew: 3, FinishSeconds: 3410},
{Boat: "Gull Wing", Crew: 5, FinishSeconds: 3990},
{Boat: "Driftwood", Crew: 2, FinishSeconds: 3588},
}
for _, entry := range entries {
if err := queries.EnterBoat(ctx, entry); err != nil {
return fmt.Errorf("entering %s: %w", entry.Boat, err)
}
}
orders := []struct {
label string
parameters store.ListEntriesParams
}{
{label: "results", parameters: store.ListEntriesParams{OrderBy: store.ListEntriesOrderByFinishSeconds, OrderByDirection: store.OrderAsc}},
{label: "by boat", parameters: store.ListEntriesParams{OrderBy: store.ListEntriesOrderByBoat, OrderByDirection: store.OrderAsc}},
{label: "largest crew first", parameters: store.ListEntriesParams{OrderBy: store.ListEntriesOrderByCrew, OrderByDirection: store.OrderDesc}},
{label: "raw text, ignored", parameters: store.ListEntriesParams{OrderBy: "boat; DROP TABLE entries", OrderByDirection: store.OrderAsc}},
}
for _, order := range orders {
listed, err := queries.ListEntries(ctx, order.parameters)
if err != nil {
return fmt.Errorf("listing entries %s: %w", order.label, err)
}
fmt.Fprintf(output, "%s:\n", order.label)
for _, entry := range listed {
finish := time.Duration(entry.FinishSeconds) * time.Second
fmt.Fprintf(output, " %-10s crew %d %s\n", entry.Boat, entry.Crew, finish)
}
}
return nil
}
main.go
// Command 012_sortable applies its migrations to a MySQL database, then runs the example
// in example.go: regatta entries are listed in the orders a caller picks from an
// allow-list.
//
// Run it with `go run . -dsn 'user:password@tcp(localhost:3306)/regatta'`, or set
// DATABASE_URL instead of passing -dsn. Give it an empty database of its own, as the
// migrations create its tables and the example adds rows each time it runs.
package main
import (
"context"
"database/sql"
"embed"
"errors"
"flag"
"fmt"
"log"
"os"
"github.com/go-sql-driver/mysql"
"seagull.sh/seagull/sdk/migrate"
"seagull.sh/seagull/sdk/migrate/migrate_backend_mysql"
)
// migrations holds the migration files, compiled into the binary.
//
//go:embed db/migrations
var migrations embed.FS
func main() {
dsn := flag.String("dsn", os.Getenv("DATABASE_URL"), "MySQL data source name; defaults to $DATABASE_URL")
flag.Parse()
if err := execute(context.Background(), *dsn); err != nil {
log.Fatal(err)
}
}
// execute opens and migrates the database dsn names, and runs the example against it.
//
// Takes dsn (string) which is the database's data source name.
//
// Returns error when the database cannot be prepared or the example fails.
func execute(ctx context.Context, dsn string) error {
if dsn == "" {
return errors.New("set -dsn or DATABASE_URL to a MySQL data source name")
}
config, err := mysql.ParseDSN(dsn)
if err != nil {
return err
}
// Seagull maps DATETIME and TIMESTAMP columns to time.Time, which the driver returns
// only when parseTime is set.
config.ParseTime = true
dsn = config.FormatDSN()
database, err := sql.Open("mysql", dsn)
if err != nil {
return err
}
defer func() { _ = database.Close() }()
migrator, err := migrate.NewMigrator(database, migrate_backend_mysql.New(migrate.WithDriverMultiStatements(config.MultiStatements)), migrations, "db/migrations")
if err != nil {
return err
}
if _, err := migrator.Up(ctx); err != nil {
return fmt.Errorf("migrating: %w", err)
}
return run(ctx, database, os.Stdout)
}
internal/store/entries.sql.go
// Code generated by sgl. DO NOT EDIT.
package store
import "context"
const enterBoatSQL = `INSERT INTO entries (boat, crew, finish_seconds) VALUES (?, ?, ?);`
type EnterBoatParams struct {
Boat string
Crew int32
FinishSeconds int32
}
func (queries *Queries) EnterBoat(ctx context.Context, params EnterBoatParams) error {
_, err := queries.writer.ExecContext(ctx, enterBoatSQL, params.Boat, params.Crew, params.FinishSeconds)
return err
}
const listEntriesSQL = `SELECT id, boat, crew, finish_seconds FROM entries`
type ListEntriesParams struct {
OrderBy ListEntriesOrderBy
OrderByDirection OrderDirection
}
type ListEntriesOrderBy string
const (
ListEntriesOrderByBoat ListEntriesOrderBy = "boat"
ListEntriesOrderByCrew ListEntriesOrderBy = "crew"
ListEntriesOrderByFinishSeconds ListEntriesOrderBy = "finish_seconds"
)
type ListEntriesRow struct {
ID int64 `json:"id"`
Boat string `json:"boat"`
Crew int32 `json:"crew"`
FinishSeconds int32 `json:"finish_seconds"`
}
func (queries *Queries) ListEntries(ctx context.Context, params ListEntriesParams) ([]ListEntriesRow, error) {
query := listEntriesSQL
switch string(params.OrderBy) {
case "boat", "crew", "finish_seconds":
query = query + (" ORDER BY " + string(params.OrderBy))
switch params.OrderByDirection {
case OrderAsc, OrderDesc:
query = query + (" " + string(params.OrderByDirection))
}
}
rows, err := queries.reader.QueryContext(ctx, query)
if err != nil {
return nil, err
}
defer rows.Close()
var results []ListEntriesRow
if rows.Next() {
var row ListEntriesRow
scanArgs := []any{&row.ID, &row.Boat, &row.Crew, &row.FinishSeconds}
for more := true; more; more = rows.Next() {
row = ListEntriesRow{}
if err := rows.Scan(scanArgs...); err != nil {
return nil, err
}
results = append(results, row)
}
}
if err := rows.Err(); err != nil {
return nil, err
}
return results, nil
}
internal/store/models.go
// Code generated by sgl. DO NOT EDIT.
package store
type Entries struct {
ID int64 `json:"id"`
Boat string `json:"boat"`
Crew int32 `json:"crew"`
FinishSeconds int32 `json:"finish_seconds"`
}
internal/store/querier.go
// Code generated by sgl. DO NOT EDIT.
// Package store reads DATETIME, DATE and TIMESTAMP columns into time.Time, so the DSN it connects with must set parseTime=true.
package store
import (
"context"
"database/sql"
)
type DBTX interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}
type dbtxWrapper interface {
WrapDBTX(inner any) any
}
type Queries struct {
reader DBTX
writer DBTX
wrapper dbtxWrapper
}
func New(db DBTX) *Queries {
wrapper, _ := db.(dbtxWrapper)
return &Queries{reader: db, writer: db, wrapper: wrapper}
}
func NewWithReplica(writer DBTX, reader DBTX) *Queries {
wrapper, _ := writer.(dbtxWrapper)
return &Queries{reader: reader, writer: writer, wrapper: wrapper}
}
func (queries *Queries) WithTx(transaction *sql.Tx) *Queries {
if queries == nil {
return &Queries{reader: transaction, writer: transaction, wrapper: nil}
}
db := queries.wrapDBTX(transaction)
return &Queries{reader: db, writer: db, wrapper: queries.wrapper}
}
func (queries *Queries) wrapDBTX(db DBTX) DBTX {
if queries.wrapper == nil {
return db
}
wrapped, ok := queries.wrapper.WrapDBTX(db).(DBTX)
if !ok {
return db
}
return wrapped
}
func (queries *Queries) RunInTx(ctx context.Context, db *sql.DB, fn func(*Queries) error) error {
transaction, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer transaction.Rollback()
if err = fn(queries.WithTx(transaction)); err != nil {
return err
}
return transaction.Commit()
}
internal/store/sortable.go
// Code generated by sgl. DO NOT EDIT.
package store
type OrderDirection string
const (
OrderAsc OrderDirection = "ASC"
OrderDesc OrderDirection = "DESC"
)
output.txt
results:
Salty Chip crew 3 56m50s
Driftwood crew 2 59m48s
Kittiwake crew 4 1h2m5s
Gull Wing crew 5 1h6m30s
by boat:
Driftwood crew 2 59m48s
Gull Wing crew 5 1h6m30s
Kittiwake crew 4 1h2m5s
Salty Chip crew 3 56m50s
largest crew first:
Gull Wing crew 5 1h6m30s
Kittiwake crew 4 1h2m5s
Salty Chip crew 3 56m50s
Driftwood crew 2 59m48s
raw text, ignored:
Kittiwake crew 4 1h2m5s
Salty Chip crew 3 56m50s
Gull Wing crew 5 1h6m30s
Driftwood crew 2 59m48s