Skip to content
Advertisement

SQL query to get data without hours in timestamp column

I have written a code and sql query to get data from database:

sql_tables <- glue("
SELECT *
FROM mytable
LIMIT 4
")
table <- dbGetQuery(con, stri_encode(sql_tables, to = "UTF-8")) %>%
     as.data.frame()

I get this dataframe:

ID      value                    timestamp
1       message sent      2019-05-29 06:45:34
2       sold out          2019-05-29 07:55:29
3       processed         2019-05-30 17:42:11
4       processed         2019-05-30 19:44:15

I want to write another query to get data only for 2019-05-29:

sql_tables <- glue("
SELECT *
FROM mytable
WHERE timestamp = '2019-05-29'
LIMIT 4
")
table <- dbGetQuery(con, stri_encode(sql_tables, to = "UTF-8")) %>%
     as.data.frame()

but it brings me an error:

Error in select(conn@ptr, statement) :
  DB::Exception: Key expression contains comparison between inconvertible types: DateTime and String inside timestamp = '2019-05-29'

How could i do that? How could i get rid of hours in timestamp column in my sql query? Desired result is:

ID      value                    timestamp
1       message sent      2019-05-29
2       sold out          2019-05-29 

Advertisement

Answer

  1. toDate(timestamp)

    SELECT * FROM mytable WHERE toDate(timestamp) = ‘2019-05-29’ LIMIT 4

  2. SELECT * FROM mytable WHERE timestamp => toDateTime(‘2019-05-29’) and timestamp < (toDateTime(‘2019-05-29’) + interval 1 day) LIMIT 4

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement