Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Table from SQL statement using dplyr

currently I am using dplyr and dplyr.snowflakedb to manipulate some data in Snowflake.

Although this solution is proving nice to query data I am facing a challenge:

Is it possible to use string sql statements with this solution ? Namely to create tables ?

That is can I use a character "CREATE TABLE my_table AS select * from table 1" to generate a new table in the database ?

thanks in advance

like image 489
into_r Avatar asked Oct 29 '25 02:10

into_r


1 Answers

You can convert the remote tibble into an SQL query with dbplyr::sql_render() and glue it together with glue::glue_sql() like this:

# Create an ephemeral in-memory RSQLite database
conn <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
dplyr::copy_to(conn, mtcars, overwrite = TRUE)


remote_tbl <- dplyr::tbl(conn, 'mtcars')
remote_tbl
#> # Source:   table<mtcars> [?? x 11]
#> # Database: sqlite 3.30.1 [:memory:]
#>      mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
#>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1  21       6  160    110  3.9   2.62  16.5     0     1     4     4
#>  2  21       6  160    110  3.9   2.88  17.0     0     1     4     4
#>  3  22.8     4  108     93  3.85  2.32  18.6     1     1     4     1
#>  4  21.4     6  258    110  3.08  3.22  19.4     1     0     3     1
#>  5  18.7     8  360    175  3.15  3.44  17.0     0     0     3     2
#>  6  18.1     6  225    105  2.76  3.46  20.2     1     0     3     1
#>  7  14.3     8  360    245  3.21  3.57  15.8     0     0     3     4
#>  8  24.4     4  147.    62  3.69  3.19  20       1     0     4     2
#>  9  22.8     4  141.    95  3.92  3.15  22.9     1     0     4     2
#> 10  19.2     6  168.   123  3.92  3.44  18.3     1     0     4     4
#> # … with more rows

modified_tbl <- remote_tbl %>% 
  dplyr::select(cyl)



select_query <- dbplyr::sql_render(modified_tbl)
table <- 'mtcars2'

insert_statement <- glue::glue_sql(
    "create table {`table`} as {DBI::SQL(select_query)}",
    .con = conn
  )
DBI::dbExecute(conn, insert_statement)
#> [1] 0
DBI::dbListTables(conn)
#> [1] "mtcars"       "mtcars2"      "sqlite_stat1" "sqlite_stat4"

Created on 2020-11-25 by the reprex package (v0.3.0)

In general, {dplyr} was not designed to write anything back or update tables. {dm} might take this spot. Consider recent developments in the {dm} package, in particular this vignette on insertion.

like image 189
Lorenz Walthert Avatar answered Oct 31 '25 16:10

Lorenz Walthert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!