content_image/736992.jpg content_image/736995.jpg content_image/736999.jpg content_image/737002.jpg
To sort the output by age  rather than name , just use a different ORDER BY  clause: 

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

<img src='content_image/736992.jpg'>

A similar query can be used to determine age at death for animals that have died. You determine which animals these are by checking whether the death  value is NULL . Then, for those with non- NULL  values, compute the difference between the death  and birth  values: 

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

<img src='content_image/736995.jpg'>

The query uses death IS NOT NULL  rather than death <> NULL  because NULL  is a special value that cannot be compared using the usual comparison operators. This is discussed later. See Section 3.3.4.6, “Working with NULL Values” . 

What if you want to know which animals have birthdays next month? For this type of calculation, year and day are irrelevant; you simply want to extract the month part of the birth  column. MySQL provides several functions for extracting parts of dates, such as YEAR() , MONTH() , and DAYOFMONTH() . MONTH() is the appropriate function here. To see how it works, run a simple query that displays the value of both birth  and MONTH(birth) : 

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

<img src='content_image/736999.jpg'>

Finding animals with birthdays in the upcoming month is also simple. Suppose that the current month is April. Then the month value is 4  and you can look for animals born in May (month 5 ) like this: 

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

<img src='content_image/737002.jpg'>

