Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format int as date in presto SQL

Tags:

sql

presto

I have an integer date column "date_created" storing values like...

20180527, 20191205, 20200208

And am wondering what the best way to parse as a date is so I could do something like this in a query...

select * from table where formatted(date_created) > formatted(date_created) - 90

(to return everything within the last 90 days)

I've found some similar examples that convert from date ints representing seconds or milliseconds, but none where the columns are essentially date strings stored as integers.

Appreciate any thoughts on the best way to achieve this

like image 814
d3wannabe Avatar asked Dec 22 '18 09:12

d3wannabe


People also ask

Can we convert integer to date in SQL?

The method will convert the integer value into dd/MM/yyyy format by extracting dd, MM, and yyyy parts separately using arithmetic operation and add / between MM and yyyy parts. It is then converted into VARCHAR datatype. CONVERT function with style 103 is used to convert the formatted string into a proper date value.

How do I convert timestamp to date in Presto?

You can convert timestamp to date with cast(col as date) or date(col) .


3 Answers

And am wondering what the best way to parse as a date is so I could do something like this in a query...

You can convert "date as a number" (eg. 20180527 for May 27, 2018) using the following:

  1. cast to varchar
  2. parse_datetime with appropriate format
  3. cast to date (since parse_datetime returns a timestamp)

Example:

presto> SELECT CAST(parse_datetime(CAST(20180527 AS varchar), 'yyyyMMdd') AS date);
   _col0
------------
 2018-05-27

However, this is not necessarily the best way to query your data. By adapting your search conditions to the format of your data (and not vice versa), you can potentially benefit from predicate push down and partition pruning. See @GordonLinoff answer for information how to do this.

like image 123
Piotr Findeisen Avatar answered Oct 16 '22 19:10

Piotr Findeisen


You can do the comparison in the world of integers or of dates. You might as well convert the current date minus 90 days to a number:

select t.*
from t
where date_created >= cast(date_format(current_date - interval '90 day',
                                       '%Y%m%d'
                                      ) as int
                          );
like image 28
Gordon Linoff Avatar answered Oct 16 '22 18:10

Gordon Linoff


the below query is index friendly for any database since it does not use function on indexed column

select * from table where date_created > timestamp (formatted(date) - 90)
like image 33
Derviş Kayımbaşıoğlu Avatar answered Oct 16 '22 18:10

Derviş Kayımbaşıoğlu