How to use math operator (eg. <, >) in glue_sql?

library(glue)

con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
colnames(iris) <- gsub("[.]", "_", tolower(colnames(iris)))
DBI::dbWriteTable(con, "iris", iris)

oper <- "<"

query <- glue_sql("SELECT * FROM iris WHERE sepal_length {`oper`} sepal_width", .con = con)

DBI::dbGetQuery(con, query)
#> Error in result_create(conn@ptr, statement): near "`<`": syntax error

Created on 2019-02-12 by the reprex package (v0.2.1)

Don't use the backticks

sepal_length {oper} sepal_width

It is another syntax error.

library(glue)

con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
colnames(iris) <- gsub("[.]", "_", tolower(colnames(iris)))
DBI::dbWriteTable(con, "iris", iris)

oper <- "<"

query <- glue_sql("SELECT * FROM iris WHERE sepal_length {oper} sepal_width", .con = con)

DBI::dbGetQuery(con, query)
#> Error in result_create(conn@ptr, statement): near "'<'": syntax error

Created on 2019-02-12 by the reprex package (v0.2.1)

Sorry for that, you need to get rid of the backticks on sql not in R, this works for me

query <- glue_sql("SELECT * FROM iris WHERE sepal_length {as.name(oper)} sepal_width", .con = con)
# <SQL> SELECT * FROM iris WHERE sepal_length < sepal_width

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.