Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL -> SQLite: DATE_TRUNC Equivalent

Tags:

sql

sqlite

Friday afternoon and I'm fried. So fellow SQL aficionado's how to take the following WHERE clause in PostgreSQL and convert it to SQLite3 without using a compiled extension:

WHERE
  DATE_TRUNC('day', c.start_date) <= DATE_TRUNC('day', q.date) AND
  DATE_TRUNC('day', c.end_date) >= DATE_TRUNC('day', q.date)

going over the date/time functions in SQLite3 it seems like they're only for string formatting. Hope I'm seeing something wrong.

like image 872
wheaties Avatar asked Feb 20 '15 21:02

wheaties


People also ask

What is DATE_TRUNC in PostgreSQL?

In PostgreSQL, DATE_TRUNC Function is used to truncate a timestamp type or interval type with specific and high level of precision. Syntax: date_trunc('datepart', field) The datepart argument in the above syntax is used to truncate one of the field,below listed field type: millennium. century.

What does DATE_TRUNC mean?

The DATE_TRUNC function truncates a timestamp expression or literal based on the date part that you specify, such as hour, day, or month.

What is the difference between DATE_TRUNC and Date_part?

Let's start with the difference between DATEPART and DATETRUNC. DATEPART returns an INTEGER value; DATETRUNC returns a DATE. So, since we're in September, a DATEPART calculation at the 'month' level of detail will return 9. DATETRUNC will return 2018-09-01 12:00:00 AM - the first date of the 'month' argument.

What does DATE_TRUNC return?

Returns timestamp truncated to the unit specified in field .


2 Answers

SQLite has no data type for dates; it uses strings or numbers instead.

To remove the time portion of a timestamp, use the start of day modifier. The actual function to use (datetime(), julianday(), strftime('%s')) depends on the format of your date values:

WHERE
  datetime(c.start_date, 'start of day') <= datetime(q.date, 'start of date') AND
  datetime(c.end_date,   'start of day') >= datetime(q.date, 'start of date')

In this case, you could just use the date() function because you do not care about the actual format of the result, only how it compares:

WHERE
  date(c.start_date) <= date(q.date) AND
  date(c.end_date)   >= date(q.date)
like image 149
CL. Avatar answered Oct 25 '22 23:10

CL.


I couldn't make the above method work for hours or minutes.

For these, you can hack something up using the strftime functionality like so:

select datetime(strftime('%Y-%m-%dT%H:00:00', 'now'));

like image 21
Att Righ Avatar answered Oct 25 '22 23:10

Att Righ