0

I am having a variable x which contains 20000 IDs. I want to write a sql query like,

select * from tablename where ID in x;

I am trying to implement this in R where I can get the values only for IDs in x variable. The following is my try,

dbSendQuery(mydb, "select * from tablename where ID in ('$x') ")

I am not getting any error while trying this. But it is returning 0 values.

Next tried using

sprintf("select * from tablename where ID in %s",x)

But this is creating 20000 individual queries which could prove costly in DB.

Can anybody suggest me a way to write a command, which would loop through IDs in x and save to a Dataframe in R in a single query?

2 Answers 2

2

You need to have the codes in the actual string. Here is how I would do it with gsub

x <- LETTERS[1:3]

sql <- "select * from tablename where ID in X_ID_CODES "

x_codes <- paste0("('", paste(x, collapse="','"), "')")

sql <- gsub("X_ID_CODES", x_codes, sql)

# see new output
cat(sql)
select * from tablename where ID in ('A','B','C')  


# then submit the query
#dbSendQuery(mydb, sql)
Sign up to request clarification or add additional context in comments.

2 Comments

Both the codes are working fine. Since that was in a single line and easier way, I accepted that. Thanks a lot !
@haimen whatever your preference. Keep this in mind, however, if you begin to develop more complex queries that need to be dynamic. Those single line statements can get pretty unwieldy.
1

How about pasting it:

dbSendQuery(mydb, paste("select * from tablename where ID in (", paste(x, collapse = ","), ")"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.