SeaQuery

Learn what SeaQuery is, how its builders construct SQL from Rust method calls, and how to render and run a built statement against Postgres.

SeaQuery is a query builder for Rust. A query builder is a library that constructs SQL statements from Rust method calls instead of from string concatenation. The code says what the query should do, one method at a time, and the builder produces the SQL string and the list of values that go with it. SeaQuery is the foundation of SeaORM: every entity query in this chapter is a SeaQuery statement built by SeaORM on the reader's behalf, and the migration files use SeaQuery's schema builders to create tables. The version used on this page is SeaQuery 1.0.2, used directly as its own crate and also pulled in by SeaORM 2.0.4.

Where This Fits

The crate page showed SeaORM turning an entity call into SQL. This page opens that step up and shows the machinery itself. SeaQuery sits between the Rust code and the database driver. Handlers and entities describe a query in Rust, SeaQuery renders it as SQL for the chosen database, and SQLx carries it to Postgres. The same builder code can render for Postgres, MySQL, or SQLite, with each backend quoting names and numbering placeholders in its own way. The pages after this one each take one statement builder, SELECT, INSERT, UPDATE, and DELETE, and teach it in depth. This page teaches the shared ideas all four builders use.

Think of SeaQuery as a form with blanks. The code fills in the blanks, table, columns, conditions, and the builder prints the finished form in the dialect of the database that will read it. Filling in a form cannot produce a sentence with a missing verb, and building a query cannot produce SQL with a missing keyword, because the builder only assembles complete, well-formed pieces.

The Smallest Working Version

SeaQuery on its own needs no database connection at all. Building a statement and printing it is pure Rust, which makes it the easiest piece of the chapter to try first. Add the crate with the Postgres backend feature:

# Cargo.toml
[package]
name = "seaquery-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
sea-query = { version = "1.0.2", features = ["backend-postgres"] }

Then build a SELECT statement and print it:

// src/main.rs
use sea_query::{Expr, PostgresQueryBuilder, Query};

fn main() {
    let query = Query::select()
        .columns(["id", "name", "email"])
        .from("users")
        .and_where(Expr::col("name").like("A%"))
        .to_owned();
    let sql = query.to_string(PostgresQueryBuilder);
    println!("{}", sql);
}

The output is one line of SQL:

SELECT "id", "name", "email" FROM "users" WHERE "name" LIKE 'A%'

No database was involved. The builder assembled the statement from the method calls and rendered it for Postgres, with double quotes around identifiers and single quotes around the string value. Change PostgresQueryBuilder to MysqlQueryBuilder and the same builder prints backticks instead of double quotes. That single swap is the whole cross-database idea: the query is described once, and the backend decides the spelling.

Building Without a Database:

If the program prints the SQL line, SeaQuery works. Rendering a statement needs no connection, no tables, and no server, which is why builder code is so easy to test.

The Four Statement Builders

SeaQuery has one builder per SQL statement kind. Each starts from the Query type, which is a small factory with one method per statement.

use sea_query::{Expr, PostgresQueryBuilder, Query};

fn main() {
    let select = Query::select()
        .columns(["id", "name"])
        .from("users")
        .to_owned();
    println!("{}", select.to_string(PostgresQueryBuilder));

    let insert = Query::insert()
        .into_table("users")
        .columns(["name", "email"])
        .values_panic(["Ada".into(), "ada@example.com".into()])
        .to_owned();
    println!("{}", insert.to_string(PostgresQueryBuilder));

    let update = Query::update()
        .table("users")
        .values([("name", "Ada Lovelace".into())])
        .and_where(Expr::col("id").eq(1))
        .to_owned();
    println!("{}", update.to_string(PostgresQueryBuilder));

    let delete = Query::delete()
        .from_table("users")
        .and_where(Expr::col("id").eq(1))
        .to_owned();
    println!("{}", delete.to_string(PostgresQueryBuilder));
}

The output is four lines:

SELECT "id", "name" FROM "users"
INSERT INTO "users" ("name", "email") VALUES ('Ada', 'ada@example.com')
UPDATE "users" SET "name" = 'Ada Lovelace' WHERE "id" = 1
DELETE FROM "users" WHERE "id" = 1

Each builder only accepts the methods that make sense for its statement. A select builder has .columns(), .from(), and .and_where(). An insert builder has .into_table(), .columns(), and .values_panic(). An update builder has .table(), .values(), and .and_where(). A delete builder has .from_table() and .and_where(). Calling a method that does not belong to the builder is a compile error, which is the builder's way of stopping a malformed statement before it exists. The four builders are each taught in full on their own pages, with their complete method lists. This page stays with what they share.

Identifiers With the Iden Trait

The smallest example used plain strings for table and column names: "users", "id", "name". Strings work, but a typo in a string is invisible until the database rejects the query. SeaQuery offers a typed alternative called Iden, short for identifier. An identifier is any name in SQL: a table name, a column name, or an index name. The Iden trait marks a Rust type as something that can be used as such a name, and the derive macro implements it for an enum:

// src/users.rs
use sea_query::Iden;

#[derive(Iden)]
pub enum Users {
    Table,
    Id,
    Name,
    Email,
}

The derive macro turns each variant into a name by converting it to snake case. The Table variant is special: it takes its string from the enum name, so Users::Table becomes "users". The other variants become their own names in snake case: Users::Id becomes "id", Users::Email becomes "email". A longer variant such as CreatedAt becomes "created_at". The same enum from the migrations page works here, because the migration's DeriveIden enum and this Iden enum do the same job with different derive macros from different crates.

Using the enum, the smallest example becomes:

use sea_query::{Expr, ExprTrait, PostgresQueryBuilder, Query};
use crate::users::Users;

let sql = Query::select()
    .columns([Users::Id, Users::Name, Users::Email])
    .from(Users::Table)
    .and_where(Expr::col(Users::Name).like("A%"))
    .to_string(PostgresQueryBuilder);

The output is identical to the string version:

SELECT "id", "name", "email" FROM "users" WHERE "name" LIKE 'A%'

The difference is who catches a mistake. With strings, Expr::col("nmae") compiles and fails at runtime. With the enum, there is no Users::Nmae variant to write, so the mistake fails at compile time. That trade is the whole reason the enum exists. One warning follows from how the Table variant works: the enum must be named after the table. An enum named User produces the table name user, not users, and the query then targets a table that does not exist. That mistake was made and caught while writing the migrations page, and it applies here in exactly the same way.

The Enum Name Is the Table Name:

#[derive(Iden)] takes the table name from the enum name, not from any attribute. Name the enum after the table it describes: Users for the users table. A singular name silently points the query at a different table.

Expressions and Conditions

A condition such as WHERE "name" LIKE 'A%' is built from expressions. An expression is a piece of SQL that produces a value: a column, a literal, or a combination of the two. Expr::col makes an expression from a column. The methods on an expression come from the ExprTrait trait, which must be imported before they are available. That import is easy to forget, and the error it produces is confusing: without the trait, .eq("Ada") resolves to the standard library's equality check and returns a bool, and the compiler complains about a type mismatch instead of a missing method.

use sea_query::{Cond, Expr, ExprTrait, PostgresQueryBuilder, Query};
use crate::users::Users;

// One condition
let one = Query::select()
    .columns([Users::Id, Users::Name])
    .from(Users::Table)
    .and_where(Expr::col(Users::Name).like("A%"))
    .to_string(PostgresQueryBuilder);

// Two conditions joined with AND
let two = Query::select()
    .columns([Users::Id, Users::Name])
    .from(Users::Table)
    .and_where(Expr::col(Users::Name).like("A%"))
    .and_where(Expr::col(Users::Email).like("%@example.com"))
    .to_string(PostgresQueryBuilder);

// Either condition, joined with OR
let either = Query::select()
    .columns([Users::Id, Users::Name])
    .from(Users::Table)
    .cond_where(
        Cond::any()
            .add(Expr::col(Users::Name).like("A%"))
            .add(Expr::col(Users::Email).like("%@example.com")),
    )
    .to_string(PostgresQueryBuilder);

The three statements print:

SELECT "id", "name" FROM "users" WHERE "name" LIKE 'A%'
SELECT "id", "name" FROM "users" WHERE "name" LIKE 'A%' AND "email" LIKE '%@example.com'
SELECT "id", "name" FROM "users" WHERE "name" LIKE 'A%' OR "email" LIKE '%@example.com'

.and_where() adds a condition joined with AND. Each call adds one more, so a query with three .and_where() calls has three conditions. .cond_where() takes a Cond value instead, and Cond::any() joins its parts with OR while Cond::all() joins them with AND. Cond values nest: a Cond::all() can sit inside a Cond::any(), which is how a query expresses "this group or that group" without writing parentheses by hand. SeaQuery adds the parentheses itself, in the right places, following the normal precedence of AND over OR.

The comparison methods on an expression cover the usual SQL operators. .eq() is =, .ne() is <>, .gt() is >, .gte() is >=, .lt() is <, .lte() is <=, .like() is LIKE, .is_in() is IN, and .is_null() is IS NULL. Arithmetic works the same way: .add(), .sub(), .mul(), and .div() build +, -, *, and / expressions. These methods are the vocabulary of conditions, and the four builder pages use them without re-teaching them.

Rendering a Statement Two Ways

A statement can be rendered in two ways, and the difference matters for safety. .to_string() renders the SQL with the values written into it, as literals. .build() renders the SQL with placeholders and returns the values separately. For Postgres, the placeholders are numbered: $1, $2, $3.

use sea_query::{Expr, ExprTrait, PostgresQueryBuilder, Query};
use crate::users::Users;

let statement = Query::select()
    .columns([Users::Id, Users::Name, Users::Email])
    .from(Users::Table)
    .and_where(Expr::col(Users::Email).eq("ada@example.com"));

let with_values_inside = statement.to_string(PostgresQueryBuilder);
println!("{}", with_values_inside);

let (sql, values) = statement.build(PostgresQueryBuilder);
println!("{}", sql);
println!("values: {:?}", values);

The output is:

SELECT "id", "name", "email" FROM "users" WHERE "email" = 'ada@example.com'
SELECT "id", "name", "email" FROM "users" WHERE "email" = $1
values: Values([String(Some("ada@example.com"))])

.to_string() is for debugging, logging, and tests. It shows exactly what the statement says, with nothing hidden. .build() is for execution. The database receives the SQL with $1 and the value separately, through the binary protocol, so the value is never parsed as SQL. That separation is what stops SQL injection: a value containing a quote or a semicolon is treated as data, not as code, because it never enters the SQL string. The rule is short: render with .to_string() when a human needs to read the query, and execute with .build() when the database needs to run it. Never send a .to_string() result to the database with user input inside it.

The same pair exists for the schema builders used in migrations. Table::create() has .to_string() and .build() as well, and the migration code passes the built statement to the SchemaManager, which sends it the same way.

The Concept Behind the Builder

Underneath the method calls, a SeaQuery statement is a small tree, an abstract syntax tree. Each method call adds a node to the tree: a column node, a condition node, a table node. Rendering walks the tree and writes SQL. The tree is what makes dynamic queries easy. A query built from user input is not a string with pieces glued on. It is a tree that grows one branch at a time, and a branch is only added when the input asks for it. The function below builds a user search with optional filters, and it was run and checked while writing this page:

use sea_query::{Expr, ExprTrait, PostgresQueryBuilder, Query};
use crate::users::Users;

fn search_users(name: Option<&str>, email: Option<&str>) -> String {
    let mut query = Query::select();
    let query = query
        .columns([Users::Id, Users::Name, Users::Email])
        .from(Users::Table);
    let query = match name {
        Some(n) => query.and_where(Expr::col(Users::Name).eq(n)),
        None => query,
    };
    let query = match email {
        Some(e) => query.and_where(Expr::col(Users::Email).eq(e)),
        None => query,
    };
    query.to_string(PostgresQueryBuilder)
}

Calling it with different inputs produces different SQL, with no leftover WHERE or dangling AND:

search_users(Some("Ada"), None)
-- SELECT "id", "name", "email" FROM "users" WHERE "name" = 'Ada'

search_users(None, None)
-- SELECT "id", "name", "email" FROM "users"

search_users(Some("Ada"), Some("ada@example.com"))
-- SELECT "id", "name", "email" FROM "users" WHERE "name" = 'Ada' AND "email" = 'ada@example.com'

The string-concatenation version of this function needs careful bookkeeping: whether a WHERE has been written yet, whether the next condition needs AND in front of it. The builder version needs none of that. The method calls either happen or they do not, and the rendered SQL is correct in every combination. That is the practical payoff of the tree. Dynamic queries, the kind with optional filters from a search form, are the queries SeaQuery exists for.

Running a Built Statement

Rendering a statement prints SQL. Running it needs a connection, and SeaORM's connection knows how to run a SeaQuery statement. The ConnectionTrait trait provides two methods for this. execute takes a statement builder directly, such as a Query::insert() value, and runs it. execute_raw takes a Statement, which is the SQL string plus its values, as produced by .build() or by Statement::from_sql_and_values. For a query that returns rows, query_all and query_one do the same for reads.

use sea_orm::{ConnectionTrait, Database, DatabaseConnection, DbErr, Statement, DatabaseBackend};
use sea_query::{Expr, ExprTrait, PostgresQueryBuilder, Query};
use crate::users::Users;

async fn insert_built(db: &DatabaseConnection) -> Result<u64, DbErr> {
    let statement = Query::insert()
        .into_table(Users::Table)
        .columns([Users::Name, Users::Email])
        .values_panic(["Ada".into(), "ada@example.com".into()])
        .to_owned();
    let result = db.execute(&statement).await?;
    Ok(result.rows_affected())
}

async fn insert_from_parts(db: &DatabaseConnection) -> Result<u64, DbErr> {
    let (sql, values) = Query::insert()
        .into_table(Users::Table)
        .columns([Users::Name, Users::Email])
        .values_panic(["Ada".into(), "ada@example.com".into()])
        .build(PostgresQueryBuilder);
    let statement = Statement::from_sql_and_values(DatabaseBackend::Postgres, sql, values);
    let result = db.execute_raw(statement).await?;
    Ok(result.rows_affected())
}

The first function passes the builder straight to execute, which renders it for the connection's backend and runs it. The second renders with .build() first, wraps the parts in a Statement, and passes that to execute_raw. Both insert the same row. The first is shorter and is the one to use when the statement is already a builder. The second is the one to use when the SQL and values arrive separately, for example from a helper that builds statements. Both were compiled and run against the mock database while writing this page, and each reported one row affected with the insert statement in the transaction log.

For ordinary work, SeaORM's entity methods are the better path, because they also map the returned rows into Model values. Running a builder directly is for the queries the entity API does not cover, such as a bulk insert built from a list of values, or a statement assembled in a helper function. The rows_affected() call on the result reports how many rows the statement changed, which is how the caller knows the write did what it expected.

Raw SQL With Safe Parameters

Some queries are easier to write as SQL than as builder calls. SeaQuery 1.0 added the raw_query! macro for that case. It looks like the format! macro, but the values in braces are turned into parameters, not pasted into the string. A name in braces becomes one placeholder, and a list preceded by .. expands into one placeholder per item.

use sea_query::{PostgresQueryBuilder};

fn raw_search() -> (String, sea_query::Values) {
    let name = "Ada";
    let ids = vec![1, 2, 3];
    let query = sea_query::raw_query!(
        PostgresQueryBuilder,
        r#"SELECT "id", "name" FROM "users" WHERE "name" LIKE {name} AND "id" IN ({..ids})"#
    );
    (query.sql, query.values)
}

The result was checked while writing this page:

SELECT "id", "name" FROM "users" WHERE "name" LIKE $1 AND "id" IN ($2, $3, $4)

The macro renumbers the placeholders for the whole statement, so {name} becomes $1 and the three ids become $2, $3, and $4, even though the list was written as one item. Nested field access works too: {user.name} reads the field and binds its value. The macro is the escape hatch for the query that fights the builder. It keeps the parameter safety of .build() while letting the SQL itself be written by hand.

Testing Builders Without a Database

Builder code is pure, so its tests are plain unit tests with no async runtime and no database. Each test builds a statement and asserts the exact SQL string it renders. The tests below are the ones run while writing this page, and they all pass against SeaQuery 1.0.2:

// tests/seaquery_test.rs
use sea_query::{Cond, Expr, ExprTrait, Func, Order, PostgresQueryBuilder, Query};
use seaquery_demo::users::Users;

#[test]
fn select_renders_exact_sql() {
    assert_eq!(
        Query::select()
            .columns([Users::Id, Users::Name, Users::Email])
            .from(Users::Table)
            .and_where(Expr::col(Users::Name).like("A%"))
            .order_by(Users::Name, Order::Asc)
            .limit(10)
            .offset(0)
            .to_string(PostgresQueryBuilder),
        r#"SELECT "id", "name", "email" FROM "users" WHERE "name" LIKE 'A%' ORDER BY "name" ASC LIMIT 10 OFFSET 0"#
    );
}

#[test]
fn build_keeps_values_separate() {
    let (sql, values) = Query::select()
        .columns([Users::Id, Users::Name, Users::Email])
        .from(Users::Table)
        .and_where(Expr::col(Users::Email).eq("ada@example.com"))
        .build(PostgresQueryBuilder);
    assert_eq!(
        sql,
        r#"SELECT "id", "name", "email" FROM "users" WHERE "email" = $1"#
    );
    assert_eq!(values.0.len(), 1);
}

#[test]
fn any_condition_renders_or() {
    assert_eq!(
        Query::select()
            .columns([Users::Id, Users::Name])
            .from(Users::Table)
            .cond_where(
                Cond::any()
                    .add(Expr::col(Users::Name).like("A%"))
                    .add(Expr::col(Users::Email).like("%@example.com")),
            )
            .to_string(PostgresQueryBuilder),
        r#"SELECT "id", "name" FROM "users" WHERE "name" LIKE 'A%' OR "email" LIKE '%@example.com'"#
    );
}

#[test]
fn count_uses_func() {
    assert_eq!(
        Query::select()
            .expr(Func::count(Expr::col(Users::Id)))
            .from(Users::Table)
            .to_string(PostgresQueryBuilder),
        r#"SELECT COUNT("id") FROM "users""#
    );
}

Exact-string tests are the right tool for builders, because the SQL is the behaviour. A test that only checks "the string contains SELECT" would pass for a broken query. A test that checks the whole string fails the moment a column is added or a condition changes, which is exactly when the reader wants to know. The Func type used in the last test builds SQL functions such as COUNT, SUM, and MAX from expressions, and it appears again on the SELECT builder page.

Common Beginner Mistakes

Forgetting to import ExprTrait

// Wrong - ExprTrait is not in scope
Expr::col(Users::Name).eq("Ada")

Without the trait, .eq() is the standard equality check and returns a bool, so .and_where() receives a bool where it expects an expression. The compiler error talks about types, not about a missing import, which makes this mistake hard to recognise. The fix is one line at the top of the file: use sea_query::ExprTrait;. The same import is needed for .like(), .gt(), .is_in(), and every other expression method.

Forgetting to_owned when returning a statement

// Wrong - the builder methods return &mut, not an owned value
fn build_query() -> SelectStatement {
    Query::select().columns(["id"]).from("users")
}

The builder methods take &mut self and return &mut Self, so a chain without .to_owned() at the end is a mutable reference, not an owned statement, and it cannot be returned from the function. The fix is to end the chain with .to_owned(), which clones the statement into an owned value. The examples on this page that assign a statement to a variable all end this way.

Sending to_string output to the database

// Wrong - values are inside the SQL string
let sql = Query::select().columns(["id"]).from("users")
    .and_where(Expr::col("name").eq(user_input))
    .to_string(PostgresQueryBuilder);
db.execute_unprepared(&sql).await?;

The values are baked into the string, so a hostile input can break out of its quotes and change the query. The fix is to use .build() and execute, or execute_raw with the Statement, so the values travel separately from the SQL.

values_panic with the wrong number of values

// Wrong - two columns, one value
Query::insert()
    .into_table(Users::Table)
    .columns([Users::Name, Users::Email])
    .values_panic(["Ada".into()])

values_panic panics when the number of values does not match the number of columns. The name says what it does: it panics instead of returning a Result. The fix is to count the values against the columns before running, or to use .values() and handle its Result instead.

Building for the wrong backend

// Wrong - MySQL quoting sent to Postgres
let sql = query.to_string(MysqlQueryBuilder);

The SQL uses backticks, which Postgres does not accept as identifier quotes. The fix is to render with the backend that matches the database the statement will run against, PostgresQueryBuilder for Postgres, and to let SeaORM pick the backend automatically when executing through a connection, which it does from the connection's own backend.

Final Complete Example

Here is a small search module that puts the page together: an identifier enum, a dynamic query builder, rendering for inspection, and execution through a SeaORM connection.

// src/users.rs
use sea_query::Iden;

#[derive(Iden)]
pub enum Users {
    Table,
    Id,
    Name,
    Email,
}
// src/search.rs
use crate::users::Users;
use sea_orm::{ConnectionTrait, DatabaseConnection, DbErr, QueryResult};
use sea_query::{Expr, ExprTrait, PostgresQueryBuilder, Query};

pub fn build_search(name: Option<&str>, email: Option<&str>) -> String {
    let mut query = Query::select();
    let query = query
        .columns([Users::Id, Users::Name, Users::Email])
        .from(Users::Table);
    let query = match name {
        Some(n) => query.and_where(Expr::col(Users::Name).eq(n)),
        None => query,
    };
    let query = match email {
        Some(e) => query.and_where(Expr::col(Users::Email).eq(e)),
        None => query,
    };
    query.to_string(PostgresQueryBuilder)
}

pub async fn run_search(
    db: &DatabaseConnection,
    name: Option<&str>,
) -> Result<Vec<QueryResult>, DbErr> {
    let mut statement = Query::select();
    let statement = statement
        .columns([Users::Id, Users::Name, Users::Email])
        .from(Users::Table);
    let statement = match name {
        Some(n) => statement.and_where(Expr::col(Users::Name).like(n)),
        None => statement,
    };
    db.query_all(statement).await
}
// src/main.rs
mod search;
mod users;

use sea_orm::{Database, DbErr};

#[tokio::main]
async fn main() -> Result<(), DbErr> {
    println!("{}", search::build_search(Some("Ada"), None));
    println!("{}", search::build_search(None, None));
    let database_url = std::env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set");
    let db = Database::connect(&database_url).await?;
    let rows = search::run_search(&db, Some("A%")).await?;
    println!("rows returned: {}", rows.len());
    Ok(())
}

Running it against the scratch database with the two users in the table prints:

SELECT "id", "name", "email" FROM "users" WHERE "name" = 'Ada'
SELECT "id", "name", "email" FROM "users"
rows returned: 1

The search for A% returns one row, Ada, because the LIKE pattern matches names starting with A and Grace does not start with A. The run_search function passes the builder directly to query_all, which renders it for Postgres and returns the raw rows. Turning those rows into Model values is the entity's job, and the SELECT builder page shows how the entity's own query methods do that without any hand-built statement at all.

Summary

SeaQuery's idea is that SQL is data before it is text. The builder calls assemble a tree, the backend renders the tree, and the values travel separately from the SQL. That separation is what makes dynamic queries safe to write and easy to test: optional filters become optional method calls, placeholders are numbered by the builder instead of by hand, and the exact SQL can be asserted in a unit test that needs no database. The decision the page leaves the reader with is when to reach for the builder directly and when to let the entity do it. When the query follows the entity, the entity's methods are shorter and return typed models. When the query is dynamic, or the entity has no method for it, the builder is the tool, and the statement it produces is the same one the entity would have built.