Syntax error Calculate age from date of birth in MySQL?

Calculate age from date of birth in MySQL?



To calculate age from date of birth, you can use the below syntax −

select timestampdiff(YEAR,yourColumnName,now()) AS anyAliasName from yourTableName;

Let us first create a table −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentDOB datetime
);
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentDOB) values('1996-01-12');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentDOB) values('1990-12-31');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentDOB) values('1989-04-01');
Query OK, 1 row affected (0.45 sec)
mysql> insert into DemoTable(StudentDOB) values('2000-06-17');
Query OK, 1 row affected (0.16 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+---------------------+
| StudentId | StudentDOB          |
+-----------+---------------------+
| 1         | 1996-01-12 00:00:00 |
| 2         | 1990-12-31 00:00:00 |
| 3         | 1989-04-01 00:00:00 |
| 4         | 2000-06-17 00:00:00 |
+-----------+---------------------+
4 rows in set (0.00 sec)

Here is the query to calculate age from date of birth −

mysql> select timestampdiff(YEAR,StudentDOB,now()) AS AGE from DemoTable;

This will produce the following output −

+------+
| AGE  |
+------+
| 23   |
| 28   |
| 30   |
| 18   |
+------+
4 rows in set (0.03 sec)
Updated on: 2019-07-30T22:30:25+05:30

894 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements