SQLx Query As and FromRow Mapping Rows to Structs Explained
Map rows to your own structs with query_as and the FromRow derive, or with the query_as! macro. Learn column renames, Option for nulls and the differences between the forms.

Rows come back as bags of columns, and you want a User. SQLx offers two ways to get there: a derive that maps by name at run time, and a macro that checks the mapping at compile time. Knowing which to use and how nulls behave covers nearly every real query. It is the mapping chapter of SQLx explained.
sqlx 0.8, PostgreSQL 17, Rust 1.90.
The derive form
use sqlx::{FromRow, PgPool};
#[derive(Debug, FromRow)]
struct User {
id: i64,
email: String,
#[sqlx(rename = "full_name")]
name: Option<String>,
}
async fn find(pool: &PgPool, id: i64) -> Result<Option<User>, sqlx::Error> {
sqlx::query_as::<_, User>("SELECT id, email, full_name FROM users WHERE id = $1")
.bind(id)
.fetch_optional(pool)
.await
}fetch_optional returns Ok(None) when no row matches, which maps to a 404; fetch_one returns Err(RowNotFound) and fetch_all returns a Vec. The Option<String> field matches a nullable column. If full_name were NOT NULL, a plain String would do.
What goes wrong at run time
Because the SQL is a string, a typo in a column name only appears when the query runs:
Error: no column found for name: emialand a null in a field that is not an Option gives error occurred while decoding column "email": unexpected null; try decoding as an Option. Cover the query with a test, or use the macro.
The macro form
let user = sqlx::query_as!(
User,
r#"SELECT id, email, full_name AS "name" FROM users WHERE id = $1"#,
id
)
.fetch_one(pool)
.await?;The macro connects at build time (or reads the offline cache), checks that the result has id, email and name, and compares types and nullability. A column that PostgreSQL says may be null while your field is String fails to compile. Aliases with AS "name" map the column to the field, and the quotes keep the casing.
Overriding inferred types
Computed columns are often reported as nullable. Force it with a type suffix: COUNT(*) AS "count!" means non-null, ... AS "x?" means nullable, and AS "ts: DateTime<Utc>" picks a Rust type.
Choosing
| Need | Use |
|---|---|
| Quick, dynamic or generated SQL | query_as with FromRow |
| Fixed SQL, safety on rename | query_as! |
| One-off scalar | query_scalar |
| Dynamic filters | QueryBuilder with FromRow |
Reuse
Prefer one struct per entity and one per projection (UserSummary), rather than a struct with many Option fields for every query. Typed IDs keep different entities apart, as in newtypes for database IDs.
Limits
FromRow maps flat rows, not graphs. For many-to-one or one-to-many relations, write a join and group in code, or use an ORM, compared in SQLx versus Diesel and SeaORM. The API is in the docs for FromRow.


