Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Insert R Data frame as parameter in SQL query WHERE clause

Trying to insert R data frame as parameter in SQL query where clause but I get a SQL error.

This is my code:

df <- data.frame(X=c(12691683,12693928)) %>% paste0(collapse = ",")

dbGetQuery(con2,"
  SELECT * FROM ORDERS WHERE ORDER_ID IN (", df, ")
")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With glue::glue_sql(), you could input multiple values for use in SQL IN statements by putting * at the end of the value and the values will be collapsed and quoted appropriately.

df <- data.frame(X = c(12691683, 12693928))

glue::glue_sql(
  "SELECT * FROM ORDERS WHERE ORDER_ID IN ({df$X*})",
)

# <SQL> SELECT * FROM ORDERS WHERE ORDER_ID IN (12691683, 12693928)

In base you could also use sprintf() to create the SQL query:

sprintf("SELECT * FROM ORDERS WHERE ORDER_ID IN (%s)",
        paste(df$X, collapse = ','))

# [1] "SELECT * FROM ORDERS WHERE ORDER_ID IN (12691683,12693928)"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading