If you're not concerned about the times in the two date/time values, then simply convert to DATE values and subtract:
SELECT "Date1", "Date2",
"Date1"::DATE, "Date2"::DATE,
"Date2"::DATE - "Date1"::DATE
FROM "mytable"
You must be running with DELIMIDENT
set in the environment to enable delimited identifiers enclosed in double quotes.
The advantage of converting to DATE is that the result of the subtraction is an integer value, not an interval, and that is usually simpler to use.
Your first example is:
If Day1 = '2021-02-29 00:00:00' and Day2 = '2021-09-27 00:00:00', then TotalDaysDifference = '7881 00:00:00.00000'.
The value should be for Date1
according to your SQL. And since 2021 was not a leap year, you should not be able to insert the value 2021-02-29
. Further, there are but 365 days in a year, so it is not clear why you expect there to be 7,881 days between two dates in the same year.
However, if we change 2021-02-29 to 2000-02-29 (the year 2000 was a leap year!), then the result of the subtraction is indeed 7881.
Proof of concept
CREATE TEMP TABLE "mytable"
(
"Date1" DATETIME YEAR TO SECOND NOT NULL,
"Date2" DATETIME YEAR TO SECOND NOT NULL
);
INSERT INTO "mytable" VALUES('1900-12-31 00:00:00', '2021-09-27 00:00:00');
--INSERT INTO "mytable" VALUES('2021-02-29 00:00:00', '2021-09-27 00:00:00');
INSERT INTO "mytable" VALUES('2000-02-29 00:00:00', '2021-09-27 00:00:00');
SELECT "Date1", "Date2",
"Date1"::DATE AS "Date1 AS DATE",
"Date2"::DATE AS "Date1 AS DATE",
"Date2"::DATE - "Date1"::DATE AS "Difference in days"
FROM "mytable";
Output
I use DBDATE=Y4MD-
in the environment, so DATE values are formatted like DATETIME values.
Date1 |
Date2 |
Date1 AS DATE |
Date1 AS DATE |
Difference in days |
DATETIME YEAR TO SECOND |
DATETIME YEAR TO SECOND |
DATE |
DATE |
INTEGER |
1900-12-31 00:00:00 |
2021-09-27 00:00:00 |
1900-12-31 |
2021-09-27 |
44100 |
2000-02-29 00:00:00 |
2021-09-27 00:00:00 |
2000-02-29 |
2021-09-27 |
7881 |