Thursday, March 19, 2015

PostgreSQL Calculate Age From Birthdate

There is AGE() function that performs two calculations depending of provided params:

  • It substracts date2 from date1 if two params are provided:
    --calculation: date1 - date2
    age(date1, date2)
  • It substracts date from the current date if only one param is provided:
    --calculation: current_date - date
    age(date)    
    

Calculate Age From Birthdate

All of the following SELECT's will give the same result:

SELECT EXTRACT(YEAR from AGE(birth)) as "age", * FROM customers;

or

SELECT EXTRACT(YEAR from AGE(NOW(), birth)) as "age", * FROM customers;

or

SELECT EXTRACT(YEAR from AGE(CURRENT_DATE, birth)) as "age", * 
FROM customers;

or

SELECT EXTRACT(YEAR from AGE(CURRENT_TIMESTAMP, birth)) as "age", * 
FROM customers;

or

SELECT EXTRACT(YEAR from AGE(CURRENT_TIMESTAMP, birth::timestamp)) as "age", * 
FROM customers;

or

SELECT date_part('year', AGE(birth)) as "age", * FROM customers;

result:

age | user_id | username | first_name | last_name |sex |   birth    | active
----+---------+----------+------------+-----------+----+------------+-------
 27 |       1 | Hommy    | Hommer     | Simpson   | m  | 1987-04-19 | 1
 27 |       2 | Marge    | Marge      | Simpson   | f  | 1987-04-19 | 1

Add Age CHECK Constraint based on Birthdate

Add adults age verification:

my_db=# ALTER TABLE customers
my_db-# ADD CONSTRAINT CHK_AGE CHECK (date_part('year', AGE(birth)) >=18);

Let's try to violate it:

my_db=# INSERT INTO customers (user_id, first_name, last_name, sex, birth)
my_db-# VALUES (3, 'Maggie', 'Simpson', 'f', '2010-04-19');
ERROR:  new row for relation "customers" violates check constraint "chk_age"   

see Also

31 comments:

  1. Hi,

    find Age Calculator then it is Overall looking for a Chronological age or anniversary calculator then this is your best option in age Calculator.

    Age Calculator By Date Of Birth (Days, Months)
    Calculation of age with interesting details!
    If you want to know the details of your age, then install the Age Calculator

    ReplyDelete
  2. Great article! I agree on nearly every aspect of this information you have written. t's really full of useful and interesting facts that anybody can grasp. You have great insight on this topic. Thank you for making this so clear and understandable. date calculator

    ReplyDelete
  3. अपनी आयु कैसे निकाले इस पर बहुत अच्छी जानकारी बताई है!

    यदि आपको 1 सेकंड में जानना है की जन्म तारीख से उम्र कैसे निकाले? तो इस आयु कैलकुलेटर का इस्तेमाल करें।

    ReplyDelete
  4. Types of Loans Types of Loans: There are various types of loans available, including personal loan

    ReplyDelete
  5. https://elrokn-elmethaly.com/%d8%b4%d8%b1%d9%83%d8%a9-%d8%aa%d9%86%d8%b8%d9%8a%d9%81-%d8%ae%d8%b2%d8%a7%d9%86%d8%a7%d8%aa-%d8%a8%d8%a8%d8%b1%d9%8a%d8%af%d8%a9/ Cgjg6Bvqgq

    ReplyDelete