Skip to content

Query Builder

Database

Database: Query Builder

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 fluently in Rust and decode typed rows back.

Laravel generates the SQL for your active database driver, binds all values as parameters, and runs the query across PostgreSQL, MySQL, MariaDB, and 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 apply to model queries as well.

You may use db::table to begin a query for a table. It returns a fluent query builder, allowing you to chain constraints onto the query before retrieving the results with get. For example, this handler lists the ten most recent active users:

1use laravel::db::{self, col};
2use laravel::prelude::*;
3use serde::Serialize;
4 
5#[derive(db::FromRow, Serialize)]
6struct User {
7 id: i64,
8 name: String,
9 email: String,
10}
11 
12pub async fn index() -> laravel::Result<Json<Vec<User>>> {
13 let users: Vec<User> = db::table("users")
14 .filter(col("active").eq(true) & col("votes").gt(100))
15 .order_by(col("created_at").desc())
16 .limit(10)
17 .get()
18 .await?;
19 
20 Ok(Json(users))
21}
1use laravel::db::{self, col};
2use laravel::prelude::*;
3use serde::Serialize;
4 
5#[derive(db::FromRow, Serialize)]
6struct User {
7 id: i64,
8 name: String,
9 email: String,
10}
11 
12pub async fn index() -> laravel::Result<Json<Vec<User>>> {
13 let users: Vec<User> = db::table("users")
14 .filter(col("active").eq(true) & col("votes").gt(100))
15 .order_by(col("created_at").desc())
16 .limit(10)
17 .get()
18 .await?;
19 
20 Ok(Json(users))
21}

A query is an ordinary Rust value. You may store it, return it from a function, and clone it. Nothing reaches the database until you await a method such as get, count, or update, and running a query only borrows it, so one query can count rows and then fetch them:

1let active = db::table("users").filter(col("active").eq(true));
2 
3let total = active.count().await?;
4let users: Vec<User> = active.order_by("id").limit(20).get().await?;
1let active = db::table("users").filter(col("active").eq(true));
2 
3let total = active.count().await?;
4let users: Vec<User> = active.order_by("id").limit(20).get().await?;

Running queries

Retrieving rows

get maps every row with db::FromRow, so a query returns structs, or single values when it selects one column:

Method Returns
get::<T>() Every row, as Vec<T>
first::<T>() The first row, or None
find::<T>(id) The row whose id column equals id, or None
sole::<T>() The only matching row. Fails with a 404 when no row matches, and a 500 when several do
value::<T>(column) One column of the first row, or None
pluck::<T>(column) One column of every row, as Vec<T>
exists() Whether any row matches

Specify the row type with a type annotation or turbofish, such as first::<User>():

1let user: Option<User> = db::table("users").find(42).await?;
2 
3let email: Option<String> = db::table("users")
4 .filter(col("name").eq("Taylor"))
5 .value("email")
6 .await?;
7 
8let titles: Vec<String> = db::table("posts")
9 .filter(col("featured").eq(true))
10 .pluck("title")
11 .await?;
1let user: Option<User> = db::table("users").find(42).await?;
2 
3let email: Option<String> = db::table("users")
4 .filter(col("name").eq("Taylor"))
5 .value("email")
6 .await?;
7 
8let titles: Vec<String> = db::table("posts")
9 .filter(col("featured").eq(true))
10 .pluck("title")
11 .await?;

To turn a missing row into a 404 response, use or_abort from the prelude:

1pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<User>> {
2 let user: User = db::table("users").find(id).await?.or_abort(404)?;
3 
4 Ok(Json(user))
5}
1pub async fn show(Params(id): Params<i64>) -> laravel::Result<Json<User>> {
2 let user: User = db::table("users").find(id).await?.or_abort(404)?;
3 
4 Ok(Json(user))
5}

You may also decode rows into a tuple, matching the selected columns in order. For example, you can select two columns as pairs and collect them into a HashMap:

1use std::collections::HashMap;
2 
3let titles: HashMap<String, String> = db::table("roles")
4 .select(["name", "title"])
5 .get::<(String, String)>()
6 .await?
7 .into_iter()
8 .collect();
1use std::collections::HashMap;
2 
3let titles: HashMap<String, String> = db::table("roles")
4 .select(["name", "title"])
5 .get::<(String, String)>()
6 .await?
7 .into_iter()
8 .collect();

Aggregates

count returns a u64, and avg returns Option<f64>. min, max, and sum are generic over the column's decoded type and return Option<T> (for any type implementing db::Decode), returning None when no rows match:

1use laravel::numeric::Decimal;
2 
3let users: u64 = db::table("users").count().await?;
4 
5let highest: Option<i64> = db::table("users").max("votes").await?;
6 
7let revenue: Option<Decimal> = db::table("orders")
8 .filter(col("status").eq("paid"))
9 .sum("total")
10 .await?;
11 
12let rating: Option<f64> = db::table("reviews").avg("stars").await?;
1use laravel::numeric::Decimal;
2 
3let users: u64 = db::table("users").count().await?;
4 
5let highest: Option<i64> = db::table("users").max("votes").await?;
6 
7let revenue: Option<Decimal> = db::table("orders")
8 .filter(col("status").eq("paid"))
9 .sum("total")
10 .await?;
11 
12let rating: Option<f64> = db::table("reviews").avg("stars").await?;

A sum of integers decodes into i64 or Decimal, and a sum of decimals into Decimal. To count distinct values, select col("user_id").count_distinct().

Chunking and streaming

When you need to work through thousands of rows, you don't want them all in memory at once. chunk_by_id returns a stream of pages of rows, ordered by an integer key. Each page starts after the last key of the previous one, so the loop may update or delete the rows it reads:

1use laravel::db::{self, col, values};
2use laravel::stream::TryStreamExt;
3 
4let mut pages = db::table("users")
5 .filter(col("active").eq(false))
6 .chunk_by_id::<User>(100, "id");
7 
8while let Some(users) = pages.try_next().await? {
9 let ids: Vec<i64> = users.iter().map(|user| user.id).collect();
10 
11 db::table("users")
12 .filter(col("id").is_in(&ids))
13 .update(values! { archived: true })
14 .await?;
15}
1use laravel::db::{self, col, values};
2use laravel::stream::TryStreamExt;
3 
4let mut pages = db::table("users")
5 .filter(col("active").eq(false))
6 .chunk_by_id::<User>(100, "id");
7 
8while let Some(users) = pages.try_next().await? {
9 let ids: Vec<i64> = users.iter().map(|user| user.id).collect();
10 
11 db::table("users")
12 .filter(col("id").is_in(&ids))
13 .update(values! { archived: true })
14 .await?;
15}

The query must select the key column. To iterate from highest to lowest key, pass col("id").desc() instead of "id". lazy_by_id takes the same arguments and yields one row at a time while still querying one page at a time:

1let mut newest_first = db::table("users").lazy_by_id::<User>(500, col("id").desc());
2 
3while let Some(user) = newest_first.try_next().await? {
4 println!("{}: {}", user.id, user.name);
5}
1let mut newest_first = db::table("users").lazy_by_id::<User>(500, col("id").desc());
2 
3while let Some(user) = newest_first.try_next().await? {
4 println!("{}: {}", user.id, user.name);
5}

chunk(size) pages with a limit and an offset instead, so the query needs an order_by. 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 stream ends.

Select statements

You may not always want to select every column from a database table. Use select to specify the columns you need (including optional as aliases), add_select to append more columns to an existing select clause, and distinct to return only unique rows:

1let users = db::table("users")
2 .select(["id", "users.name as author"])
3 .add_select(["email"])
4 .distinct();
1let users = db::table("users")
2 .select(["id", "users.name as author"])
3 .add_select(["email"])
4 .distinct();

An array holds items of one type. To mix names and expressions, pass a tuple:

1let totals = db::table("orders")
2 .select(("user_id", col("total").sum().alias("lifetime_total")))
3 .group_by(["user_id"]);
1let totals = db::table("orders")
2 .select(("user_id", col("total").sum().alias("lifetime_total")))
3 .group_by(["user_id"]);

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

filter restricts the query to rows matching a condition. Build conditions using col and a comparison method:

1db::table("users").filter(col("votes").ge(100));
1db::table("users").filter(col("votes").ge(100));
Method SQL
eq, ne =, <>
lt, le, gt, ge <, <=, >, >=
like like, or ilike on PostgreSQL
starts_with, ends_with, contains like with % and _ escaped automatically
like_case_sensitive like, or glob on SQLite
is_in, is_not_in in (...), not in (...)
is_null, is_not_null is null, is not null
between between ... and ...

The argument of a comparison is a value, so a string there is a bound parameter. To compare two columns, wrap the other column in col too:

1db::table("posts").filter(col("updated_at").gt(col("created_at")));
1db::table("posts").filter(col("updated_at").gt(col("created_at")));

like matches a pattern, ignoring case with each database's default settings. For literal prefix, suffix, or substring matching against user input, use starts_with, ends_with, or contains, which escape %, _, and \ automatically.

When case matters, such as for coupon codes, use like_case_sensitive. It distinguishes SUMMER25 from summer25 on every database regardless of the column's collation:

1db::table("coupons").filter(col("code").like_case_sensitive("SUMMER%"));
1db::table("coupons").filter(col("code").like_case_sensitive("SUMMER%"));

On SQLite, its pattern must be a value, such as a string, rather than another column.

is_null and is_not_null check for NULL and NOT NULL. Comparing with None (such as an Option field) also writes is null:

1db::table("users").filter(col("email_verified_at").is_not_null());
1db::table("users").filter(col("email_verified_at").is_not_null());

In SQL, col("team_id").ne(2) leaves out rows where team_id is NULL. When you want those rows included, use is_distinct_from, which treats NULL as a value of its own:

1let team_id: Option<i64> = Some(2);
2 
3db::table("users").filter(col("team_id").is_distinct_from(team_id));
1let team_id: Option<i64> = Some(2);
2 
3db::table("users").filter(col("team_id").is_distinct_from(team_id));

For database-specific or custom operators that don't have a dedicated method, such as PostgreSQL's regex operator (~*), pass a db::raw! condition to filter:

1db::table("users").filter(db::raw!("email ~* {pattern}"));
1db::table("users").filter(db::raw!("email ~* {pattern}"));

Combining conditions

Combine conditions with & for and, | for or, and ! for not. Operator precedence matches SQL, so a & b | c evaluates as (a and b) or c, and you may wrap sub-expressions in parentheses to group conditions explicitly:

1use laravel::time::Timestamp;
2 
3let since: Timestamp = "2026-10-01T00:00:00Z".parse()?;
4 
5let posts = db::table("posts")
6 .filter(col("published").eq(true))
7 .filter(
8 col("status").eq("featured")
9 | (col("votes").ge(50) & col("created_at").gt(since)),
10 );
1use laravel::time::Timestamp;
2 
3let since: Timestamp = "2026-10-01T00:00:00Z".parse()?;
4 
5let posts = db::table("posts")
6 .filter(col("published").eq(true))
7 .filter(
8 col("status").eq("featured")
9 | (col("votes").ge(50) & col("created_at").gt(since)),
10 );
1select * from "posts"
2where "published" = $1
3 and ("status" = $2 or ("votes" >= $3 and "created_at" > $4))
1select * from "posts"
2where "published" = $1
3 and ("status" = $2 or ("votes" >= $3 and "created_at" > $4))

Multiple filter calls are combined with and, and each call is wrapped in its own parentheses in the generated SQL. Because each call is isolated this way, an or (|) inside one filter call will never bypass constraints added by another filter call.

A condition is a value, so you may name it, pass it to a function, and build it in a loop. db::any and db::all combine a list of conditions, and filter skips None values, which is handy when building search forms with optional filters:

1use laravel::db::{self, Condition, col};
2use laravel::prelude::*;
3 
4#[laravel::input]
5#[validate(anyone)]
6pub struct UserSearch {
7 role: Option<String>,
8 name: Option<String>,
9 email: Option<String>,
10}
11 
12pub async fn index(search: Valid<UserSearch>) -> laravel::Result<Json<Vec<User>>> {
13 let terms: Vec<Condition> = [
14 search.name.as_deref().map(|name| col("name").contains(name)),
15 search.email.as_deref().map(|email| col("email").contains(email)),
16 ]
17 .into_iter()
18 .flatten()
19 .collect();
20 
21 let users = db::table("users")
22 .filter(search.role.as_deref().map(|role| col("role").eq(role)))
23 .when(!terms.is_empty(), |query| query.filter(db::any(terms)))
24 .get()
25 .await?;
26 
27 Ok(Json(users))
28}
1use laravel::db::{self, Condition, col};
2use laravel::prelude::*;
3 
4#[laravel::input]
5#[validate(anyone)]
6pub struct UserSearch {
7 role: Option<String>,
8 name: Option<String>,
9 email: Option<String>,
10}
11 
12pub async fn index(search: Valid<UserSearch>) -> laravel::Result<Json<Vec<User>>> {
13 let terms: Vec<Condition> = [
14 search.name.as_deref().map(|name| col("name").contains(name)),
15 search.email.as_deref().map(|email| col("email").contains(email)),
16 ]
17 .into_iter()
18 .flatten()
19 .collect();
20 
21 let users = db::table("users")
22 .filter(search.role.as_deref().map(|role| col("role").eq(role)))
23 .when(!terms.is_empty(), |query| query.filter(db::any(terms)))
24 .get()
25 .await?;
26 
27 Ok(Json(users))
28}

The handler checks for an empty list before it filters, because db::any of no conditions matches no rows, while an empty search form should show everyone. db::all of no conditions matches every row.

Lists and ranges

is_in and is_not_in take an array, a Vec, a slice, or a reference to one. An empty is_in list matches no rows, and an empty is_not_in list matches every row:

1let ids = vec![3, 7, 42];
2 
3db::table("users").filter(col("id").is_in(&ids));
4db::table("posts").filter(col("status").is_not_in(["draft", "archived"]));
1let ids = vec![3, 7, 42];
2 
3db::table("users").filter(col("id").is_in(&ids));
4db::table("posts").filter(col("status").is_not_in(["draft", "archived"]));

between takes an inclusive range. Its bounds may be values or columns:

1db::table("users").filter(col("votes").between(1, 100));
2db::table("patients").filter(col("weight").between(col("min_weight"), col("max_weight")));
1db::table("users").filter(col("votes").between(1, 100));
2db::table("patients").filter(col("weight").between(col("min_weight"), col("max_weight")));

Subqueries and exists

You may pass another query directly into is_in to filter against a subquery's results, or pass a scalar subquery anywhere a comparison expects a value:

1let user_id = 42;
2 
3let following = db::table("follows")
4 .select(["followed_id"])
5 .filter(col("follower_id").eq(user_id));
6 
7let feed = db::table("posts").filter(col("user_id").is_in(following));
8 
9let largest = db::table("orders").select([col("total").max()]);
10 
11let biggest_orders = db::table("orders").filter(col("total").eq(largest));
1let user_id = 42;
2 
3let following = db::table("follows")
4 .select(["followed_id"])
5 .filter(col("follower_id").eq(user_id));
6 
7let feed = db::table("posts").filter(col("user_id").is_in(following));
8 
9let largest = db::table("orders").select([col("total").max()]);
10 
11let biggest_orders = db::table("orders").filter(col("total").eq(largest));

When you want to put a subquery or a plain value on the left side of a comparison, wrap it in db::expr. For example, this query retrieves all users whose plan is named "Pro":

1let plan = db::table("plans")
2 .select(["name"])
3 .filter(col("plans.id").eq(col("users.plan_id")));
4 
5let pro_users = db::table("users").filter(db::expr(plan).eq("Pro"));
1let plan = db::table("plans")
2 .select(["name"])
3 .filter(col("plans.id").eq(col("users.plan_id")));
4 
5let pro_users = db::table("users").filter(db::expr(plan).eq("Pro"));

To select a subquery's value as a column, give it a name with alias. For example, this query selects each user's name along with their total number of posts as posts_count:

1let posts = db::table("posts")
2 .select([col("*").count()])
3 .filter(col("posts.user_id").eq(col("users.id")));
4 
5let users = db::table("users").select(("name", posts.alias("posts_count")));
1let posts = db::table("posts")
2 .select([col("*").count()])
3 .filter(col("posts.user_id").eq(col("users.id")));
4 
5let users = db::table("users").select(("name", posts.alias("posts_count")));

If you want to keep all of the table's columns and append the subquery as an extra column, pass the subquery to add_select:

1let users = db::table("users").add_select([posts.alias("posts_count")]);
1let users = db::table("users").add_select([posts.alias("posts_count")]);

To sort rows by a subquery's value, call asc or desc on the subquery inside order_by. For example, this query lists users by their most recent login, starting with the user who logged in last:

1let last_login = db::table("logins")
2 .select([col("created_at").max()])
3 .filter(col("logins.user_id").eq(col("users.id")));
4 
5let users = db::table("users").order_by(last_login.desc());
1let last_login = db::table("logins")
2 .select([col("created_at").max()])
3 .filter(col("logins.user_id").eq(col("users.id")));
4 
5let users = db::table("users").order_by(last_login.desc());

db::exists matches rows for which a subquery returns at least one row, and you may reference the outer query's columns with col. For example, this query retrieves every user who has placed at least one order:

1let customers = db::table("users")
2 .filter(db::exists(db::table("orders").filter(col("orders.user_id").eq(col("users.id")))));
1let customers = db::table("users")
2 .filter(db::exists(db::table("orders").filter(col("orders.user_id").eq(col("users.id")))));

JSON columns

Use -> in a column name to read inside a JSON column, and [n] for an array element:

1db::table("users").filter(col("options->language").eq("en"));
2db::table("users").filter(col("options->languages[0]").eq("en"));
3db::table("users").filter(col("options->notifications->mentions").eq(true));
1db::table("users").filter(col("options->language").eq("en"));
2db::table("users").filter(col("options->languages[0]").eq("en"));
3db::table("users").filter(col("options->notifications->mentions").eq(true));

Compare with the type the document holds: a number for a JSON number, and a string for a JSON string. On SQLite, col("options->size").eq("3") doesn't match {"size": 3}.

You may also query JSON arrays and object keys using json_contains, json_has_key, and json_length. Like other conditions, json_contains and json_has_key may be negated with !:

1db::table("users").filter(col("options->languages").json_contains("en"));
2db::table("users").filter(col("options->languages").json_contains(["en", "de"]));
3db::table("users").filter(!col("options->theme").json_has_key());
4db::table("users").filter(col("options->languages").json_length().gt(1));
1db::table("users").filter(col("options->languages").json_contains("en"));
2db::table("users").filter(col("options->languages").json_contains(["en", "de"]));
3db::table("users").filter(!col("options->theme").json_has_key());
4db::table("users").filter(col("options->languages").json_length().gt(1));

On PostgreSQL, MySQL, and MariaDB, json_contains can also match partial JSON objects, such as col("options").json_contains(json!({ "theme": "dark" })). SQLite supports only single values and arrays of values, so passing a JSON object returns an error.

A selected JSON path decodes into a String when it holds text. PostgreSQL, MySQL, and MariaDB return extracted JSON numbers and booleans as text, whereas SQLite returns them as numbers (1 or 0 for booleans), so compare non-text JSON values in a condition rather than selecting them directly.

Dates

You may extract part of a date or timestamp column using date, time, year, month, or day to filter or select by that component:

1use laravel::time::civil::Date;
2 
3let halloween: Date = "2026-10-31".parse()?;
4 
5db::table("orders").filter(col("created_at").date().eq(halloween));
6db::table("orders").filter(col("created_at").year().eq(2026));
1use laravel::time::civil::Date;
2 
3let halloween: Date = "2026-10-31".parse()?;
4 
5db::table("orders").filter(col("created_at").date().eq(halloween));
6db::table("orders").filter(col("created_at").year().eq(2026));

Many date conditions compare with the current time, such as the invoices that are overdue or the orders placed today. is_past and is_future compare a column with laravel::now(). is_today, is_before_today, and is_after_today compare its date with today's date:

1db::table("invoices").filter(col("due_at").is_past() & col("paid_at").is_null());
2db::table("orders").filter(col("created_at").is_today());
3db::table("events").filter(col("starts_at").is_after_today());
1db::table("invoices").filter(col("due_at").is_past() & col("paid_at").is_null());
2db::table("orders").filter(col("created_at").is_today());
3db::table("events").filter(col("starts_at").is_after_today());

Negate a condition with ! to include the present: !col("starts_at").is_future() matches events that start now or earlier, and !col("due_at").is_before_today() matches invoices due today or later. Rows with a NULL value in the date column are excluded even when the condition is negated.

These helpers evaluate against Laravel's application clock in UTC when the condition is built. When you need "today" in a specific user's timezone, query the range between the start and end of their day instead:

1use laravel::time::{Dates, ToSpan};
2 
3let start = laravel::now().in_tz("America/Chicago")?.start_of_day()?;
4let end = start.plus(1.day());
5 
6db::table("orders").filter(col("created_at").ge(&start) & col("created_at").lt(&end));
1use laravel::time::{Dates, ToSpan};
2 
3let start = laravel::now().in_tz("America/Chicago")?.start_of_day()?;
4let end = start.plus(1.day());
5 
6db::table("orders").filter(col("created_at").ge(&start) & col("created_at").lt(&end));

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. db::search(columns, terms) is a condition 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 does not sort the results, so pass the same search to order_by if you want the most relevant matches first:

1let search = db::search(["title", "body"], "query builder");
2 
3let articles = db::table("articles").filter(search.clone()).order_by(search).limit(10);
1let search = db::search(["title", "body"], "query builder");
2 
3let articles = db::table("articles").filter(search.clone()).order_by(search).limit(10);

The columns need a full-text index on exactly the searched columns. Create it in a migration with table.full_text, such as table.full_text(["title", "body"]).

You can customize how the database parses search terms by chaining a variety of methods on db::search:

1let search = db::search(["title", "body"], "\"query builder\" -legacy")
2 .language("english")
3 .websearch();
4 
5let articles = db::table("articles")
6 .select(("title", search.relevance().alias("score")))
7 .filter(search.clone())
8 .order_by(search)
9 .limit(10);
1let search = db::search(["title", "body"], "\"query builder\" -legacy")
2 .language("english")
3 .websearch();
4 
5let articles = db::table("articles")
6 .select(("title", search.relevance().alias("score")))
7 .filter(search.clone())
8 .order_by(search)
9 .limit(10);
Method Database Description
websearch() PostgreSQL Search engine syntax: quotes for a phrase, or, and - to exclude a word
phrase() PostgreSQL Match the words next to each other, in order
language(name) PostgreSQL Set the text search configuration (english by default)
boolean() MySQL, MariaDB Boolean mode: + before a required word, - before an excluded one, and * after a prefix
expanded() MySQL, MariaDB Expand the search with words from the best matches
relevance() PostgreSQL, MySQL, MariaDB Return the relevance score as an expression you may select

A query that uses another database's method fails when it runs. PostgreSQL stems words, so "running" finds "run". MySQL doesn't, so search for run* with boolean() to match word beginnings.

MySQL's boolean() mode fails with a syntax error on ordinary input such as [email protected] or C++. Use it only for terms your application writes. For text from a search box, use the default mode on MySQL, or 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.

To store an embedding, wrap it in db::vector:

1use laravel::db::{self, values};
2 
3// The embedding your AI provider returns for the document's text...
4let embedding: Vec<f32> = vec![0.12, -0.53, 0.88];
5 
6db::table("documents")
7 .insert(values! { title: "Napa Valley wineries", embedding: db::vector(&embedding) })
8 .await?;
1use laravel::db::{self, values};
2 
3// The embedding your AI provider returns for the document's text...
4let embedding: Vec<f32> = vec![0.12, -0.53, 0.88];
5 
6db::table("documents")
7 .insert(values! { title: "Napa Valley wineries", embedding: db::vector(&embedding) })
8 .await?;

similar_to(column, embedding, min_similarity) filters to rows whose similarity to the embedding is at least min_similarity, ordering the closest matches first. Cosine similarity ranges from -1 to 1. Vectors pointing in the same direction score 1, perpendicular vectors score 0, and vectors pointing in opposite directions score -1:

1#[derive(db::FromRow)]
2pub struct Document {
3 id: i64,
4 title: String,
5}
6 
7let documents: Vec<Document> = db::table("documents")
8 .similar_to("embedding", &embedding, 0.4)
9 .limit(10)
10 .get()
11 .await?;
1#[derive(db::FromRow)]
2pub struct Document {
3 id: i64,
4 title: String,
5}
6 
7let documents: Vec<Document> = db::table("documents")
8 .similar_to("embedding", &embedding, 0.4)
9 .limit(10)
10 .get()
11 .await?;

The embedding you search with must have as many dimensions as the column. For more control, col("embedding").cosine_distance(&embedding) is an expression you may select, filter, and order by. To read a stored vector back, decode it into db::Vector, which you may pass to similar_to as it is.

Ordering, grouping, limit, and offset

The order_by method sorts query results by a given column. Passing a column name sorts in ascending order, or you may pass a col expression with .asc() or .desc() to choose the direction. You may chain multiple order_by calls to sort by more than one column:

1db::table("users").order_by(col("created_at").desc()).order_by("name");
1db::table("users").order_by(col("created_at").desc()).order_by("name");

latest and oldest sort by a date column, newest or oldest first, which covers most feeds and activity logs:

1db::table("logins").latest("created_at").limit(10);
1db::table("logins").latest("created_at").limit(10);

Like order_by, latest and oldest also accept column expressions and raw SQL. For example, you might sort forum threads by their most recent reply, falling back to created_at when a thread has no replies yet:

1db::table("threads").latest(db::raw!("coalesce(last_reply_at, created_at)"));
1db::table("threads").latest(db::raw!("coalesce(last_reply_at, created_at)"));

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 in_order_of. Rows whose value isn't in the list come last. The values may be strings, numbers, or enums that derive Enum:

1db::table("tickets").in_order_of("status", ["escalated", "open", "pending"]).order_by("id");
1db::table("tickets").in_order_of("status", ["escalated", "open", "pending"]).order_by("id");

You may use db::random() to sort rows in random order:

1let quote: Option<String> = db::table("quotes").order_by(db::random()).value("body").await?;
1let quote: Option<String> = db::table("quotes").order_by(db::random()).value("body").await?;

To remove any existing order_by clauses from a query and optionally apply a new ordering, call unordered:

1let query = db::table("users").order_by("name");
2 
3let unordered_users: Vec<User> = query.clone().unordered().get().await?;
4let reordered_users: Vec<User> = query.unordered().order_by("email").get().await?;
1let query = db::table("users").order_by("name");
2 
3let unordered_users: Vec<User> = query.clone().unordered().get().await?;
4let reordered_users: Vec<User> = query.unordered().order_by("email").get().await?;

The group_by and having methods may be used to group query results and filter the resulting groups. Repeat the aggregate expression in having rather than referencing its alias, because PostgreSQL does not allow column aliases in HAVING clauses:

1let busy_days = db::table("orders")
2 .select((col("created_at").date().alias("day"), col("*").count().alias("orders")))
3 .group_by([col("created_at").date()])
4 .having(col("*").count().gt(100));
1let busy_days = db::table("orders")
2 .select((col("created_at").date().alias("day"), col("*").count().alias("orders")))
3 .group_by([col("created_at").date()])
4 .having(col("*").count().gt(100));

You may use limit and offset to restrict how many rows are returned or skip a given number of rows. The for_page(page, per_page) method sets both at once using 1-based page numbers:

1db::table("users").order_by("id").for_page(3, 15); // limit 15 offset 30
1db::table("users").order_by("id").for_page(3, 15); // limit 15 offset 30

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. Use when to apply clauses when a boolean is true, and when_some to apply them when an Option contains a value:

1let only_verified = true;
2let per_page: Option<u64> = Some(25);
3 
4let users = db::table("users")
5 .when(only_verified, |query| query.filter(!col("email_verified_at").is_null()))
6 .when_some(per_page, |query, per_page| query.limit(per_page));
1let only_verified = true;
2let per_page: Option<u64> = Some(25);
3 
4let users = db::table("users")
5 .when(only_verified, |query| query.filter(!col("email_verified_at").is_null()))
6 .when_some(per_page, |query, per_page| query.limit(per_page));

When several queries share the same constraints, extract them into a helper function that accepts and returns a db::Builder:

1use laravel::db::{self, col};
2 
3fn published(query: db::Builder) -> db::Builder {
4 query.filter(col("published").eq(true) & !col("published_at").is_null())
5}
6 
7let posts = published(db::table("posts")).latest("published_at").limit(10);
8let count = published(db::table("posts")).filter(col("user_id").eq(42)).count().await?;
1use laravel::db::{self, col};
2 
3fn published(query: db::Builder) -> db::Builder {
4 query.filter(col("published").eq(true) & !col("published_at").is_null())
5}
6 
7let posts = published(db::table("posts")).latest("published_at").limit(10);
8let count = published(db::table("posts")).filter(col("user_id").eq(42)).count().await?;

Joins

You may join other tables to your query using join, left_join, and right_join. Each method accepts a table name (with an optional alias) and a join condition built with the same condition API as filter. For example, this query joins orders with their users and any approved refunds:

1let lines = db::table("orders as o")
2 .join("users as u", col("u.id").eq(col("o.user_id")))
3 .left_join(
4 "refunds as r",
5 col("r.order_id").eq(col("o.id")) & col("r.status").eq("approved"),
6 )
7 .select(["o.id", "u.email", "r.amount as refunded"]);
1let lines = db::table("orders as o")
2 .join("users as u", col("u.id").eq(col("o.user_id")))
3 .left_join(
4 "refunds as r",
5 col("r.order_id").eq(col("o.id")) & col("r.status").eq("approved"),
6 )
7 .select(["o.id", "u.email", "r.amount as refunded"]);

For a Cartesian product with no join condition, use cross_join:

1let variants = db::table("sizes").cross_join("colors");
1let variants = db::table("sizes").cross_join("colors");

You may also join against a subquery by giving it an alias with db::sub. For example, this query joins each user with the timestamp of their most recent post:

1let latest = db::table("posts")
2 .select(("user_id", col("created_at").max().alias("last_posted_at")))
3 .group_by(["user_id"]);
4 
5let authors = db::table("users")
6 .join(db::sub(latest, "latest"), col("latest.user_id").eq(col("users.id")))
7 .select(["users.name", "latest.last_posted_at"]);
1let latest = db::table("posts")
2 .select(("user_id", col("created_at").max().alias("last_posted_at")))
3 .group_by(["user_id"]);
4 
5let authors = db::table("users")
6 .join(db::sub(latest, "latest"), col("latest.user_id").eq(col("users.id")))
7 .select(["users.name", "latest.last_posted_at"]);

You may also pass db::sub to db::table to query directly from a derived table.

Unions

You may combine the results of two or more queries using db::union (which removes duplicate rows) or db::union_all (which keeps all rows). Any clauses you chain onto the union, such as order_by, limit, or filter, apply to the combined result set:

1use laravel::db::{self, col};
2 
3let no_first_name = db::table("users").filter(col("first_name").is_null());
4let no_last_name = db::table("users").filter(col("last_name").is_null());
5 
6let users = db::union([no_first_name, no_last_name]).order_by("id");
1use laravel::db::{self, col};
2 
3let no_first_name = db::table("users").filter(col("first_name").is_null());
4let no_last_name = db::table("users").filter(col("last_name").is_null());
5 
6let users = db::union([no_first_name, no_last_name]).order_by("id");

Each query in the union may define its own ordering and limit. For example, this query returns the three largest orders alongside the three smallest:

1let largest = db::table("orders").order_by(col("total").desc()).limit(3);
2let smallest = db::table("orders").order_by("total").limit(3);
3 
4let extremes = db::union_all([largest, smallest]);
1let largest = db::table("orders").order_by(col("total").desc()).limit(3);
2let smallest = db::table("orders").order_by("total").limit(3);
3 
4let extremes = db::union_all([largest, smallest]);

The queries must select the same number of columns. When you combine model queries, such as db::union([Post::query().filter(..), Post::query().filter(..)]), the union returns models.

Raw expressions

Sometimes you may need to insert a SQL expression that the query builder does not directly model, such as a window function or custom arithmetic. Use db::raw! to embed raw SQL while binding Rust variables safely with {name} (or spreading a list with {...name}), like db::query!. You may pass a raw expression wherever the builder expects a condition, value, selected column, ordering, or table:

1let (multiplier, minimum) = (1.5, 1000);
2let seasons = [2025, 2026];
3 
4let ranked = db::table("players")
5 .select(["name"])
6 .add_select([db::raw!("rank() over (order by score desc)").alias("position")])
7 .filter(db::raw!("score * {multiplier} > {minimum}"))
8 .filter(db::raw!("season in ({...seasons})"))
9 .order_by(db::raw!("score * {multiplier}").desc());
1let (multiplier, minimum) = (1.5, 1000);
2let seasons = [2025, 2026];
3 
4let ranked = db::table("players")
5 .select(["name"])
6 .add_select([db::raw!("rank() over (order by score desc)").alias("position")])
7 .filter(db::raw!("score * {multiplier} > {minimum}"))
8 .filter(db::raw!("season in ({...seasons})"))
9 .order_by(db::raw!("score * {multiplier}").desc());

Raw orderings sort in ascending order by default, so chain .desc() on db::raw! instead of writing DESC inside the SQL string.

You may combine db::raw! conditions with other conditions using &, |, and !. For example, this query retrieves popular posts that are not drafts:

1let views = 1000;
2 
3let popular = db::table("posts").filter(db::raw!("views > {views}") & col("draft").eq(false));
1let views = 1000;
2 
3let popular = db::table("posts").filter(db::raw!("views > {views}") & col("draft").eq(false));

When you need to construct raw SQL dynamically at runtime, wrap the string in AssertSqlSafe after verifying that it contains no untrusted user input. Laravel embeds the string verbatim without parameter bindings:

1use laravel::db::sqlx::AssertSqlSafe;
2 
3let latest = true;
4let function = if latest { "max" } else { "min" };
5 
6db::table("posts").select([
7 db::raw!(AssertSqlSafe(format!("{function}(created_at)"))).alias("at"),
8]);
1use laravel::db::sqlx::AssertSqlSafe;
2 
3let latest = true;
4let function = if latest { "max" } else { "min" };
5 
6db::table("posts").select([
7 db::raw!(AssertSqlSafe(format!("{function}(created_at)"))).alias("at"),
8]);

Inserts

The write methods below operate directly on database tables via db::table. If you are working with models, use create!, insert, and upsert instead so Laravel checks columns and manages timestamps automatically.

Use insert with the db::values! macro to insert a new row into a table. Write each column as a column: value pair, using a quoted string key when a column name is not a valid Rust identifier:

1use laravel::db::{self, values};
2 
3db::table("users")
4 .insert(values! {
5 name: "Taylor",
6 email: "[email protected]",
7 votes: 0,
8 })
9 .await?;
1use laravel::db::{self, values};
2 
3db::table("users")
4 .insert(values! {
5 name: "Taylor",
6 email: "[email protected]",
7 votes: 0,
8 })
9 .await?;

To insert multiple rows in a single statement, pass an array or Vec of values! rows that all specify the same columns. The insert method returns the number of inserted rows:

1db::table("users")
2 .insert([
3 values! { name: "Taylor", votes: 0 },
4 values! { name: "Abigail", votes: 3 },
5 ])
6 .await?;
1db::table("users")
2 .insert([
3 values! { name: "Taylor", votes: 0 },
4 values! { name: "Abigail", votes: 3 },
5 ])
6 .await?;

When the rows come from a dynamic collection such as a Vec, map each item into values! and collect into a Vec:

2 
3let rows: Vec<_> = emails
4 .iter()
5 .map(|email| values! { email: *email, subscribed: true })
6 .collect();
7 
8db::table("subscribers").insert(rows).await?;
2 
3let rows: Vec<_> = emails
4 .iter()
5 .map(|email| values! { email: *email, subscribed: true })
6 .collect();
7 
8db::table("subscribers").insert(rows).await?;

Because each value is sent as a bound parameter, very large batch inserts can hit your database's parameter limit (65,535 on PostgreSQL and MySQL, and 32,766 on SQLite). For large imports, iterate in chunks (such as emails.chunks(1_000)) and run a separate insert for each chunk.

If the table has an auto-incrementing ID, use insert_get_id to insert a row and immediately retrieve its generated key, passing the key column name as the second argument (on MySQL, this must be the table's auto-increment column):

1let id = db::table("users").insert_get_id(values! { name: "Taylor" }, "id").await?;
1let id = db::table("users").insert_get_id(values! { name: "Taylor" }, "id").await?;

To skip rows that would violate a unique constraint, use insert_or_ignore:

1db::table("users")
2 .insert_or_ignore([
3 values! { id: 1, email: "[email protected]" },
4 values! { id: 2, email: "[email protected]" },
5 ])
6 .await?;
1db::table("users")
2 .insert_or_ignore([
3 values! { id: 1, email: "[email protected]" },
4 values! { id: 2, email: "[email protected]" },
5 ])
6 .await?;

insert_or_ignore may suppress errors other than duplicate keys. For example, MySQL may substitute a default for an invalid value and insert the row. Use insert when invalid input must fail the write.

To insert rows directly from the results of another query, use insert_using. The target column names are populated in the same order as the subquery's selected columns:

1let inactive = db::table("users").select(["id", "email"]).filter(col("active").eq(false));
2 
3db::table("archived_users").insert_using(["user_id", "email"], inactive).await?;
1let inactive = db::table("users").select(["id", "email"]).filter(col("active").eq(false));
2 
3db::table("archived_users").insert_using(["user_id", "email"], inactive).await?;

Upserts

The upsert method inserts rows that do not yet exist and updates matching rows that already do. The first argument 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:

1db::table("flights")
2 .upsert(
3 [
4 values! { departure: "Oakland", destination: "San Diego", price: 99 },
5 values! { departure: "Chicago", destination: "New York", price: 150 },
6 ],
7 ["departure", "destination"],
8 ["price"],
9 )
10 .await?;
1db::table("flights")
2 .upsert(
3 [
4 values! { departure: "Oakland", destination: "San Diego", price: 99 },
5 values! { departure: "Chicago", destination: "New York", price: 150 },
6 ],
7 ["departure", "destination"],
8 ["price"],
9 )
10 .await?;

On PostgreSQL and SQLite, the identifying columns must have a unique index. MySQL and MariaDB ignore the list of identifying columns and detect conflicts using every primary or unique index on the table.

When you need to compute updated values from the existing row rather than replacing them outright, pass values! as the third argument 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:

1db::table("page_views")
2 .upsert(
3 values! { path: "/", views: 1 },
4 ["path"],
5 values! { views: col("page_views.views") + db::excluded("views") },
6 )
7 .await?;
1db::table("page_views")
2 .upsert(
3 values! { path: "/", views: 1 },
4 ["path"],
5 values! { views: col("page_views.views") + db::excluded("views") },
6 )
7 .await?;

Updates

Use update with db::values! to modify rows matching your query constraints. It returns the number of affected rows, and each value may be either a literal or a column expression:

1db::table("users")
2 .filter(col("id").eq(1))
3 .update(values! { votes: col("votes") + 1, name: "Taylor" })
4 .await?;
1db::table("users")
2 .filter(col("id").eq(1))
3 .update(values! { votes: col("votes") + 1, name: "Taylor" })
4 .await?;

For updating numeric columns such as counters or balances, the query builder provides increment and decrement:

1db::table("users").filter(col("id").eq(1)).increment("votes", 5).await?;
1db::table("users").filter(col("id").eq(1)).increment("votes", 5).await?;

To update a single field inside a JSON column without overwriting the rest of the document, use -> syntax in the column key. The parent key along the path must already exist:

1db::table("users").filter(col("id").eq(1)).update(values! { "options->theme": "dark" }).await?;
1db::table("users").filter(col("id").eq(1)).update(values! { "options->theme": "dark" }).await?;

If you want to update an existing record or insert it if no matching record exists, use update_or_insert. The first values! argument defines the attributes used to locate an existing row, and the second provides the values to update or insert:

1db::table("users")
2 .update_or_insert(
3 values! { email: "[email protected]" },
4 values! { name: "Taylor", votes: 2 },
5 )
6 .await?;
1db::table("users")
2 .update_or_insert(
3 values! { email: "[email protected]" },
4 values! { name: "Taylor", votes: 2 },
5 )
6 .await?;

Because update_or_insert 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 cannot include joins, having, unions, ordering, or limits. If you need to constrain a write using those clauses, filter by a subquery such as col("id").is_in(db::table(..)) instead. Model queries wrap the query in a subquery for you automatically, so they support joins, ordering, and limits directly.

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:

1db::table("users").filter(col("votes").lt(10)).delete().await?;
2 
3db::table("sessions").truncate().await?;
1db::table("users").filter(col("votes").lt(10)).delete().await?;
2 
3db::table("sessions").truncate().await?;

On PostgreSQL, truncate also truncates tables with foreign keys that reference the target table. On SQLite, Laravel deletes the rows and resets the counter in one transaction, so any guards registered with before_starting_transaction apply.

Connections and transactions

Queries run against your default database connection unless you select another configured connection with connection:

1let signups = db::table("events")
2 .connection("reporting")
3 .filter(col("kind").eq("signup"))
4 .count()
5 .await?;
1let signups = db::table("events")
2 .connection("reporting")
3 .filter(col("kind").eq("signup"))
4 .count()
5 .await?;

Inside a db::transaction callback, every query builder call on that connection automatically runs within the transaction so all statements commit or roll back together:

1use laravel::db::{self, col, values};
2 
3let (from, to, amount) = (1_i64, 2_i64, 25_i64);
4 
5db::transaction(async |_| {
6 db::table("accounts").filter(col("id").eq(from)).decrement("balance", amount).await?;
7 db::table("accounts").filter(col("id").eq(to)).increment("balance", amount).await?;
8 
9 db::table("transfers").insert(values! { from_id: from, to_id: to, amount: amount }).await?;
10 
11 Ok(())
12})
13.await?;
1use laravel::db::{self, col, values};
2 
3let (from, to, amount) = (1_i64, 2_i64, 25_i64);
4 
5db::transaction(async |_| {
6 db::table("accounts").filter(col("id").eq(from)).decrement("balance", amount).await?;
7 db::table("accounts").filter(col("id").eq(to)).increment("balance", amount).await?;
8 
9 db::table("transfers").insert(values! { from_id: from, to_id: to, amount: amount }).await?;
10 
11 Ok(())
12})
13.await?;

When a connection is configured with read and write replicas, read queries use a replica automatically. To force a specific query to read from the primary writer instead, chain use_write_connection() onto the query.

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 lock_for_update (which blocks other transactions from modifying or locking the selected rows until your transaction ends) or shared_lock (which allows other reads while preventing modifications):

1use laravel::db::{self, col};
2use laravel::numeric::Decimal;
3 
4let (id, amount) = (1_i64, Decimal::from(25));
5 
6db::transaction(async |_| {
7 let balance: Decimal = db::table("accounts")
8 .filter(col("id").eq(id))
9 .lock_for_update()
10 .value("balance")
11 .await?
12 .or_abort(404)?;
13 
14 if balance >= amount {
15 db::table("accounts").filter(col("id").eq(id)).decrement("balance", &amount).await?;
16 }
17 
18 Ok(())
19})
20.await?;
1use laravel::db::{self, col};
2use laravel::numeric::Decimal;
3 
4let (id, amount) = (1_i64, Decimal::from(25));
5 
6db::transaction(async |_| {
7 let balance: Decimal = db::table("accounts")
8 .filter(col("id").eq(id))
9 .lock_for_update()
10 .value("balance")
11 .await?
12 .or_abort(404)?;
13 
14 if balance >= amount {
15 db::table("accounts").filter(col("id").eq(id)).decrement("balance", &amount).await?;
16 }
17 
18 Ok(())
19})
20.await?;

Locking queries always run against the primary writer connection. SQLite does not support row-level locks, but because it permits only one writer at a time, you can safely retry contested transactions with db::transaction_with_attempts.

By default, a locking query waits until conflicting locks are released. Call skip_locked() to omit rows locked by other transactions, which is useful when multiple workers claim jobs from a shared table, or call no_wait() to fail immediately when a row is locked. On MySQL, both methods require MySQL 8.0 or later; on MariaDB, skip_locked requires MariaDB 10.6 or later:

1let next: Option<i64> = db::table("exports")
2 .filter(col("started_at").is_null())
3 .order_by("id")
4 .skip_locked()
5 .value("id")
6 .await?;
1let next: Option<i64> = db::table("exports")
2 .filter(col("started_at").is_null())
3 .order_by("id")
4 .skip_locked()
5 .value("id")
6 .await?;

Debugging

To inspect the SQL and bound parameters a query will send to the database without executing it, call to_sql:

1let sql = db::table("users").filter(col("votes").gt(100)).to_sql()?;
2 
3assert_eq!(sql.text(), r#"select * from "users" where "votes" > $1"#); // On PostgreSQL.
1let sql = db::table("users").filter(col("votes").gt(100)).to_sql()?;
2 
3assert_eq!(sql.text(), r#"select * from "users" where "votes" > $1"#); // On PostgreSQL.

Every executed query is also dispatched to your query listeners.