sql keyword IN using RSQLite and DBI package

61 views Asked by At

When using the RSQLite and DBI package to form a query, I wonder if there is a way to use SQL keyword IN?

I don't think SQL keyword IN is currently implemented?

e.g.

## instead of:
dbGetQuery(con, "SELECT * FROM mtcars WHERE cyl = :targetCyl" , 
params = list( targetCyl = 4 ))

## I want to do the following:

dbGetQuery(con, "SELECT * FROM mtcars WHERE cyl IN :targetCyl" , 
params = list( targetCyl = c( 2, 4, 6 ) ))
1

There are 1 answers

0
r2evans On BEST ANSWER
  1. SQL's IN operator requires its arguments to be in parentheses, as in

    select * from mtcars where cyl in (?,?,?)
    
  2. DBI requires you to instantiate the number of parens you need, as in

    targetCyl <- c( 2, 4, 6 )
    dbGetQuery(
      con, paste("SELECT * FROM mtcars WHERE cyl IN (",
                 paste(rep("?", length(targetCyl)), collapse = ","), ")"),
      params = as.list(targetCyl))
    

FYI, this is not specific to SQLite or RSQLite, it's DBI in general.