Oracle 5.0 Reference Manual page 225

Table of Contents

Advertisement

+----------+------------+
| Puffball | 1999-03-30 |
| Chirpy
| 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim
| 1996-04-29 |
| Claws
| 1994-03-17 |
| Fluffy
| 1993-02-04 |
| Fang
| 1990-08-27 |
| Bowser
| 1989-08-31 |
| Buffy
| 1989-05-13 |
+----------+------------+
You can sort on multiple columns, and you can sort different columns in different directions. For
example, to sort by type of animal in ascending order, then by birth date within animal type in
descending order (youngest animals first), use the following query:
mysql>
SELECT name, species, birth FROM pet
->
ORDER BY species, birth DESC;
+----------+---------+------------+
| name
| species | birth
+----------+---------+------------+
| Chirpy
| bird
| Whistler | bird
| Claws
| cat
| Fluffy
| cat
| Fang
| dog
| Bowser
| dog
| Buffy
| dog
| Puffball | hamster | 1999-03-30 |
| Slim
| snake
+----------+---------+------------+
The
keyword applies only to the column name immediately preceding it (birth); it does not
DESC
affect the
species
3.3.4.5. Date Calculations
MySQL provides several functions that you can use to perform calculations on dates, for example, to
calculate ages or extract parts of dates.
To determine how many years old each of your pets is, use the
Its arguments are the unit in which you want the result expressed, and the two date for which to take
the difference. The following query shows, for each pet, the birth date, the current date, and the age in
years. An alias (age) is used to make the final output column label more meaningful.
mysql>
SELECT name, birth, CURDATE(),
->
TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age
->
FROM pet;
+----------+------------+------------+------+
| name
| birth
+----------+------------+------------+------+
| Fluffy
| 1993-02-04 | 2003-08-19 |
| Claws
| 1994-03-17 | 2003-08-19 |
| Buffy
| 1989-05-13 | 2003-08-19 |
| Fang
| 1990-08-27 | 2003-08-19 |
| Bowser
| 1989-08-31 | 2003-08-19 |
| Chirpy
| 1998-09-11 | 2003-08-19 |
| Whistler | 1997-12-09 | 2003-08-19 |
| Slim
| 1996-04-29 | 2003-08-19 |
| Puffball | 1999-03-30 | 2003-08-19 |
+----------+------------+------------+------+
The query works, but the result could be scanned more easily if the rows were presented in some
order. This can be done by adding an
mysql>
SELECT name, birth, CURDATE(),
->
TIMESTAMPDIFF(YEAR,birth,CURDATE()) AS age
->
FROM pet ORDER BY name;
+----------+------------+------------+------+
Retrieving Information from a Table
|
| 1998-09-11 |
| 1997-12-09 |
| 1994-03-17 |
| 1993-02-04 |
| 1990-08-27 |
| 1989-08-31 |
| 1989-05-13 |
| 1996-04-29 |
column sort order.
| CURDATE()
| age
ORDER BY name
TIMESTAMPDIFF()
|
10 |
9 |
14 |
12 |
13 |
4 |
5 |
7 |
4 |
clause to sort the output by name:
205
[930]
function.

Advertisement

Table of Contents
loading

This manual is also suitable for:

Mysql 5.0

Table of Contents