Database: Query Builder
- Introduction
- Running queries
- Select statements
- Conditions
- Ordering, grouping, limit, and offset
- Conditional clauses
- Joins
- Unions
- Raw expressions
- Inserts
- Updates
- Deletes
- Connections and transactions
- Debugging
Introduction
Most database interactions come down to reading and writing rows: listing recent posts, counting orders, or archiving inactive records. The query builder lets you build these queries as Go method calls and scan the rows into your own structs.
Laravel writes the SQL for your database, binds every value as a parameter, and runs the query on PostgreSQL, MySQL, MariaDB, or SQLite, using the same connections, read replicas, and transactions as raw queries. Because models build on the query builder, the reads, updates, and deletes on this page work in model queries as well.
You may use db.Table to begin a query for a table. It returns a *db.Query, so you may chain clauses onto the query before you run it with a method such as Get. For example, this handler lists the ten most popular published posts:
// handlers/posts/posts.go
package posts
import (
"time"
"go.laravel.com/db"
"go.laravel.com/web"
)
type Post struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id"`
Title string `json:"title"`
Votes int64 `json:"votes"`
PublishedAt *time.Time `json:"published_at"`
}
func Index(r *web.Request) *web.Response {
posts, err := db.Table("posts").
WhereGt("votes", 100).
WhereNotNull("published_at").
OrderByDesc("votes").
Limit(10).
Get[Post](r)
if err != nil {
return web.Fail(err)
}
return web.JSON(posts)
}Get returns a slice of rows, matching columns to fields by name, as mapping rows to structs describes.
A query is an ordinary Go value. Each clause method returns a new query and leaves the original unchanged, so you may store a query, pass it to a function, and run it more than once. Nothing reaches the database until you call a method that takes a context, such as Get, Count, or Update. In a handler, pass the request r. In a job, a command, or a function of your own, pass the context.Context it receives. The query runs on the database the context carries, and joins any transaction the context is in:
published := db.Table("posts").WhereNotNull("published_at")
total, err := published.Count(ctx)
if err != nil {
return err
}
posts, err := published.OrderByDesc("votes").Limit(20).Get[Post](ctx)Running queries
Retrieving rows
Each of these methods runs the query and scans what it reads into the type you name in brackets:
| Method | Returns |
|---|---|
Get[T](ctx) | Every row, as []T |
First[T](ctx) | The first row, as T. No row is a *db.NotFoundError |
Find[T](ctx, id) | The row whose id column equals id, as T. No row is a *db.NotFoundError |
Sole[T](ctx) | The only matching row, as T. No row is a *db.NotFoundError, and several are a *db.MultipleRowsError |
Value[V](ctx, column) | One column of the first row. No row is a *db.NotFoundError |
Pluck[V](ctx, column) | One column of every row, as []V |
Exists(ctx) | Whether any row matches |
For example, you might read a user's email address, or the titles of the featured posts:
email, err := db.Table("users").WhereEq("name", "Taylor").Value[string](ctx, "email")
titles, err := db.Table("posts").WhereEq("featured", true).Pluck[string](ctx, "title")For a column that may be NULL, read a pointer, such as Value[*string], which is nil for NULL. (When scanning into an existing pointer, GetInto, FirstInto, FindInto, and SoleInto accept a pointer destination.)
A *db.NotFoundError responds with a 404, so a handler that shows one record passes the error to web.Fail and needs no check of its own. Pass Find an integer from r.PathInt rather than the string from r.PathValue, because PostgreSQL rejects text such as hello for an integer column, and the request fails with a 500 instead of a 404:
func Show(r *web.Request) *web.Response {
id, err := r.PathInt("post")
if err != nil {
return web.Fail(err)
}
post, err := db.Table("posts").Find[Post](r, id)
if err != nil {
return web.Fail(err)
}
return web.JSON(post)
}Aggregates
Count and CountDistinct return an int. Sum, Avg, Min, and Max return the column's aggregate as the type in brackets:
users, err := db.Table("users").Count(ctx)
votes, err := db.Table("posts").WhereEq("user_id", 42).Sum[int64](ctx, "votes")
rating, err := db.Table("reviews").Avg[*float64](ctx, "stars")
buyers, err := db.Table("orders").WhereMonth("created_at", "=", 11).CountDistinct(ctx, "user_id")When no row matches, Sum returns 0, but Avg, Min, and Max read NULL. If the query might match no rows, read a pointer from those methods, such as Max[*int64], which is nil for NULL.
Sum a decimal column, such as an order's total, into a numeric.Decimal, which keeps every digit that a float64 would round:
import "go.laravel.com/numeric"
revenue, err := db.Table("orders").WhereEq("status", "paid").Sum[numeric.Decimal](ctx, "total")Chunking and streaming
When you need to work through thousands of rows, you don't want them all in memory at once. ChunkByID returns an iterator over pages of rows, ordered by an integer key column. Each page starts after the last key of the previous one, so the loop may update or delete the rows it reads. Give the row type in brackets:
type User struct {
ID int64
Email string
}
inactive := db.Table("users").WhereEq("active", false)
for users, err := range inactive.ChunkByID[User](ctx, 100, "id") {
if err != nil {
return err
}
ids := make([]int64, len(users))
for i, user := range users {
ids[i] = user.ID
}
_, err = db.Table("users").
WhereIn("id", ids).
Update(ctx, db.Values{"archived": true})
if err != nil {
return err
}
}To walk the keys from highest to lowest, use ChunkByIDDesc. LazyByID and LazyByIDDesc take the same arguments and yield one row at a time, while still querying one page at a time:
for user, err := range db.Table("users").LazyByIDDesc[User](ctx, 500, "id") {
if err != nil {
return err
}
fmt.Println(user.ID, user.Email)
}Chunk(ctx, size) pages with a limit and an offset instead, so the query needs an OrderBy. Use it only when the loop doesn't change which rows match. Cursor streams every row of one query and holds its connection until the loop ends. Inside a transaction, a query inside a cursor's loop fails with db.ErrCursorOpen, so read the rows with Get first when the loop needs to write.
Select statements
You may not always want to select every column from a database table. Use Select to name the columns you need, including optional as aliases, and Distinct to return only unique rows. Each call to Select adds to the columns the query already reads:
type author struct {
ID int64
Author string
}
authors, err := db.Table("users").Select("id", "users.name as author").Get[author](ctx)
roles, err := db.Table("users").Distinct().Pluck[string](ctx, "role")Laravel quotes every name you pass to Select, so Select("count(*)") reads a column named count(*). To select an expression, use SelectRaw:
type userTotal struct {
UserID int64
LifetimeTotal int64
}
totals, err := db.Table("orders").
Select("user_id").
SelectRaw("sum(total) as lifetime_total").
GroupBy("user_id").
Get[userTotal](ctx)警告
Although Laravel quotes every table and column name to prevent SQL injection, passing untrusted request input as a column name can still expose columns users shouldn't be able to read or sort by. Always validate user-supplied column names against an explicit allowlist before passing them to a query.
Conditions
Comparing columns and values
Use the operator helper methods for the common comparisons, or Where when you want to pass the operator explicitly:
db.Table("users").WhereEq("active", true).WhereGe("votes", 100)
db.Table("users").Where("votes", ">=", 100)| Helper | Or helper | Operator | SQL |
|---|---|---|---|
WhereEq(column, value) | OrWhereEq | = | = |
WhereNe(column, value) | OrWhereNe | <>, != | <> |
WhereLt(column, value) | OrWhereLt | < | < |
WhereLe(column, value) | OrWhereLe | <= | <= |
WhereGt(column, value) | OrWhereGt | > | > |
WhereGe(column, value) | OrWhereGe | >= | >= |
Where(column, "like", value) | OrWhere | like, not like | like, not like |
A query with any other operator fails when it runs, so an operator from a variable can't inject SQL.
The value of a Where is always a bound parameter, so a string there is never read as a column name. To compare two columns of the same row, such as posts edited after they were created, use WhereColumn:
db.Table("posts").WhereColumn("updated_at", ">", "created_at")The like operator ignores case on MySQL and SQLite, but not on PostgreSQL, where T% doesn't match taylor. For a pattern that behaves the same on every database, use WhereLike, whose last argument says whether case matters. A search box usually ignores case, while a coupon code may not, so SUMMER25 and summer25 are different codes:
db.Table("users").WhereLike("name", "%taylor%", false)
db.Table("coupons").WhereLike("code", "SUMMER%", true)WhereNotLike takes the same arguments and keeps the rows that don't match. OrWhereLike and OrWhereNotLike join their conditions with or.
WhereNull checks for NULL, and WhereNotNull checks for IS NOT NULL. Comparing with nil, such as Where("deleted_at", "=", nil), also writes is null:
db.Table("users").WhereNotNull("email_verified_at")In SQL, Where("team_id", "<>", 2) leaves out rows where team_id is NULL. When you want those rows included, use WhereDistinctFrom, which treats NULL as a value of its own. WhereNotDistinctFrom is its opposite, an equality where NULL matches NULL:
var teamID *int64 // nil for users without a team
db.Table("users").WhereDistinctFrom("team_id", 2)
db.Table("users").WhereNotDistinctFrom("team_id", teamID)For database-specific operators that don't have a method, such as PostgreSQL's regex operator (~*), write the condition with WhereRaw:
db.Table("users").WhereRaw("email ~* ?", pattern)Combining conditions
Each Where adds a condition joined with and, and OrWhere adds one joined with or. They group the way SQL does, where and comes before or, so Where(a).OrWhere(b).Where(c) evaluates as a or (b and c). To group conditions yourself, pass a function to WhereGroup, which wraps the conditions the function adds in parentheses:
posts := db.Table("posts").
WhereNotNull("published_at").
WhereGroup(func(q *db.Query) *db.Query {
return q.WhereEq("featured", true).OrWhereGe("votes", 50)
})select * from "posts" where "published_at" is not null and ("featured" = $1 or "votes" >= $2)OrWhereGroup joins its group with or. When a query has other conditions beside an OrWhere, put the OrWhere inside a group, so a condition that a shared function adds later still applies to every row.
Lists and ranges
WhereIn keeps the rows whose value is in a slice, and WhereNotIn keeps the rows whose value isn't. An empty slice matches no rows in WhereIn, and every row in WhereNotIn:
ids := []int64{3, 7, 42}
db.Table("users").WhereIn("id", ids)
db.Table("posts").WhereNotIn("status", []string{"draft", "archived"})WhereBetween keeps the rows whose value is in an inclusive range:
db.Table("users").WhereBetween("votes", 1, 100)Subqueries and exists
You may pass another query to WhereIn and WhereNotIn to filter against a subquery's results, or as the value in Where to compare with a subquery's single value. Build the subquery with db.Table, and leave off the method that runs it:
following := db.Table("follows").Select("followed_id").WhereEq("follower_id", 42)
feed := db.Table("posts").WhereIn("user_id", following)
largest := db.Table("orders").SelectRaw("max(total)")
biggestOrders := db.Table("orders").WhereEq("total", largest)When you want to put a subquery on the left side of a comparison, use WhereSub. The subquery refers to the outer query's columns by their table's name, with WhereColumn. For example, this query retrieves all users whose plan is named "Pro":
plan := db.Table("plans").Select("name").WhereColumn("plans.id", "=", "users.plan_id")
proUsers := db.Table("users").WhereSub(plan, "=", "Pro")To select a subquery's value as a column, use SelectSub with an alias. For example, this query selects each user's name along with their total number of posts as posts_count:
posts := db.Table("posts").SelectRaw("count(*)").WhereColumn("posts.user_id", "=", "users.id")
type author struct {
Name string
PostsCount int64
}
authors, err := db.Table("users").Select("name").SelectSub(posts, "posts_count").Get[author](ctx)To sort rows by a subquery's value, use OrderBySub or OrderBySubDesc. For example, this query lists users by their most recent login, starting with the user who logged in last:
lastLogin := db.Table("logins").
SelectRaw("max(created_at)").
WhereColumn("logins.user_id", "=", "users.id")
users := db.Table("users").OrderBySubDesc(lastLogin)WhereExists matches rows for which a subquery returns at least one row, and WhereNotExists matches the others. For example, this query retrieves every user who has placed at least one order:
orders := db.Table("orders").WhereColumn("orders.user_id", "=", "users.id")
customers := db.Table("users").WhereExists(orders)JSON columns
Use -> in a column name to read inside a JSON column, and [n] for an array element. A column with a path works in Where, WhereIn, WhereNull, Select, OrderBy, GroupBy, and the aggregates:
db.Table("users").WhereEq("options->language", "en")
db.Table("users").WhereEq("options->languages[0]", "en")
db.Table("users").WhereEq("options->notifications->mentions", true)Compare with the type the document holds: a number for a JSON number, and a string for a JSON string. On SQLite, WhereEq("options->size", "3") doesn't match {"size": 3}.
You may also query JSON arrays and object keys. WhereJSONContains keeps the rows whose array holds a value, or every value of a slice, and WhereJSONDoesntContain keeps the other rows. WhereJSONContainsKey keeps the rows whose document has a key, even one that holds null, and WhereJSONDoesntContainKey keeps the others. WhereJSONLength compares an array's length:
db.Table("users").WhereJSONContains("options->languages", "en")
db.Table("users").WhereJSONContains("options->languages", []string{"en", "de"})
db.Table("users").WhereJSONDoesntContainKey("options->theme")
db.Table("users").WhereJSONLength("options->languages", ">", 1)A selected JSON path scans into a string when it holds text. To scan the path into a struct field, give it an alias that matches the field:
type userLanguage struct {
Name string
Language string
}
users, err := db.Table("users").Select("name", "options->language as language").Get[userLanguage](ctx)Dates
You may compare part of a date and time column using WhereDate, WhereTime, WhereYear, WhereMonth, or WhereDay. WhereDate and WhereTime take text or a time.Time:
db.Table("orders").WhereDate("created_at", "=", "2026-10-31")
db.Table("orders").WhereYear("created_at", "=", 2026)These clauses wrap the column in a function, so the database can't use an index on it. On a large table, compare the column with a range instead, such as WhereBetween("created_at", start, end).
Many date conditions compare with the current time, such as the invoices that are overdue or the orders placed today. WherePast and WhereFuture compare a column with now. WhereToday, WhereBeforeToday, and WhereAfterToday compare its date with today's date:
db.Table("invoices").WherePast("due_at").WhereNull("paid_at")
db.Table("orders").WhereToday("created_at")
db.Table("events").WhereAfterToday("starts_at")To include the present, use WhereNowOrPast, WhereNowOrFuture, WhereTodayOrBefore, or WhereTodayOrAfter. Rows with a NULL value in the date column match none of these conditions.
These conditions read Laravel's clock in UTC from the context when the query runs. When you need "today" in a specific user's timezone, query the range between the start and end of their day instead:
chicago, err := time.LoadLocation("America/Chicago")
if err != nil {
return err
}
start := date.TodayIn(ctx, chicago).In(chicago)
end := start.AddDate(0, 0, 1)
db.Table("orders").WhereGe("created_at", start).WhereLt("created_at", end)Full-text search
A like condition gets slow on large text columns and can't rank its matches. For a search box over articles or posts, use a full-text search instead. A db.FullText describes a search that matches rows whose columns contain the search terms as words, not as an exact substring. It runs on PostgreSQL, MySQL, and MariaDB. Filtering by a search with WhereFullText doesn't sort the results, so pass the same search to OrderByRelevance if you want the most relevant matches first:
func Search(r *web.Request) *web.Response {
var params struct {
Q string `json:"q"`
}
if err := r.QueryInto(¶ms); err != nil {
return web.Fail(err)
}
search := db.FullText{Columns: []string{"title", "body"}, Terms: params.Q}
posts, err := db.Table("posts").
WhereFullText(search).
OrderByRelevance(search).
Limit(10).
Get[Post](r)
if err != nil {
return web.Fail(err)
}
return web.JSON(posts)
}The columns need a full-text index on exactly the searched columns. Create it in a migration with table.FullText, such as table.FullText("title", "body").
You can customize how the database parses search terms with the Mode field of the db.FullText, and set PostgreSQL's text search configuration with its Language field, which is english unless you set another:
search := db.FullText{
Columns: []string{"title", "body"},
Terms: `"query builder" -legacy`,
Mode: db.WebSearch,
Language: "english",
}| Mode | Database | Description |
|---|---|---|
db.NaturalLanguage | PostgreSQL, MySQL, MariaDB | The default. PostgreSQL matches rows with every word, while MySQL and MariaDB match rows with any of them |
db.WebSearch | PostgreSQL | Search engine syntax: quotes for a phrase, or, and - to exclude a word |
db.Phrase | PostgreSQL | Match the words next to each other, in order |
db.Boolean | MySQL, MariaDB | Boolean mode: + before a required word, - before an excluded one, and * after a prefix |
db.Expanded | MySQL, MariaDB | Expand the search with words from the best matches |
A query that uses another database's mode fails when it runs. PostgreSQL stems words, so "running" finds "run". MySQL doesn't, so search for run* in db.Boolean mode to match word beginnings.
MySQL and MariaDB can't search rows that aren't committed yet, and a test's rows never commit, so a test that inserts the rows it searches finds nothing. Insert them in a seeder that the test runs with laraveltest.SeedOnce, whose rows are committed.
警告
db.Boolean mode fails with a syntax error on ordinary input such as taylor@example.com or C++. Use it only for terms your application writes. For text from a search box, use the default mode on MySQL, or db.WebSearch on PostgreSQL.
Vector similarity
Vector search finds rows by meaning rather than exact word matches. Store a vector embedding for each row, such as an embedding returned by an AI model, and query for the rows closest to a target embedding. Vector queries run on PostgreSQL with the pgvector extension and on MariaDB 11.7 or later. Create the column with table.Vector.
To store an embedding, wrap it in db.Vector, which is a []float32:
// The embedding your AI provider returns for the document's text...
embedding := []float32{0.12, -0.53, 0.88}
err := db.Table("documents").Insert(ctx, db.Values{
"title": "Napa Valley wineries",
"embedding": db.Vector(embedding),
})WhereVectorSimilarTo(column, embedding, minSimilarity) filters to rows whose similarity to the embedding is at least minSimilarity, ordering the closest matches first. Similarity scores range from 0 to 1, where 1 represents an exact match:
type Document struct {
ID int64 `json:"id"`
Title string `json:"title"`
Embedding db.Vector `json:"-"`
}
documents, err := db.Table("documents").
WhereVectorSimilarTo("embedding", embedding, 0.4).
Limit(10).
Get[Document](ctx)The embedding you search with must have as many dimensions as the column. To find the closest rows however similar they are, such as the five documents nearest to the document a reader is viewing, use OrderByVectorDistance("embedding", document.Embedding) with a limit. A stored vector scans into a db.Vector field, which you may pass to either method as it is.
Ordering, grouping, limit, and offset
OrderBy sorts query results by a column in ascending order, and OrderByDesc sorts in descending order. You may chain several calls to sort by more than one column:
db.Table("users").OrderByDesc("created_at").OrderBy("name")Latest and Oldest sort by a date column, newest or oldest first, which covers most feeds and activity logs:
db.Table("logins").Latest("created_at").Limit(10)Sort by columns that can't be NULL, such as created_at, because databases don't agree on where NULL goes.
To sort rows by a list of values in an order you choose, such as ticket statuses in the order your support team works through them, use InOrderOf. Rows whose value isn't in the list come last:
db.Table("tickets").InOrderOf("status", "escalated", "open", "pending").OrderBy("id")You may use InRandomOrder to sort rows in random order. To remove the orderings from a query you reuse, such as a shared feed query, call Reorder, and the OrderBy calls after it start a new ordering:
quote, err := db.Table("quotes").InRandomOrder().Value[string](ctx, "body")
newest := db.Table("posts").Latest("created_at")
byTitle := newest.Reorder().OrderBy("title")To sort in a direction from the request, such as ?direction=desc, parse it with db.ParseDirection and pass it to OrderByDirection. It accepts asc and desc in any case, and anything else is an error that responds with a 400:
var params struct {
Direction string `json:"direction"`
}
if err := r.QueryInto(¶ms); err != nil {
return web.Fail(err)
}
direction, err := db.ParseDirection(cmp.Or(params.Direction, "asc"))
if err != nil {
return web.Fail(err)
}
posts := db.Table("posts").OrderByDirection("title", direction)The GroupBy and Having methods group query results and filter the resulting groups. Repeat the aggregate expression in Having rather than referencing its alias, because PostgreSQL doesn't allow column aliases in having clauses. OrHaving joins a condition with or, and HavingRaw takes any other expression:
type authorCount struct {
UserID int64
Posts int64
}
authors, err := db.Table("posts").
Select("user_id").
SelectRaw("count(*) as posts").
GroupBy("user_id").
Having("count(*)", ">", 10).
Get[authorCount](ctx)You may use Limit and Offset to restrict how many rows are returned or skip a given number of rows. The ForPage(page, perPage) method sets both at once using 1-based page numbers:
db.Table("users").OrderBy("id").ForPage(3, 15) // limit 15 offset 30A page that lists posts often shows each post's newest comments. Limit(3) would give you three comments in all, so add LimitPer("post_id") to apply the limit to each post's comments instead. When you load comments through a model relationship, a constrained eager load with a limit does this for you:
newest := db.Table("comments").
WhereIn("post_id", postIDs).
Latest("created_at").
Limit(3).
LimitPer("post_id")To read the current page from the request and generate pagination links automatically, use Paginate instead. To learn more, check out the pagination guide.
Conditional clauses
Sometimes you may want query clauses to apply only when a condition is met, such as filtering by an optional parameter from an incoming request. When applies a function's clauses only when its condition is true. For example, this handler searches posts by any of the filters in the query string, and lists every post when the request has none:
func Search(r *web.Request) *web.Response {
var filters struct {
Title string `json:"title"`
Author int `json:"author"`
}
if err := r.QueryInto(&filters); err != nil {
return web.Fail(err)
}
posts, err := db.Table("posts").
When(filters.Title != "", func(q *db.Query) *db.Query {
return q.WhereLike("title", "%"+filters.Title+"%", false)
}).
When(filters.Author != 0, func(q *db.Query) *db.Query {
return q.WhereEq("user_id", filters.Author)
}).
Latest("created_at").
Get[Post](r)
if err != nil {
return web.Fail(err)
}
return web.JSON(posts)
}When several queries share the same constraints, extract them into a function that accepts and returns a *db.Query, and apply it with Scope:
func published(q *db.Query) *db.Query {
return q.WhereEq("status", "published").WhereNotNull("published_at")
}
posts := db.Table("posts").Scope(published).Latest("published_at").Limit(10)
count, err := db.Table("posts").Scope(published).WhereEq("user_id", 42).Count(ctx)Joins
You may join other tables to your query using Join, LeftJoin, and RightJoin. Each method accepts a table name, which may have an alias, and two columns to compare with an operator. In a joined query, name each column with its table, as in o.id, and scan a left join's columns into pointer fields, because they're NULL when no row matches:
type orderLine struct {
ID int64
Email string
Refunded *int64
}
lines, err := db.Table("orders as o").
Join("users as u", "u.id", "=", "o.user_id").
LeftJoin("refunds as r", "r.order_id", "=", "o.id").
Select("o.id", "u.email", "r.amount as refunded").
Get[orderLine](ctx)When a join needs more than one condition, such as only the approved refunds, use JoinOn, LeftJoinOn, or RightJoinOn. The function you pass adds the join's conditions, with WhereColumn for columns and the other Where methods for values:
refunds := db.Table("orders as o").
LeftJoinOn("refunds as r", func(q *db.Query) *db.Query {
return q.WhereColumn("r.order_id", "=", "o.id").WhereEq("r.status", "approved")
}).
Select("o.id", "r.amount as refunded")For a Cartesian product with no join condition, use CrossJoin:
variants := db.Table("sizes").CrossJoin("colors")You may also join against a subquery with JoinSub or LeftJoinSub, giving it an alias. For example, this query joins each user with the timestamp of their most recent post:
latest := db.Table("posts").
Select("user_id").
SelectRaw("max(created_at) as last_posted_at").
GroupBy("user_id")
authors := db.Table("users").
JoinSub(latest, "latest", "latest.user_id", "=", "users.id").
Select("users.name", "latest.last_posted_at")You may also pass a subquery and an alias to db.TableSub to query directly from a derived table, such as to find the customers who have spent more than 1,000 in total:
totals := db.Table("orders").Select("user_id").SelectRaw("sum(total) as spent").GroupBy("user_id")
bigSpenders, err := db.TableSub(totals, "totals").WhereGt("spent", 1000).Pluck[int64](ctx, "user_id")Unions
You may combine the results of two or more queries using Union, which removes duplicate rows, or UnionAll, which keeps all rows. The queries must select the same number of columns. The first query's order, limit, and offset apply to the combined result set, and Count, Exists, and the paginators count the combined rows:
noFirstName := db.Table("users").Select("id", "email").WhereNull("first_name")
type userEmail struct {
ID int64
Email string
}
users, err := db.Table("users").
Select("id", "email").
WhereNull("last_name").
Union(noFirstName).
OrderBy("id").
Get[userEmail](ctx)Raw expressions
Sometimes you may need to insert a SQL expression that the query builder doesn't directly model, such as a window function or custom arithmetic. The raw methods embed your SQL in the query, and bind a value for each ?, as a raw query does. To bind a list, pass it with db.In:
| Method | Adds |
|---|---|
SelectRaw(sql, args...) | A selected column |
WhereRaw(sql, args...), OrWhereRaw(sql, args...) | A condition, in parentheses |
HavingRaw(sql, args...) | A condition on the groups |
OrderByRaw(sql, args...) | An ordering |
multiplier, minimum := 1.5, 1000
seasons := []int{2025, 2026}
type rankedPlayer struct {
Name string
Position int64
}
ranked, err := db.Table("players").
Select("name").
SelectRaw("rank() over (order by score desc) as position").
WhereRaw("score * ? > ?", multiplier, minimum).
WhereRaw("season in (?)", db.In(seasons)).
OrderByRaw("score * ? desc", multiplier).
Get[rankedPlayer](ctx)To use an expression where a value goes, such as posts with more than twice as many votes as downvotes, wrap it in db.Raw. A db.Raw works as the value in Where, an insert, or an update:
db.Table("posts").WhereGt("votes", db.Raw("downvotes * ?", 2))警告
Laravel embeds a raw expression's SQL in the query verbatim. Pass input as an argument for a ?, and never build the SQL string from user input.
Inserts
The write methods below operate directly on database tables via db.Table. If you're working with models, use model.Create instead, so Laravel sets the model's timestamps for you. The query builder doesn't set timestamp columns such as created_at, so include them yourself.
Use Insert with a db.Values map from column names to values to insert a new row into a table:
err := db.Table("users").Insert(ctx, db.Values{
"name": "Taylor",
"email": "taylor@example.com",
"votes": 0,
})To insert multiple rows in a single statement, pass several db.Values that all specify the same columns. When the rows come from a slice, pass it with ...:
emails := []string{"taylor@example.com", "abigail@example.com", "jess@example.com"}
rows := make([]db.Values, len(emails))
for i, email := range emails {
rows[i] = db.Values{"email": email, "subscribed": true}
}
err := db.Table("subscribers").Insert(ctx, rows...)Because each value is sent as a bound parameter, very large batch inserts can hit your database's parameter limit. For large imports, split the rows into chunks, such as with slices.Chunk(rows, 1000), and run a separate Insert for each chunk.
If the table has an auto-incrementing ID, use InsertGetID to insert a row and retrieve its generated id, such as to redirect to the new row's page. On MySQL and MariaDB, id must be the table's auto-increment column:
func Store(r *web.Request) *web.Response {
var form struct {
Title string `json:"title"`
}
if err := r.BindInto(&form); err != nil {
return web.Fail(err)
}
now := date.Now(r)
id, err := db.Table("posts").InsertGetID(r, db.Values{
"title": form.Title,
"created_at": now,
"updated_at": now,
})
if err != nil {
return web.Fail(err)
}
return web.RedirectRoute("posts.show", "post", id)
}In your application, validate the input before you insert it.
To silently skip rows that would violate a unique index, use InsertOrIgnore. It returns how many rows it inserted:
inserted, err := db.Table("users").InsertOrIgnore(ctx,
db.Values{"id": 1, "email": "taylor@example.com"},
db.Values{"id": 2, "email": "abigail@example.com"},
)To insert rows directly from the results of another query, use InsertUsing. It fills the columns you name in the same order as the subquery's selected columns, and returns how many rows it inserted:
inactive := db.Table("users").Select("id", "email").WhereEq("active", false)
archived, err := db.Table("archived_users").InsertUsing(ctx, []string{"user_id", "email"}, inactive)Upserts
The Upsert method inserts rows that don't exist yet and updates matching rows that already do. The first argument after the context provides the rows to insert, the second lists the unique columns that identify existing records, and the third lists the columns to update when a matching row is found:
_, err := db.Table("flights").Upsert(ctx,
[]db.Values{
{"departure": "Oakland", "destination": "San Diego", "price": 99},
{"departure": "Chicago", "destination": "New York", "price": 150},
},
[]string{"departure", "destination"},
[]string{"price"},
)The identifying columns must have a unique index. Pass nil as the last argument to update every column that isn't one of them.
When you need to compute updated values from the existing row rather than replacing them outright, use UpsertSet, which takes the values to set instead of a list of columns, and reference the incoming values with db.Excluded(column). Qualify existing columns with the table name so PostgreSQL can distinguish them from incoming values. For example, this upsert increments a page's view count when the path already exists:
_, err := db.Table("page_views").UpsertSet(ctx,
[]db.Values{{"path": "/", "views": 1}},
[]string{"path"},
db.Values{"views": db.Raw("page_views.views + ?", db.Excluded("views"))},
)Updates
Use Update with db.Values to modify rows matching your query constraints. It returns the number of matched rows, and each value may be a Go value, a db.Raw expression, or a validation.Sometimes field (which writes the value when present and omits the column when absent):
_, err := db.Table("users").
WhereEq("id", 1).
Update(ctx, db.Values{"votes": db.Raw("votes + ?", 1), "name": "Taylor"})For updating numeric columns such as counters or balances, the query builder provides Increment and Decrement. For money and other exact amounts, pass a numeric.Decimal:
_, err := db.Table("users").WhereEq("id", 1).Increment(ctx, "votes", 5)
_, err = db.Table("accounts").WhereEq("id", 42).Decrement(ctx, "balance", numeric.MustParse("25.00"))To update a single field inside a JSON column without overwriting the rest of the document, use -> syntax in the column key:
_, err := db.Table("users").WhereEq("id", 1).Update(ctx, db.Values{"options->theme": "dark"})If you want to update an existing record or insert it if no matching record exists, use UpdateOrInsert. The first db.Values argument defines the attributes used to locate an existing row, and the second provides the values to update or insert:
err := db.Table("users").UpdateOrInsert(ctx,
db.Values{"email": "taylor@example.com"},
db.Values{"name": "Taylor", "votes": 2},
)Because UpdateOrInsert checks for a matching row before writing, two concurrent requests may both insert. Prefer Upsert when you need atomic conflict handling.
Table-level updates and deletes can't include joins, groups, ordering, or limits, and return an error if they do. If you need to constrain a write using those clauses, filter by a subquery such as WhereIn("id", db.Table(...)) instead.
Deletes
Use Delete to remove rows matching your query constraints. It returns the number of deleted rows. To remove every row from a table and reset its auto-increment counter, call Truncate:
_, err := db.Table("users").WhereLt("votes", 10).Delete(ctx)
err = db.Table("sessions").Truncate(ctx)On PostgreSQL and MySQL, Truncate fails on a table that another table's foreign key refers to, so empty such a table with Delete instead.
Connections and transactions
Queries run against your default database connection unless the context selects another configured connection. Use db.Connection to get a context whose queries run on a connection by name:
reporting := db.Connection(ctx, "reporting")
signups, err := db.Table("events").WhereEq("kind", "signup").Count(reporting)Inside a db.Transaction function, every query you run with the function's context runs within the transaction, so all statements commit or roll back together:
func Transfer(ctx context.Context, from, to, amount int64) error {
return db.Transaction(ctx, func(ctx context.Context) error {
_, err := db.Table("accounts").
WhereEq("id", from).
Decrement(ctx, "balance", amount)
if err != nil {
return err
}
_, err = db.Table("accounts").
WhereEq("id", to).
Increment(ctx, "balance", amount)
if err != nil {
return err
}
return db.Table("transfers").Insert(ctx, db.Values{
"from_id": from,
"to_id": to,
"amount": amount,
})
})
}When a connection is configured with read and write connections, read queries use a replica automatically. To force a specific query to read from the writer instead, such as for a row another request has just written, run it on db.Writer(r):
order, err := db.Table("orders").On(db.Writer(r)).Find[Order](r, id)Pessimistic locking
When two concurrent requests read and update the same row, such as an account balance, one write can silently overwrite the other. Inside a transaction, you can prevent race conditions with LockForUpdate, which blocks other transactions from changing or locking the selected rows until your transaction ends, or SharedLock, which allows other reads while preventing changes:
var ErrInsufficientFunds = errors.New("the account's balance is too low")
func Withdraw(ctx context.Context, id, amount int64) error {
return db.Transaction(ctx, func(ctx context.Context) error {
balance, err := db.Table("accounts").
WhereEq("id", id).
LockForUpdate().
Value[int64](ctx, "balance")
if err != nil {
return err
}
if balance < amount {
return ErrInsufficientFunds
}
_, err = db.Table("accounts").WhereEq("id", id).Decrement(ctx, "balance", amount)
return err
})
}Locking queries always run against the writer. SQLite doesn't support row-level locks, so both methods do nothing there, but because it permits only one writer at a time, you can safely retry contested transactions with db.TransactionWithAttempts.
By default, a locking query waits until conflicting locks are released. Call SkipLocked to omit rows locked by other transactions, which is useful when multiple workers claim jobs from a shared table, or NoWait to fail immediately when a row is locked. For that error, db.FailureOf returns db.LockTimeout. Both methods lock the rows for update when the query has no lock of its own. On MySQL, both methods require MySQL 8.0 or later, and on MariaDB, they require MariaDB 10.6 or later:
id, err := db.Table("exports").
WhereNull("started_at").
OrderBy("id").
SkipLocked().
Value[int64](ctx, "id")Debugging
To inspect the SQL and bound values a query will send to the database without running it, call ToSQL:
sql, args, err := db.Table("users").WhereGt("votes", 100).ToSQL(ctx)
// On PostgreSQL, sql is: select * from "users" where "votes" > $1
// and args is []any{100}.To see every query your application runs, set LOG_LEVEL to debug. To act on each query, such as to report the slow ones, register a query listener.