subtract two dates from a table in sql

307 views Asked by At

I have a table which has date of births of some employees. How can I find the age difference between two employees?

2

There are 2 answers

2
Mureinik On BEST ANSWER

Subtracting two date columns in Oracle will result in the difference in days, which you could divide by 365 to get the difference in years:

SELECT     FLOOR(ABS((d1 - d2) / 365)) AS age_diff
FROM       (SELECT dob AS d1
            FROM   employee
            WHERE  empId = 'some_id') t1
CROSS JOIN (SELECT dob AS d2
            FROM   employee
            WHERE  empId = 'some_other_id') t2
1
mahi_0707 On

Can you try the below to get days , months and years between two dates.

DECLARE

dob1 date := TO_DATE('11-17-2015','MM-DD-YYYY'); -- change your dates here
dob2 date := TO_DATE('11-18-2012','MM-DD-YYYY');
v_years varchar2(100);
v_months varchar2(100);
v_days varchar2(100);

BEGIN

select (abs(dob1 - dob2)) into v_days from dual;
DBMS_output.put_line('DAYS   : ' || v_days);

select floor(abs(dob1 - dob2)/365) into v_years from dual;
DBMS_output.put_line('YEARS  : ' || v_years);

select floor(abs(dob1 - dob2)/365*12) into v_months from dual;
DBMS_output.put_line('MONTHS : ' || v_months);


END;
/

OUTPUT:

DAYS : 1094
YEARS : 2
MONTHS : 35

PL/SQL procedure successfully completed.