Hi,
I was trying to create an SQL query which would grab the end of a string. In this example it was supposed to be the last five characters. However, the show_query function shows it returns null rather than calculated integers.
Is that a correct behaviour?
library(RSQLite)
library(DBI)
library(dplyr)
library(dbplyr)
# Create example SQL database and load with example table
conn <- DBI::dbConnect(RSQLite::SQLite(), "")
DBI::dbWriteTable(conn,
"iris",
iris %>% distinct(Species),
overwrite = TRUE)
# Expected behaviour
DBI::dbGetQuery(conn,
"SELECT `Species`
,LENGTH(`Species`) AS `Length`
,SUBSTR(`Species`, LENGTH(`Species`)-4, LENGTH(`Species`)) AS `Trimmed`
FROM `iris`")
#> Species Length Trimmed
#> 1 setosa 6 etosa
#> 2 versicolor 10 color
#> 3 virginica 9 inica
# Actual code example; start and stop substituted with NULL
tbl(conn, DBI::Id(Table = "iris")) %>%
mutate(Length = length(Species),
Trimmed = substr(Species, start = length(Species)-4, stop = length(Species))) %T>%
show_query() %>%
collect()
#> Warning in substr(Species, start = length(Species) - 4, stop = length(Species)):
#> NAs introduced by coercion
#> Warning in pmax(as.integer(stop) - start + 1L, 0L): NAs introduced by coercion
#> <SQL>
#> SELECT `Species`, length(`Species`) AS `Length`, SUBSTR(`Species`, NULL, NULL) AS `Trimmed`
#> FROM `iris`
#> Warning in substr(Species, start = length(Species) - 4, stop = length(Species)):
#> NAs introduced by coercion
#> Warning in substr(Species, start = length(Species) - 4, stop = length(Species)):
#> NAs introduced by coercion
#> # A tibble: 3 x 3
#> Species Length Trimmed
#> <chr> <int> <lgl>
#> 1 setosa 6 NA
#> 2 versicolor 10 NA
#> 3 virginica 9 NA
Created on 2021-01-21 by the reprex package (v0.3.0)
I've tried using nchar and len instead of R length but with the same effect (My actual database uses len rather than length).
Thanks
Edit: Provided a better example showing that using native SQL code gets desired result
Hi,
I was trying to create an SQL query which would grab the end of a string. In this example it was supposed to be the last five characters. However, the
show_queryfunction shows it returnsnullrather than calculated integers.Is that a correct behaviour?
Created on 2021-01-21 by the reprex package (v0.3.0)
I've tried using
ncharandleninstead of Rlengthbut with the same effect (My actual database useslenrather thanlength).Thanks
Edit: Provided a better example showing that using native SQL code gets desired result