expression

SQLite: enforce a domain rule using CHECK

A database constraint protects data even when a caller forgets application validation. NOT NULL is included because a CHECK expression evaluating to NULL does not reject a row in SQLite. Here negative stock is rejected before it becomes stored data. Run in the accompanying Cargo project. Expected stdout (not executed): rejected: true; inserted: 1 Common mistake: Assuming a CHECK constraint alone always rejects NULL.

Formal Syntax & Structure

rust syntaxrust
qty INTEGER NOT NULL CHECK(qty >= 0)

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    let db = rusqlite::Connection::open_in_memory()?;    db.execute("CREATE TABLE item (qty INTEGER NOT NULL CHECK(qty >= 0))", [])?;    let invalid = db.execute("INSERT INTO item VALUES (?1)", [-1_i64]);    let valid = db.execute("INSERT INTO item VALUES (?1)", [0_i64])?;    println!("rejected: {}; inserted: {valid}", invalid.is_err());    Ok(())}
Rust Reference