The expression ENDDATE-STARTDATE
is not a date, time or a timestamp type, it is an INTEGER
with the number of days between the dates, so EXTRACT
won't work. Firebird does not have an INTERVAL
datatype, like some other DBMSes have.
As Luuk mentioned in the comments, you could use DATEDIFF
. However, doing so will not have the desired effect, because DATEDIFF
will take the difference between the current unit, ignoring 'lower' units, and it will take all units, so the result would by 2 years (2023-2021 = 2), 20 months (total number of months between September 2021 and May 2023 and 607 days (total number of days between 1 Sept 2021 and 1 May 2023).
There is no built-in way to get the difference you want. You would need to find a custom UDF or UDR that does this, or write your own UDF, UDR or PSQL function or procedure.
For example, something like:
create procedure custom_diff(startdate date, enddate date)
returns (years integer, months integer, days integer)
as
declare calcdate date;
begin
if (startdate > enddate) then
begin
calcdate = enddate;
enddate = startdate;
startdate = calcdate;
end
else
begin
calcdate = startdate;
end
years = datediff(year, calcdate, enddate);
calcdate = dateadd(year, years, calcdate);
if (calcdate > enddate) then
begin
years = years - 1;
calcdate = dateadd(year, -1, calcdate);
end
months = datediff(month, calcdate, enddate);
calcdate = dateadd(month, months, calcdate);
if (calcdate > enddate) then
begin
months = months - 1;
calcdate = dateadd(month, -1, calcdate);
end
days = datediff(day, calcdate, enddate);
suspend;
end
Which you can then use as:
select *
from (
select date'09/01/2021' as startdate, date'05/01/2023' as enddate
from rdb$database
) r
cross join custom_diff(r.startdate, r.enddate)
Which results in :
STARTDATE |
ENDDATE |
YEARS |
MONTHS |
DAYS |
2021-09-01 |
2023-05-01 |
1 |
8 |
0 |