Skip to main content

Subqueries, sets, and CTEs

A query can sit inside another one as a list of values, a single value, or a table. Global filters and soft deletes still apply inside it.

Match a list of values from another query​

ant.SubOf turns a query and a column into something InSub and NotInSub can use.

authors := ant.SubOf(db.Posts.Where(ant.Eq(&Posts.Published, true)), &Posts.UserID)

wrote, err := db.Users.Where(ant.InSub(&Users.ID, authors)).All(ctx)
// SELECT ... FROM "users"
// WHERE "users"."id" IN (SELECT "posts"."user_id" FROM "posts" WHERE "posts"."published" = $1)

quiet, err := db.Users.Where(ant.NotInSub(&Users.ID, authors)).All(ctx)
// SELECT ... FROM "users"
// WHERE "users"."id" NOT IN (SELECT "posts"."user_id" FROM "posts" WHERE "posts"."published" = $1)

InSub also avoids the parameter limit of a long In list.

A subquery can refer to the outer row with EqCol.

theirs := db.Posts.Where(ant.EqCol(&Posts.UserID, &Users.ID))

wrote, err := db.Users.Where(ant.Exists(theirs)).All(ctx)
// SELECT ... FROM "users"
// WHERE EXISTS (SELECT 1 FROM "posts" WHERE "posts"."user_id" = "users"."id")

quiet, err := db.Users.Where(ant.NotExists(theirs)).All(ctx)
// SELECT ... FROM "users"
// WHERE NOT EXISTS (SELECT 1 FROM "posts" WHERE "posts"."user_id" = "users"."id")

For a relation, see ant.Has.

Compare with a single value​

ant.SubExpr runs a query for a single value, usable anywhere an expression goes.

oldest := ant.SubExpr(db.Users.Where(), ant.Max(&Users.Age)).Expr()

users, err := db.Users.Where(ant.Col(&Users.Age).EqExpr(oldest)).All(ctx)
// SELECT ... FROM "users" WHERE "users"."age" = (SELECT MAX("users"."age") FROM "users")

Ordering by a subquery sorts users by post count:

posts := ant.SubExpr(db.Posts.Where(ant.EqCol(&Posts.UserID, &Users.ID)), ant.Count()).Expr()

busiest, err := db.Users.Order(posts.Desc()).All(ctx)
// SELECT ... FROM "users"
// ORDER BY (SELECT COUNT(*) FROM "posts" WHERE "posts"."user_id" = "users"."id") DESC

Query a subquery​

From replaces the table a query reads with another query, so conditions added afterward apply to its result.

adults := db.Users.Where(ant.Gt(&Users.Age, 18))

users, err := db.Users.Query().From(adults).Where(ant.Lt(&Users.Age, 35)).All(ctx)
// SELECT ... FROM (SELECT ... FROM "users" WHERE "users"."age" > $1) AS "users"
// WHERE "users"."age" < $2

Include in a subquery returns ant.ErrIncludeInSubquery.

An Update or Delete on a query like this selects its rows by key in a subquery. Bulk writes lists what a derived source must hold for that to work.

Union, intersect, except​

These combine queries of one model. Conditions, ordering and paging added afterward apply to the combined rows. The sides must select the model's columns in the same order.

young := db.Users.Where(ant.Lt(&Users.Age, 35))
old := db.Users.Where(ant.Gt(&Users.Age, 25))

either, err := young.Union(old).OrderBy(&Users.Name).All(ctx)
// SELECT ... FROM (
// SELECT ... FROM "users" WHERE "users"."age" < $1
// UNION (SELECT ... FROM "users" WHERE "users"."age" > $2)
// ) AS "users" ORDER BY "users"."name"

repeats, err := young.UnionAll(old).All(ctx) // UNION ALL keeps duplicates
both, err := young.Intersect(old).All(ctx) // INTERSECT
onlyYoung, err := young.Except(old).All(ctx) // EXCEPT

Page each side​

Each side keeps its own OrderBy, Limit and Offset, which choose that side's rows before the sides combine. This gets the two youngest and two oldest users:

youngest := db.Users.OrderBy(&Users.Age).Limit(2)
oldest := db.Users.OrderByDesc(&Users.Age).Limit(2)

extremes, err := youngest.Union(oldest).OrderBy(&Users.Name).All(ctx)
// SELECT ... FROM (
// SELECT * FROM (SELECT ... FROM "users" ORDER BY "users"."age" LIMIT $1) AS "users"
// UNION (SELECT * FROM (SELECT ... FROM "users" ORDER BY "users"."age" DESC LIMIT $2) AS "users")
// ) AS "users" ORDER BY "users"."name"

A side with a Limit or Offset is wrapped in a derived table. A side that orders without paging loses its order. To order or page the combined rows, call OrderBy and Limit after the set operation, as OrderBy(&Users.Name) does above.

Common table expressions​

FromCTE names a query in a WITH clause and reads from it.

named := db.Users.Where(ant.Like(&Users.Name, "A%"))

users, err := db.Users.Query().FromCTE("named", named).OrderBy(&Users.Name).All(ctx)
// WITH "named" AS (SELECT ... FROM "users" WHERE "users"."name" LIKE $1)
// SELECT ... FROM "named" AS "users" ORDER BY "users"."name"

Count and Exists on such a query keep the WITH at the start of the statement on every database:

n, err := db.Users.Query().FromCTE("named", db.Users.Where(ant.Like(&Users.Name, "A%"))).Count(ctx)
// WITH "named" AS (SELECT ... FROM "users" WHERE "users"."name" LIKE $1)
// SELECT COUNT(*) FROM "named" AS "users"

SQL Server takes WITH only at the start of a statement, so it can't run an Update or Delete after FromCTE or Recursive, and returns ant.ErrUnsupported. See bulk writes and databases.

Walk a tree​

Recursive follows a model's relation to itself from the rows of the query down to the leaves. RecursiveOne walks up to the parents instead.

type Folder struct {
ID int64
ParentID *int64
Name string
Parent *Folder
Children []Folder
}

var Folders = ant.Fields[Folder]()

tree, err := db.Folders.Where(ant.Eq(&Folders.ID, id)).
Recursive(&Folders.Children).
OrderBy(&Folders.Name).
All(ctx)
// WITH RECURSIVE "ant_tree" AS (
// SELECT ... FROM "folders" WHERE "folders"."id" = $1
// UNION (SELECT ... FROM "folders" JOIN "ant_tree" ON "folders"."parent_id" = "ant_tree"."id")
// ) SELECT ... FROM "ant_tree" AS "folders" ORDER BY "folders"."name"

ancestors, err := db.Folders.Where(ant.Eq(&Folders.ID, id)).
RecursiveOne(&Folders.Parent).
All(ctx)
// WITH RECURSIVE "ant_tree" AS (
// SELECT ... FROM "folders" WHERE "folders"."id" = $1
// UNION (SELECT ... FROM "folders" JOIN "ant_tree" ON "folders"."id" = "ant_tree"."parent_id")
// ) SELECT ... FROM "ant_tree" AS "folders"

A loop in the data doesn't hang the query. The parts are joined with UNION, which drops a row it has already seen, so a row reached from two starting rows comes back once.

The starting rows can be limited and ordered like the sides of a set operation:

first, err := db.Folders.OrderBy(&Folders.Name).Limit(1).Recursive(&Folders.Children).All(ctx)
// WITH RECURSIVE "ant_tree" AS (
// SELECT * FROM (SELECT ... FROM "folders" ORDER BY "folders"."name" LIMIT $1) AS "folders"
// UNION (SELECT ... FROM "folders" JOIN "ant_tree" ON "folders"."parent_id" = "ant_tree"."id")
// ) SELECT ... FROM "ant_tree" AS "folders"

SQL Server writes the statement differently with the same result. Its recursive WITH has no RECURSIVE and joins its parts only with UNION ALL, which neither ends a cycle nor drops a repeated row. So each row carries the path of keys that reached it, a row already on its path isn't followed again, and the query reads one row per key. ant also adds OPTION (MAXRECURSION 0), which lifts SQL Server's limit of 100 levels. MySQL, MariaDB and SQLite use UNION as PostgreSQL does. See databases.

Rows held in memory​

ant.Values treats rows in your program as a table. An empty list is ant.ErrNoRows, because SQL has no empty VALUES.

type Wanted struct {
UserID int64
Label string
}

var Wanteds = ant.Fields[Wanted]()

wanted := ant.Values(db, Wanted{alice.ID, "first"}, Wanted{bob.ID, "second"})

rows, err := ant.JoinSub(db.Users.Query(), wanted, ant.EqCol(&Users.ID, &Wanteds.UserID)).
Select(func(u *User, w *Wanted) string { return w.Label + ": " + u.Name }).
All(ctx)
// SELECT ... FROM "users"
// JOIN (SELECT "wanteds"."user_id", "wanteds"."label" FROM (VALUES
// (CAST($1 AS bigint), CAST($2 AS text)), (CAST($3 AS bigint), CAST($4 AS text))
// ) AS "wanteds" ("user_id", "label")) AS "wanteds"
// ON "users"."id" = "wanteds"."user_id"

Values works on every database. PostgreSQL casts the values to the column types. SQLite and MySQL write the rows as SELECT ... UNION ALL SELECT ..., and SQL Server as VALUES without casts. Results aren't tracked.

Table functions​

ant.FromFunc reads a function that returns rows. The call is SQL for your database, with ? for arguments.

type Number struct {
N int64
}

var Numbers = ant.Fields[Number]()

numbers, err := ant.
FromFunc[Number](db, "generate_series(?::bigint, ?::bigint) AS numbers(n)", 1, 5).
Where(ant.Gt(&Numbers.N, 3)).
All(ctx)
// SELECT "numbers"."n" FROM (SELECT * FROM generate_series($1::bigint, $2::bigint) AS numbers(n)) AS "numbers"
// WHERE "numbers"."n" > $3