expression

SQLx: distinguish SQL NULL from missing rows

An outer Option can indicate whether a row exists; the inner Option represents a nullable column in that row. NULL is not the same as an absent result. Explicit casts make the SQL type clear in these examples. Requires an explicitly authorized disposable local PostgreSQL lab with verified TLS; see fixture README. Expected stdout (not executed): null row: true; absent: true Common mistake: Flattening the nested Option before deciding whether missing and null have different meanings.

Formal Syntax & Structure

rust syntaxrust
let v: Option<Option<String>> = query_scalar(sql).fetch_optional(&pool).await?;

Working Example

Example Snippetrust
async fn lab_pool() -> Result<sqlx::PgPool, Box<dyn std::error::Error>> {    use sqlx::postgres::{PgConnectOptions, PgPoolOptions, PgSslMode};    use std::time::Duration;    if std::env::var("BM_SQLX_LAB_OPT_IN").as_deref() != Ok("yes") {        return Err("disposable PostgreSQL lab required".into());    }    // Reject ambient PostgreSQL settings to keep the target explicit.    if std::env::vars_os().any(|(key, _)| key.to_string_lossy().to_ascii_uppercase().starts_with("PG")) {        return Err("remove ambient PG* environment settings".into());    }    let password = std::env::var("BM_SQLX_LAB_PASSWORD")?;    let ca = std::env::var("BM_SQLX_LAB_CA")?;    let options = PgConnectOptions::new_without_pgpass()        .host("127.0.0.1").port(55432)        .username("bm_learner").database("bm_sqlx_lab")        .password(&password).ssl_mode(PgSslMode::VerifyFull)        .ssl_root_cert(ca);    let pool = PgPoolOptions::new().max_connections(2)        .acquire_timeout(Duration::from_secs(3))        .connect_with(options).await?;    Ok(pool)}
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> {    let pool = lab_pool().await?;    let present_null: Option<Option<String>> = sqlx::query_scalar("SELECT NULL::text")        .fetch_optional(&pool).await?;    let absent: Option<Option<String>> = sqlx::query_scalar("SELECT NULL::text WHERE FALSE")        .fetch_optional(&pool).await?;    pool.close().await;    println!("null row: {}; absent: {}", present_null == Some(None), absent.is_none());    Ok(())}
Rust Reference