In PostgreSQL, the AGE() function is used to get the age or date difference based on the specified dates. The stated functions retrieve the age as an interval. This works okay until unless you only want the age to be returned in years. However, if you have to get the age in years instead of the whole interval, then the AGE() function must be used with the DATE_PART() or the EXTRACT() function.
This blog will present a profound understanding of getting the age in years in Postgres.
How to Get the Age in Years in Postgres?
The DATE_PART() and EXTRACT() functions are used to get a specific date field such as a year, month, etc. Therefore, both these functions can be used with the AGE() function to extract the year from the returned value of the AGE() function. Utilize the below syntax to get the age in years:
SELECT DATE_PART('YEAR', AGE(First_DATE, Second_DATE));
Specify the date values to the AGE() function to get the age as an interval. After that, the DATE_PART() function will extract the year from the interval retrieved by the AGE() function.
Example 1: Getting Age in Years Using DATE_PART() Function
In the following snippet, we will utilize the AGE() function along with the DATE_PART() function to get the age in years:
SELECT DATE_PART('YEAR', AGE(CURRENT_DATE, '1996-01-11'));
From the output, it can be clearly noticed that the age is retrieved in years.
Example 2: Getting Age in Years Using EXTRACT() Function
Alternatively, the EXTRACT() function can be utilized with the AGE() function to get the age in years:
SELECT EXTRACT('YEAR' FROM AGE('2020-01-01', '1996-01-11'));
The output shows that the use of the EXTRACT() function along with the AGE() function retrieves the desired results.
Example 3: Getting Age in Years From the Table’s Data
Suppose we want to calculate the employees’ experience in years. To do that, we can utilize the AGE() function along with the EXTRACT() or DATE_PART() functions. We will pass the targeted date column and CURRENT_DATE() functions as arguments to the AGE() function:
SELECT emp_name, joining_date, EXTRACT('YEAR' FROM AGE(CURRENT_DATE, joining_date)) AS experience FROM emp_info;
The output shows that the stated functions successfully retrieved the experience in years.
That was all about getting the age in years.
Conclusion
In PostgreSQL, the AGE() function must be used with the DATE_PART() or the EXTRACT() function to get the age in years. The AGE() function retrieves the age as an interval while the DATE_PART() and EXTRACT() functions are used to get a specific date field such as a year, month, etc. AGE() retrieves an interval which is passed as an argument to the DATE_PART() or EXTRACT() function; the stated functions will extract the year from the interval retrieved by AGE(). This post has provided a thorough guide on getting age in years.