The Crystal Programming Language Forum

How to implement PostgreSQL's WHERE IN clause?

Problem:
I have an array of id values; say, idvals = ["id1", "id2", "id3"]. I want to execute the following query:

select id, var1 from mytable
where 
id in ('id1', 'id2', 'id3');

How can I implement it in Crystal using db and pg libraries?

Thank you.

After posting, I searched for how this could be done in Golang. Found one possible solution. If you think there is a better way, please respond. Otherwise, this may be helpful to others.

idvals = ["id1", "id2", "id3"]
idvalsStr = "{" + idvals.join(", ") + "}"
conn.query_all("select id, var1 from mytable 
                          where id = Any($1)",
                          idvalsStr, 
                          as: {id: String, var1: String}
                       )

See the “Exec” section in https://crystal-lang.org/reference/database/ for how to use parameter substitution. I haven’t checked if Arrays can be passed via that mechanism, but that’s where I’d start.