TIMESTAMPDIFF() function


SELECT name, birth, CURDATE(),
TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age
FROM pet;

ORDER BY name

SELECT name, birth, CURDATE(), TIMESTAMPDIFF(YEAR,birth,CURDATE())
AS age FROM pet ORDER BY name;

Sort the output by age rather than name, just use a different ORDER BY clause:

SELECT name, birth, CURDATE(),
TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age
FROM pet ORDER BY age;

 

Query can be used to determine age at death for animals that have died

SELECT name, birth, death,
TIMESTAMPDIFF(YEAR,birth,death) AS age
FROM pet WHERE death IS NOT NULL ORDER BY age;

Query that displays the value of both birth and MONTH(birth):

SELECT name, birth, MONTH(birth) FROM pet;

 

Finding animals with birthdays in the upcoming month 5 (May)

SELECT name, birth FROM pet WHERE MONTH(birth) = 5;

There is a small complication if the current month is December. You cannot merely add one to the month number (12) and look for animals born in month 13, because there is no such month. Instead, you look for animals born in January (month 1).

You can write the query so that it works no matter what the current month is, so that you do not have to use the number for a particular month. DATE_ADD() enables you to add a time interval to a given date. If you add a month to the value of CURDATE(), then extract the month part with MONTH(), the result produces the month in which to look for birthdays:

A different way to accomplish the same task is to add 1 to get the next month after the current one after using the modulo function (MOD) to wrap the month value to 0 if it is currently 12:
MONTH() returns a number between 1 and 12. And MOD(something,12) returns a number between 0 and 11.
So the addition has to be after the MOD(), otherwise we would go from November (11) to January (1).

SELECT name, birth FROM pet WHERE MONTH(birth) = MONTH(DATE_ADD(CURDATE(),INTERVAL 1 MONTH));