expression

Diesel: query nullable fields

SQL NULL requires a null predicate rather than normal equality. The corresponding nullable text field may decode into Option<String>. This example selects rows with no note and separately reads the known nullable field. Uses a disposable in-memory SQLite database. Expected stdout (not executed): id 1; note absent: true Common mistake: Confusing a missing row with an existing row whose nullable column is NULL.

Formal Syntax & Structure

rust syntaxrust
items::note.is_null()

Working Example

Example Snippetrust
use diesel::prelude::*;use diesel::sqlite::SqliteConnection;
diesel::table! {    items (id) {        id -> Integer,        label -> Text,        note -> Nullable<Text>,    }}
fn sample_db() -> Result<SqliteConnection, Box<dyn std::error::Error>> {    let mut conn = SqliteConnection::establish(":memory:")?;    diesel::sql_query("CREATE TABLE items (id INTEGER PRIMARY KEY, label TEXT NOT NULL, note TEXT)")        .execute(&mut conn)?;    diesel::insert_into(items::table)        .values((items::id.eq(1), items::label.eq("Pen")))        .execute(&mut conn)?;    diesel::insert_into(items::table)        .values((items::id.eq(2), items::label.eq("Book"), items::note.eq(Some("blue"))))        .execute(&mut conn)?;    Ok(conn)}
fn main() -> Result<(), Box<dyn std::error::Error>> {    let mut conn = sample_db()?;    let id: i32 = items::table.filter(items::note.is_null()).select(items::id).first(&mut conn)?;    let note: Option<String> = items::table.find(id).select(items::note).first(&mut conn)?;    println!("id {id}; note absent: {}", note.is_none());    Ok(())}
Rust Reference