Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of days between two dates - ANSI SQL

I need a way to determine the number of days between two dates in SQL.

Answer must be in ANSI SQL.

like image 614
David Wright Avatar asked Nov 25 '09 22:11

David Wright


People also ask

How do I calculate the number of days between two dates in SQL query?

The DATEDIFF() function returns the difference between two dates.

What is a datediff () function?

You can use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year.

What is valid ANSI standard SQL time value?

Is a two-digit hour value between -12 to +14.

Does ANSI recognize the data type date?

date complies with the ANSI SQL standard definition for the Gregorian calendar: "NOTE 85 - Datetime data types will allow dates in the Gregorian format to be stored in the date range 0001-01-01 CE through 9999-12-31 CE."


2 Answers

ANSI SQL-92 defines DATE - DATE as returning an INTERVAL type. You are supposed to be able to extract scalars from INTERVALS using the same method as extracting them from DATEs using – appropriately enough – the EXTRACT function (4.5.3).

<extract expression> operates on a datetime or interval and returns an exact numeric value representing the value of one component of the datetime or interval.

However, this is very poorly implemented in most databases. You're probably stuck using something database-specific. DATEDIFF is pretty well implemented across different platforms.

Here's the "real" way of doing it.

SELECT EXTRACT(DAY FROM DATE '2009-01-01' - DATE '2009-05-05') FROM DUAL;

Good luck!

like image 165
Monkey Boson Avatar answered Oct 13 '22 00:10

Monkey Boson


I can't remember using a RDBMS that didn't support DATE1-DATE2 and SQL 92 seems to agree.

like image 42
Jonas Elfström Avatar answered Oct 13 '22 00:10

Jonas Elfström