Can I get Age using BirthDate column in a MySQL query?

MySQLMySQLi Database

To get Age using BirthDate column in a MySQL query, you can use datediff(). Let us first create a table:

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   DateOfBirth date
);
Query OK, 0 rows affected (1.46 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable(DateOfBirth) values('2010-01-21');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(DateOfBirth) values('1993-04-02');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(DateOfBirth) values('1999-12-01');
Query OK, 1 row affected (1.53 sec)
mysql> insert into DemoTable(DateOfBirth) values('1998-11-16');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(DateOfBirth) values('2004-03-19');
Query OK, 1 row affected (0.11 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output:

+----+-------------+
| Id | DateOfBirth |
+----+-------------+
|  1 | 2010-01-21  |
|  2 | 1993-04-02  |
|  3 | 1999-12-01  |
|  4 | 1998-11-16  |
|  5 | 2004-03-19  |
+----+-------------+
5 rows in set (0.00 sec)

Let us now get Age using birthdate column with DATEDIFF() method:

mysql> select cast(DATEDIFF(curdate(),DateOfBirth) / 365.25 AS UNSIGNED) AS AGE from DemoTable;

This will produce the following output:

+------+
| AGE  |
+------+
|    9 |
|   26 |
|   19 |
|   20 |
|   15 |
+------+
5 rows in set (0.00 sec)

Let us now write a query to get the DOB and ID where Age is between 20 and 26:

mysql> SELECT *FROM DemoTable WHERE YEAR(CURDATE())-YEAR(DateOfBirth)
BETWEEN 20 AND 26;

This will produce the following output:

+----+-------------+
| Id | DateOfBirth |
+----+-------------+
|  2 | 1993-04-02  |
|  3 | 1999-12-01  |
|  4 | 1998-11-16  |
+----+-------------+
3 rows in set (0.00 sec)
raja
Published on 29-Apr-2019 08:25:37
Advertisements