dust

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.

dust-framework 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:

rust
use dust::db::{self, col};use dust::prelude::*;use serde::Serialize;#[derive(db::FromRow, Serialize)]struct User {    id: i64,    name: String,    email: String,}pub async fn index() -> dust::Result<Json<Vec<User>>> {    let users: Vec<User> = db::table("users")        .filter(col("active").eq(true) & col("votes").gt(100))        .order_by(col("created_at").desc())        .limit(10)        .get()        .await?;    Ok(Json(users))}

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:

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

Choosing between the builder and models

The builder and models share the same connections, transactions, read-replica routing, and query listeners. The difference is what they know about your table:

You need Use
A row as a model with hooks, events, timestamps, and relationships Models
Typed columns and compile-time column names Models
A projection, aggregate, tuple, or derived table db::table
Rows from a table with no model, such as a job or cache table db::table
A bulk write that skips per-row events Either; the builder is explicit about it
One value from one row Either value or a model query's value

A model query always selects every column, because hydrating a model needs all of them. When you only need two columns from a million rows, db::table(..).select([..]) sends less data and decodes less work:

rust
use dust::db::{self, col};// The model query: typed columns, every column, a Vec<Post>.let posts = Post::query()    .filter(Post::published_at.is_not_null())    .latest(Post::published_at)    .limit(10)    .get()    .await?;// The builder query: an explicit projection into a smaller struct.#[derive(db::FromRow)]struct PostSummary {    id: i64,    title: String,}let summaries: Vec<PostSummary> = db::table("posts")    .filter(col("published_at").is_not_null())    .select(["id", "title"])    .latest("published_at")    .limit(10)    .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

sole is the method for "exactly one row": it returns the row when one matches, aborts with 404 when none does, and fails with a 500 when several match. Use first when several matches are acceptable.

Decoding is strict about the columns you map: a FromRow struct ignores columns it does not declare, but a missing field, a NULL in a non-Option field, or a value of the wrong type returns an error naming the column. A tuple decodes the selected columns in order, so the number and types of both must agree.

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

rust
let user: Option<User> = db::table("users").find(42).await?;let email: Option<String> = db::table("users")    .filter(col("name").eq("Taylor"))    .value("email")    .await?;let titles: Vec<String> = db::table("posts")    .filter(col("featured").eq(true))    .pluck("title")    .await?;

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

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

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:

rust
use std::collections::HashMap;let titles: HashMap<String, String> = db::table("roles")    .select(["name", "title"])    .get::<(String, String)>()    .await?    .into_iter()    .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:

rust
use dust::numeric::Decimal;let users: u64 = db::table("users").count().await?;let highest: Option<i64> = db::table("users").max("votes").await?;let revenue: Option<Decimal> = db::table("orders")    .filter(col("status").eq("paid"))    .sum("total")    .await?;let 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:

rust
use dust::db::{self, col, values};use dust::stream::TryStreamExt;let mut pages = db::table("users")    .filter(col("active").eq(false))    .chunk_by_id::<User>(100, "id");while let Some(users) = pages.try_next().await? {    let ids: Vec<i64> = users.iter().map(|user| user.id).collect();    db::table("users")        .filter(col("id").is_in(&ids))        .update(values! { archived: true })        .await?;}

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:

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

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:

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

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

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

[!WARNING] Although dust-framework 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:

rust
db::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:

rust
db::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:

rust
db::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:

rust
db::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:

rust
let team_id: Option<i64> = Some(2);db::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:

rust
db::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:

rust
use dust::time::Timestamp;let since: Timestamp = "2026-10-01T00:00:00Z".parse()?;let posts = db::table("posts")    .filter(col("published").eq(true))    .filter(        col("status").eq("featured")            | (col("votes").ge(50) & col("created_at").gt(since)),    );
sql
select * from "posts"where "published" = $1  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:

rust
use dust::db::{self, Condition, col};use dust::prelude::*;#[dust::input]#[validate(anyone)]pub struct UserSearch {    role: Option<String>,    name: Option<String>,    email: Option<String>,}pub async fn index(search: Valid<UserSearch>) -> dust::Result<Json<Vec<User>>> {    let terms: Vec<Condition> = [        search.name.as_deref().map(|name| col("name").contains(name)),        search.email.as_deref().map(|email| col("email").contains(email)),    ]    .into_iter()    .flatten()    .collect();    let users = db::table("users")        .filter(search.role.as_deref().map(|role| col("role").eq(role)))        .when(!terms.is_empty(), |query| query.filter(db::any(terms)))        .get()        .await?;    Ok(Json(users))}

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:

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

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

rust
db::table("users").filter(col("votes").between(1, 100));db::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:

rust
let user_id = 42;let following = db::table("follows")    .select(["followed_id"])    .filter(col("follower_id").eq(user_id));let feed = db::table("posts").filter(col("user_id").is_in(following));let largest = db::table("orders").select([col("total").max()]);let 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":

rust
let plan = db::table("plans")    .select(["name"])    .filter(col("plans.id").eq(col("users.plan_id")));let 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:

rust
let posts = db::table("posts")    .select([col("*").count()])    .filter(col("posts.user_id").eq(col("users.id")));let 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:

rust
let 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:

rust
let last_login = db::table("logins")    .select([col("created_at").max()])    .filter(col("logins.user_id").eq(col("users.id")));let 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:

rust
let customers = db::table("users")    .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:

rust
db::table("users").filter(col("options->language").eq("en"));db::table("users").filter(col("options->languages[0]").eq("en"));db::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 !:

rust
db::table("users").filter(col("options->languages").json_contains("en"));db::table("users").filter(col("options->languages").json_contains(["en", "de"]));db::table("users").filter(!col("options->theme").json_has_key());db::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:

rust
use dust::time::civil::Date;let halloween: Date = "2026-10-31".parse()?;db::table("orders").filter(col("created_at").date().eq(halloween));db::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 dust::now(). is_today, is_before_today, and is_after_today compare its date with today's date:

rust
db::table("invoices").filter(col("due_at").is_past() & col("paid_at").is_null());db::table("orders").filter(col("created_at").is_today());db::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 dust-framework'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:

rust
use dust::time::{Dates, ToSpan};let start = dust::now().in_tz("America/Chicago")?.start_of_day()?;let end = start.plus(1.day());db::table("orders").filter(col("created_at").ge(&start) & col("created_at").lt(&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. 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:

rust
let search = db::search(["title", "body"], "query builder");let 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:

rust
let search = db::search(["title", "body"], "\"query builder\" -legacy")    .language("english")    .websearch();let articles = db::table("articles")    .select(("title", search.relevance().alias("score")))    .filter(search.clone())    .order_by(search)    .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.

[!WARNING] MySQL's 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 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:

rust
use dust::db::{self, values};// The embedding your AI provider returns for the document's text...let embedding: Vec<f32> = vec![0.12, -0.53, 0.88];db::table("documents")    .insert(values! { title: "Napa Valley wineries", embedding: db::vector(&embedding) })    .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:

rust
#[derive(db::FromRow)]pub struct Document {    id: i64,    title: String,}let documents: Vec<Document> = db::table("documents")    .similar_to("embedding", &embedding, 0.4)    .limit(10)    .get()    .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:

rust
db::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:

rust
db::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:

rust
db::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:

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

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

rust
let 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:

rust
let query = db::table("users").order_by("name");let unordered_users: Vec<User> = query.clone().unordered().get().await?;let 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:

rust
let busy_days = db::table("orders")    .select((col("created_at").date().alias("day"), col("*").count().alias("orders")))    .group_by([col("created_at").date()])    .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:

rust
db::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:

rust
let only_verified = true;let per_page: Option<u64> = Some(25);let users = db::table("users")    .when(only_verified, |query| query.filter(!col("email_verified_at").is_null()))    .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:

rust
use dust::db::{self, col};fn published(query: db::Builder) -> db::Builder {    query.filter(col("published").eq(true) & !col("published_at").is_null())}let posts = published(db::table("posts")).latest("published_at").limit(10);let 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:

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

Once a table is aliased, reach its columns through the alias. An unqualified column that exists in more than one joined table makes the database reject the query as ambiguous, and select(["*"]) across a join can return duplicate column names, so list the columns you need.

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

rust
let 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:

rust
let latest = db::table("posts")    .select(("user_id", col("created_at").max().alias("last_posted_at")))    .group_by(["user_id"]);let authors = db::table("users")    .join(db::sub(latest, "latest"), col("latest.user_id").eq(col("users.id")))    .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:

rust
use dust::db::{self, col};let no_first_name = db::table("users").filter(col("first_name").is_null());let no_last_name = db::table("users").filter(col("last_name").is_null());let 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:

rust
let largest = db::table("orders").order_by(col("total").desc()).limit(3);let smallest = db::table("orders").order_by("total").limit(3);let 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:

rust
let (multiplier, minimum) = (1.5, 1000);let seasons = [2025, 2026];let ranked = db::table("players")    .select(["name"])    .add_select([db::raw!("rank() over (order by score desc)").alias("position")])    .filter(db::raw!("score * {multiplier} > {minimum}"))    .filter(db::raw!("season in ({...seasons})"))    .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:

rust
let views = 1000;let 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. dust-framework embeds the string verbatim without parameter bindings:

rust
use dust::db::sqlx::AssertSqlSafe;let latest = true;let function = if latest { "max" } else { "min" };db::table("posts").select([    db::raw!(AssertSqlSafe(format!("{function}(created_at)"))).alias("at"),]);

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 dust-framework 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:

rust
use dust::db::{self, values};db::table("users")    .insert(values! {        name: "Taylor",        email: "taylor@example.com",        votes: 0,    })    .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:

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

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

rust
let emails = vec!["taylor@example.com", "abigail@example.com", "jess@example.com"];let rows: Vec<_> = emails    .iter()    .map(|email| values! { email: *email, subscribed: true })    .collect();db::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):

rust
let 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:

rust
db::table("users")    .insert_or_ignore([        values! { id: 1, email: "taylor@example.com" },        values! { id: 2, email: "abigail@example.com" },    ])    .await?;

[!WARNING] 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:

rust
let inactive = db::table("users").select(["id", "email"]).filter(col("active").eq(false));db::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:

rust
db::table("flights")    .upsert(        [            values! { departure: "Oakland", destination: "San Diego", price: 99 },            values! { departure: "Chicago", destination: "New York", price: 150 },        ],        ["departure", "destination"],        ["price"],    )    .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:

rust
db::table("page_views")    .upsert(        values! { path: "/", views: 1 },        ["path"],        values! { views: col("page_views.views") + db::excluded("views") },    )    .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:

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

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

rust
db::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:

rust
db::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:

rust
db::table("users")    .update_or_insert(        values! { email: "taylor@example.com" },        values! { name: "Taylor", votes: 2 },    )    .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:

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

On PostgreSQL, truncate also truncates tables with foreign keys that reference the target table. On SQLite, dust-framework 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:

rust
let signups = db::table("events")    .connection("reporting")    .filter(col("kind").eq("signup"))    .count()    .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:

rust
use dust::db::{self, col, values};let (from, to, amount) = (1_i64, 2_i64, 25_i64);db::transaction(async |_| {    db::table("accounts").filter(col("id").eq(from)).decrement("balance", amount).await?;    db::table("accounts").filter(col("id").eq(to)).increment("balance", amount).await?;    db::table("transfers").insert(values! { from_id: from, to_id: to, amount: amount }).await?;    Ok(())}).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):

rust
use dust::db::{self, col};use dust::numeric::Decimal;let (id, amount) = (1_i64, Decimal::from(25));db::transaction(async |_| {    let balance: Decimal = db::table("accounts")        .filter(col("id").eq(id))        .lock_for_update()        .value("balance")        .await?        .or_abort(404)?;    if balance >= amount {        db::table("accounts").filter(col("id").eq(id)).decrement("balance", &amount).await?;    }    Ok(())}).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:

rust
let next: Option<i64> = db::table("exports")    .filter(col("started_at").is_null())    .order_by("id")    .skip_locked()    .value("id")    .await?;

Performance notes

The builder sends exactly the SQL you describe. It does not add indexes, cache results, or rewrite a slow condition, so the shape of the query matters:

  • Filter and order on indexed columns. A condition on an unindexed column scans the table. Use table.index in a migration, then check the plan with EXPLAIN through db::query! when a query is unexpectedly slow.
  • Ask for existence, not a count. exists() stops at the first row, while count() counts every match.
  • Select less. pluck and value decode one column without hydrating models. db::table(..).select([..]) avoids sending columns you never read.
  • Bound every list. A list from a request can hold thousands of IDs; combine limit with the list, or filter by a subquery instead.
  • Avoid a leading wildcard on large text. contains cannot use a normal index. Use db::search or a prefix condition on an indexed column.
  • Watch correlated subqueries. A subquery that references the outer row, such as the posts_count example, runs once per row. For large result sets, a join with group_by is often cheaper; measure both.
  • Page with a key, not an offset, in background work. chunk_by_id resumes after the last key, while a deep OFFSET still scans and discards the skipped rows. See Pagination.
  • Batch writes. One insert of 500 rows is far cheaper than 500 inserts. Stay under the parameter limit (65,535 on PostgreSQL and MySQL, 32,766 on SQLite).
  • Avoid N+1 queries. Loading a relationship inside a loop runs one query per row. Eager-load it with with or count it with with_count.

order_by(db::random()) sorts the whole result set, so use it on small tables or with a limit that the database can apply after sorting.

Common errors

Most query-builder surprises come from SQL semantics rather than from dust-framework. These are the ones worth recognising:

What you see Why Fix
is_in([]) matches nothing An empty IN () is false by definition Skip the filter when the list is empty
ne(value) leaves out NULL rows NULL <> value is unknown, not true Use is_distinct_from or add is_null()
An aggregate returns None sum, min, and max return None when no row matches Use unwrap_or_default() for a zero
A joined column is ambiguous Two joined tables have a column with the same name Qualify it, such as col("u.id")
An update or delete refuses joins, ordering, or limit Table-level writes compile to a single statement Filter by a subquery, or use a model query
A MySQL upsert updates the wrong rows MySQL ignores the conflict-column list Make the unique indexes match your intent
insert_or_ignore hides a bad value MySQL may substitute a default instead of failing Use insert when invalid input must fail
A JSON number compares as text PostgreSQL and MySQL return extracted JSON scalars as text, while SQLite returns numbers Compare in SQL, or compare against the string on PostgreSQL and MySQL

Every one of these explains itself through the generated SQL, which to_sql() prints without running the query.

Debugging

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

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

Every executed query is also dispatched to your query listeners.