expression

SQLx QueryBuilder: bind a variable-length IN list

Generate one placeholder for each selected ID. An empty list needs its own meaning; this example explicitly returns no matches instead of generating invalid SQL IN (). Bound list length must be capped before query construction. No database connection is required by this example. Expected stdout (not executed): SELECT id FROM items WHERE id IN ($1, $2) SELECT id FROM items WHERE FALSE Common mistake: Building an empty IN clause or using unbounded request lists. The assert is a lab invariant, not request validation.

Formal Syntax & Structure

rust syntaxrust
builder.separated(", ").push_bind(value)

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> {    use sqlx::{Postgres, QueryBuilder};    fn statement(ids: &[i32]) -> String {        assert!(ids.len() <= 100);        let mut q = QueryBuilder::<Postgres>::new("SELECT id FROM items WHERE ");        if ids.is_empty() { q.push("FALSE"); }        else {            q.push("id IN (");            let mut list = q.separated(", ");            for &id in ids { list.push_bind(id); }            list.push_unseparated(")");        }        q.sql().to_owned()    }    println!("{}", statement(&[7, 9]));    println!("{}", statement(&[]));    Ok(())}
Rust Reference