Using ANY to bind a WHERE IN Diesel sql_query

January 24, 20201 minute

Say you have a query that you want to run in diesel that selects records using WHERE IN:

SELECT id, name from user
WHERE IN (1, 2, 3)

Also, lets assume the query is more complex and needs to use sql_query instead of diesel's dsl.

How do you bind the ids? By using ANY:

SELECT id, name from user

Then you can use sql_query from diesel:

stuct User {
  id: i32,
  name: String

let my_ids = vec![1, 2, 3];

let results = diesel::sql_query(include_str!("./myquery.sql"))
  .bind::<Array<Integer>, _>(my_ids)
Tweet this post
© 2020 Dan Bruder