Query Builder
User::find() returns Query<User>. Every builder method takes self by value and returns a new query, so you can chain methods freely.
Filtering
#![allow(unused)]
fn main() {
let users = User::find()
.where_(User::age.gte(18))
.where_(User::name.eq("Ali Khan"))
.all(&pool).await?;
}
Combining Conditions
Condition provides and and or, both taking self and another condition by value.
AND:
#![allow(unused)]
fn main() {
let users = User::find()
.where_(
User::age.gte(18)
.and(User::name.eq("Ali Khan"))
)
.all(&pool).await?;
}
OR:
#![allow(unused)]
fn main() {
let users = User::find()
.where_(
User::name.eq("Ali Khan")
.or(User::name.eq("Fakhir Israr"))
)
.all(&pool).await?;
}
Mixing AND and OR — Mind the Grouping
and and or build a left-nested condition tree. There are no grouping helpers, so the order of chaining determines the grouping:
#![allow(unused)]
fn main() {
a.and(b).or(c) // → (a AND b) OR c
a.or(b).and(c) // → (a OR b) AND c
}
Chain conditions in the order you intend.
Each separate .where_() call is combined with AND at the top level. This provides one level of grouping:
#![allow(unused)]
fn main() {
let users = User::find()
.where_(User::age.gte(18))
.where_(
User::name.eq("Ali")
.or(User::name.eq("Fakhir"))
)
.all(&pool).await?;
}
Generated SQL:
WHERE age >= $1 AND (name = $2 OR name = $3)
Chained where_() calls are AND-ed. Each call merges into the existing condition with AND; it does not replace the previous condition.
For deeper nesting than this, use raw SQL.
Comparison Operators
Important: Comparison operators are currently implemented only for
Stringandi32fields.
| Field Type | eq | not_eq | gt | gte | lt | lte |
|---|---|---|---|---|---|---|
String | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Int (i32) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Boolean | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
Float (f64) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
DateTime | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
Decimal | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
Json | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
Nullable fields (Option<T>) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
The following examples do not compile:
#![allow(unused)]
fn main() {
User::find().where_(Post::published.eq(true))
User::find().where_(User::created_at.gt(some_date))
User::find().where_(User::bio.eq("x"))
}
These correspond to:
Field<E, bool>Field<E, DateTime>Field<E, Option<String>>
Null Checks
Null checks work with every field type:
#![allow(unused)]
fn main() {
let users = User::find()
.where_(User::bio.is_null())
.all(&pool).await?;
let users = User::find()
.where_(User::bio.is_not_null())
.all(&pool).await?;
}
Using Raw SQL
For comparisons that are not supported by the query builder, use SQLx directly:
#![allow(unused)]
fn main() {
let rows: Vec<UserModel> = sqlx::query_as(
"SELECT * FROM users WHERE published = $1 AND created_at > $2"
)
.bind(true)
.bind(cutoff)
.fetch_all(&pool)
.await?;
}
Raw SQL serves as an escape hatch when the query builder cannot express a particular query.
Ordering and Pagination
#![allow(unused)]
fn main() {
let page = User::find()
.order_by(User::id.desc())
.take(20) // LIMIT
.skip(40) // OFFSET
.all(&pool).await?;
}
The methods are take() and skip(), not limit() and offset().
Single-Column Ordering
order_by() stores only one ordering value. Calling it again replaces the previous value:
#![allow(unused)]
fn main() {
let users = User::find()
.order_by(User::name.asc())
.order_by(User::id.desc()) // Replaces name ordering
.all(&pool).await?;
}
Multi-column ordering is not currently supported.
For queries such as:
ORDER BY name ASC, id DESC
use raw SQL.
DISTINCT, GROUP BY and Aggregates
#![allow(unused)]
fn main() {
let names = User::find()
.distinct()
.all(&pool).await?;
}
You can also select specific columns and aggregate values:
#![allow(unused)]
fn main() {
let counts: Vec<(String, i64)> = User::find()
.select(User::name.select())
.select(User::id.count())
.group_by(User::name.column())
.fetch_all(&pool).await?;
}
Selection Behaviour
- The first
select()call clears the default column list and adds the selected expression. - Subsequent
select()calls append additional selections. group_by()accumulates columns. Call it once for each grouping column.- Aggregate projections require
fetch_all::<M>()with a matching tuple or struct because the result no longer matchesUserModel.
Available Aggregates
The following aggregate methods are available on any field:
| Method | Description |
|---|---|
count() | Counts values |
sum() | Calculates the sum |
avg() | Calculates the average |
min() | Returns the minimum |
max() | Returns the maximum |
HAVING Limitations
having() accepts a Condition<E>, which is built from field comparisons.
However, aggregate methods such as count() return a SelectItem, not a condition.
Therefore, this does not compile:
#![allow(unused)]
fn main() {
.having(User::id.count().gt(2))
}
HAVING COUNT(*) > 2 cannot currently be expressed through the query builder.
Use raw SQL for grouped filters.
Subqueries
The query builder supports subqueries through in_subquery().
#![allow(unused)]
fn main() {
let active = User::find()
.select(User::id.select())
.where_(User::name.eq("Ali Khan"));
let posts = Post::find()
.where_(Post::user_id.in_subquery(active))
.all(&pool).await?;
}
in_subquery() compiles the inner query and embeds its SQL and bind values into the outer query.
Placeholder numbering is adjusted correctly, keeping $1, $2, and subsequent parameters consistent across both queries.
Joins
The query builder supports inner, left, right, full and cross joins.
#![allow(unused)]
fn main() {
let rows = User::find()
.inner_join(Post::user_id.eq_column(User::id))
.all(&pool).await?;
}
Available Join Methods
| Method | Argument |
|---|---|
inner_join() | T: JoinTarget |
left_join() | T: JoinTarget |
right_join() | T: JoinTarget |
full_join() | T: JoinTarget |
cross_join() | &'static str — raw table name |
Understanding eq_column()
The field on which you call eq_column() determines the joined table.
When querying User and joining posts, call it on the Post field:
#![allow(unused)]
fn main() {
User::find()
.inner_join(Post::user_id.eq_column(User::id))
}
Generated SQL:
INNER JOIN posts ON posts.user_id = users.id
Both fields must have the same Rust type:
#![allow(unused)]
fn main() {
Field<E, T>
Field<E2, T>
}
Join Limitations
Joins change the shape of the returned rows.
When using joins:
- Explicitly define the selected columns with
select(). - Use
fetch_all::<M>()with a matching result type. - Do not rely on
all()to constructUserModelfrom a joined result.
Important: GROUP BY and ORDER BY currently emit unqualified column names.
If joined tables contain columns with the same name, such as id, PostgreSQL may return an ambiguity error.
Use raw SQL for such queries.
Query Execution
| Method | Accepts | Returns |
|---|---|---|
all(db) | impl Acquire — pool or transaction | Result<Vec<E::Model>, sqlx::Error> |
count(db) | &PgPool only | Result<i64, sqlx::Error> |
fetch_all::<M>(db) | &PgPool only | Result<Vec<M>, sqlx::Error> |
Fetching All Records
#![allow(unused)]
fn main() {
let users = User::find()
.where_(User::age.gte(18))
.all(&pool).await?;
}
Counting Records
#![allow(unused)]
fn main() {
let total = User::find()
.where_(User::age.gte(18))
.count(&pool).await?;
}
Custom Result Types
For custom projections and aggregate queries:
#![allow(unused)]
fn main() {
let results: Vec<(String, i64)> = User::find()
.select(User::name.select())
.select(User::id.count())
.group_by(User::name.column())
.fetch_all(&pool).await?;
}
COUNT Limitations
count() currently includes only joins and WHERE conditions.
It ignores:
GROUP BYHAVINGLIMITOFFSET
This means:
- Counting a grouped query returns the ungrouped matching row count, not the number of groups.
- Calling
count()aftertake(10)returns the full matching count, not just 10.
The second behaviour is useful for pagination when you need the total number of matching records rather than the number of records on the current page.
Do not rely on count() for grouped queries.
Method Reference
| Category | Methods | Behaviour |
|---|---|---|
| Filtering | where_() | Combines conditions with AND |
| Relations | with(), with_nested() | Loads relations |
| Ordering | order_by() | Single ordering column |
| Pagination | take(), skip() | LIMIT and OFFSET |
| Shape | distinct(), select() | Controls selected results |
| Grouping | group_by() | Accumulates grouping columns |
| Group filtering | having() | Accepts Condition<E> |
| Joins | inner_join(), left_join(), right_join(), full_join(), cross_join() | Joins tables |
| Execution | all(), count(), fetch_all() | Executes queries |
Not Available in 0.1
The following methods are not currently available:
first()one()limit()offset()like()
For queries requiring unsupported functionality, use SQLx raw SQL.