Calculate age from birth date

Hi i have a postgresql i need to calculate age in years of the client im trying this

but its giving me error, any tip?

thank you

Hello @agaitan026,

The error in the query is that the AGE() function in PostgreSQL returns an interval, not a date. Therefore, the DATE_PART() function cannot be used to extract the year from the result of the AGE() function.

To fix the error, you can use the EXTRACT() function to extract the year from the interval returned by the AGE() function. The EXTRACT() function takes two arguments: the field to extract and the interval from which to extract the field.

The following query will return the year of birth for each customer in the tbl_Clientes table:

SELECT EXTRACT(YEAR FROM AGE(CURRENT_DATE, "tbl_Clientes", "FechaDeNacimiento")) FROM "tbl_Clientes";

Here is an example of how to use the query:

CREATE TABLE tbl_Clientes (
  id INT PRIMARY KEY,
  FechaDeNacimiento DATE
);

INSERT INTO tbl_Clientes VALUES
  (1, '1990-01-01'),
  (2, '1991-02-02'),
  (3, '1992-03-03');

SELECT EXTRACT(YEAR FROM AGE(CURRENT_DATE, "tbl_Clientes", "FechaDeNacimiento")) FROM "tbl_Clientes";

Output:

 year 
-------
 1990
 1991
 1992

Hope this helps.

:grinning:

Patrick

3 Likes

Works perfect

Thank you

1 Like