How SQLx and Diesel compare for a Rust backend on Postgres: compile-time checked SQL vs a typed query DSL, async support, migrations, dynamic queries and transactions.

SQLx and Diesel are the two libraries most Rust backends pick from for Postgres, and they disagree about where queries live. SQLx checks SQL strings against a live database at compile time, while Diesel describes tables in Rust and builds queries from a typed DSL.
The difference shows when queries get dynamic and when builds run in CI, and Diesel's async story adds a separate crate on top.
The examples use SQLx 0.9, Diesel 2.4 with diesel-async 0.10, Tokio 1 and chrono for timestamps, against this table:
-- migrations/1_create_orders.up.sql
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
customer_id TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
total_cents BIGINT NOT NULL CHECK (total_cents >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
SQLx sends each query! or query_as! string to the database named by DATABASE_URL while the crate compiles, asks Postgres for the parameter and column types, and fails the build if they do not match the Rust side. The struct is plain Rust with a FromRow derive:
use chrono::{DateTime, Utc};
use sqlx::postgres::PgPool;
#[derive(Debug, sqlx::FromRow)]
struct Order {
id: i64,
customer_id: String,
status: String,
total_cents: i64,
created_at: DateTime<Utc>,
}
async fn create_order(pool: &PgPool, customer_id: &str, total_cents: i64) -> sqlx::Result<Order> {
sqlx::query_as!(
Order,
r#"INSERT INTO orders (customer_id, total_cents)
VALUES ($1, $2)
RETURNING id, customer_id, status, total_cents, created_at"#,
customer_id,
total_cents
)
.fetch_one(pool)
.await
}
async fn mark_paid(pool: &PgPool, id: i64) -> sqlx::Result<bool> {
let res = sqlx::query!(
"UPDATE orders SET status = 'paid' WHERE id = $1 AND status = 'pending'",
id
)
.execute(pool)
.await?;
Ok(res.rows_affected() == 1) // false on a second call
}
Optional filters cannot go through the macros, since the SQL has to be fixed at compile time. QueryBuilder assembles the statement at runtime and keeps values as bound parameters, at the cost of losing the compile-time check for that query:
async fn search(pool: &PgPool, customer_id: &str, status: Option<&str>) -> sqlx::Result<Vec<Order>> {
let mut qb = sqlx::QueryBuilder::new(
"SELECT id, customer_id, status, total_cents, created_at FROM orders WHERE customer_id = ",
);
qb.push_bind(customer_id);
if let Some(s) = status {
qb.push(" AND status = ").push_bind(s);
}
qb.push(" ORDER BY created_at DESC LIMIT 50");
qb.build_query_as::<Order>().fetch_all(pool).await
}
The build dependency on a database is the main friction. In CI, cargo sqlx prepare writes the query metadata to a .sqlx directory, and with SQLX_OFFLINE=true the macros read it instead of connecting, as the offline mode docs describe. Forgetting to rerun prepare after a schema change is the usual way a build breaks. Migrations with sqlx::migrate!("./migrations") read numbered .up.sql files and track them in a _sqlx_migrations table.
Best fit: async Rust services where the team thinks in SQL and wants Postgres itself to validate every static query.
Diesel describes the schema in Rust with the table! macro, normally generated by diesel print-schema, and every query is built from it. A wrong column name or a comparison between mismatched types is a compile error without a database connection. Async access comes from diesel-async, here with a deadpool pool:
use chrono::{DateTime, Utc};
use diesel::prelude::*;
use diesel_async::pooled_connection::deadpool::Pool;
use diesel_async::pooled_connection::AsyncDieselConnectionManager;
use diesel_async::{AsyncConnection, AsyncPgConnection, RunQueryDsl};
diesel::table! {
orders (id) {
id -> Int8,
customer_id -> Text,
status -> Text,
total_cents -> Int8,
created_at -> Timestamptz,
}
}
#[derive(Queryable, Selectable, Debug)]
#[diesel(table_name = orders)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct Order {
pub id: i64,
pub customer_id: String,
pub status: String,
pub total_cents: i64,
pub created_at: DateTime<Utc>,
}
#[derive(Insertable)]
#[diesel(table_name = orders)]
pub struct NewOrder<'a> {
pub customer_id: &'a str,
pub total_cents: i64,
}
Inserts, updates and filtered selects read as chains, and into_boxed() lets a filter be added only when it is present, with the type check intact:
let config = AsyncDieselConnectionManager::<AsyncPgConnection>::new(url);
let pool = Pool::builder(config).max_size(10).build()?;
let mut conn = pool.get().await?;
let order: Order = diesel::insert_into(orders::table)
.values(&NewOrder { customer_id: "cus_7", total_cents: 4200 })
.returning(Order::as_returning())
.get_result(&mut conn)
.await?;
let mut query = orders::table
.filter(orders::customer_id.eq("cus_7"))
.into_boxed();
if let Some(s) = status_filter {
query = query.filter(orders::status.eq(s));
}
let recent: Vec<Order> = query
.order(orders::created_at.desc())
.limit(50)
.select(Order::as_select())
.load(&mut conn)
.await?;
Transactions in diesel-async 0.10 take an async closure, and an error returned from it rolls back:
let order_id = order.id;
let shipped = conn
.transaction::<_, diesel::result::Error, _>(async |conn| {
diesel::update(orders::table.filter(orders::id.eq(order_id)))
.set(orders::status.eq("shipped"))
.execute(conn)
.await
})
.await?;
The cost is the learning curve and the errors: a type mismatch deep in a join produces a long trait-bound message that points at the macro expansion rather than the column, and queries Diesel's DSL does not cover, such as some window functions or CTEs, drop down to sql_query with manual QueryableByName structs. The Diesel guides cover the schema workflow, and its migration CLI uses timestamped directories with up.sql and down.sql inside.
Best fit: Rust services with many queries over a stable schema, where catching column and type mistakes without a database at build time is worth the DSL.
Both are fast enough that Postgres round trips dominate for typical APIs. SQLx reuses prepared statements per connection, and Diesel's query building is resolved at compile time for non-boxed queries. The practical differences are build time, where Diesel's macros and generics add compile time on large schemas, and the build dependency SQLx has on a database or .sqlx metadata.
Both libraries need a Postgres that exists locally, in CI and in production, with the same migrations applied. Encore works alongside the Axum or Actix Web service you already have and provisions that database from a static declaration. Encore for Rust is in private beta, and you can request an invite.

The database is declared once, and its connection_string() hands either library a URL. Under encore run that is a local Postgres with the migrations applied, and after deploy it is RDS or Cloud SQL in your own AWS or GCP account:
use diesel_async::pooled_connection::deadpool::Pool;
use diesel_async::pooled_connection::AsyncDieselConnectionManager;
use diesel_async::AsyncPgConnection;
use encore::storage::postgres::Database;
use sqlx::postgres::PgPool;
// Encore applies these migrations locally and on deploy.
static DB: Database = Database::new("orders").migrations("./migrations");
async fn sqlx_pool() -> Result<PgPool, Box<dyn std::error::Error>> {
Ok(PgPool::connect(&DB.connection_string()?).await?)
}
fn diesel_pool() -> Result<Pool<AsyncPgConnection>, Box<dyn std::error::Error>> {
let manager = AsyncDieselConnectionManager::<AsyncPgConnection>::new(DB.connection_string()?);
Ok(Pool::builder(manager).max_size(10).build()?)
}
The migrations stay in Encore's numbered .up.sql format, which is the format sqlx::migrate! already reads, so with Encore you drop the migrate! call and let Encore apply them. With Diesel, keep the same files and run diesel print-schema against the local database to refresh schema.rs. The connection string points at a proxy inside the process, so it is only valid in a process that runs the SDK, and under encore test it returns the test's own database.
An agent that adds a column writes one migration, refreshes the .sqlx metadata or schema.rs against the local Postgres, and runs the endpoint before the change leaves the laptop, with the same declaration creating the database in the cloud on deploy.
Best fit: Rust services that use SQLx or Diesel for queries and want one Postgres declaration that runs locally and in their own AWS or GCP account.
Pick SQLx when you write SQL comfortably, want async without an extra crate, and can provide a database or .sqlx metadata at build time. Pick Diesel when most queries are CRUD and filters over a schema that changes slowly, you want mistakes caught without a database, and the team will invest in its DSL. For reporting queries in a Diesel codebase, sql_query covers the gaps; for heavily dynamic filters in a SQLx codebase, QueryBuilder does.
SQLx is the better fit when you want to write SQL and have it checked against a real database at compile time, with async support built in. Diesel is the better fit when you want queries written in Rust with type errors for wrong columns and joins, and you are comfortable with its macros and trait-heavy error messages.
No. Diesel itself is synchronous, but the diesel-async crate adds async connections for Postgres, with pooling through deadpool, bb8 or mobc, and it works with Tokio-based frameworks such as Axum.
Yes. By default the query! and query_as! macros need either a DATABASE_URL to check against or offline metadata. Run cargo sqlx prepare to write that metadata to a .sqlx directory, commit it, and set SQLX_OFFLINE=true in CI so builds do not need a database.
Declare the database with Database::new("orders").migrations("./migrations") and connect a pool with PgPool::connect(&DB.connection_string()?). Encore applies the migrations, locally under encore run and on deploy, so you do not also run sqlx::migrate! against that database.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.