How to use sqlx to query mysql IN a slice?


I want to query a table in mysql database for values IN a slice:

var qids []int
//fill qids dynamically
err = database.SQL.Select(&quotes,
    "SELECT * FROM quote WHERE qid IN $1", qids)
if err != nil {

But I get this error:

sql: converting Exec argument #0's type: unsupported type []int, a slice
quotes []

How can I fix this?


sqlx has a great helper for that: In() we just have to prepare the query by taking the args and Rebind, like this:

var qids []int

// fills qids on query dynamically
query, args, err := sqlx.In("SELECT * FROM quote WHERE qid IN (?)", qids)
if err != nil {

// sqlx.In returns queries with the `?` bindvar, we can rebind it for our backend
query = database.SQL.Rebind(query)  // database.SQL should be a *sqlx.DB

err = database.SQL.Select(&quotes, query, args...)
if err != nil {

// or just in one line:

err = database.SQL.Select(&quotes, database.SQL.Rebind(query), args...)

Also I recommend you take a look here: there’re a lot of examples including IN

Answered By – Yandry Pozo

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.