SELECT Queries and Perl - The ORDER BY Clause (
Page 2 of 4 )
The last bit of SQL that we will look at will be how to order the output. The
ORDER BY
clause allows us to specify on which field the output should be sorted. Let’s say we want to show all the musician information, but the output is to be sorted by name.
mysql> SELECT * FROM musicians ORDER BY name;
|
|
|
player_id name |
phone |
|
|
|
|
|
2 Geddy Lee |
555-2323 |
|
|
5 Lenny Kravitz |
555-5656 |
|
|
3 Marshall Mathers III 555-3434 |
|
|
6 Mike Diamond |
555-6767 |
|
|
1 Roger Waters |
555-1212 |
|
|
4 Thom Yorke |
555-4545 |
|
|
6 rows in set (0.00 sec)
How about all the instruments and their difficulty from easiest to hardest.
mysql> SELECT instrument, difficulty FROM instruments ORDER BY difficulty;
+------------+------------+
| instrument | difficulty |
+------------+------------+
| drums | 0 |
| conductor | 0 |
| keyboards | 1 |
| bass | 3 |
| timpani | 4 |
| guitar | 4 |
| trumpet | 5 |
| piccolo | 5 |
| vocals | 5 |
| bugle | 6 |
| violin | 7 |
| harp | 8 |
| bagpipes | 9 |
| oboe | 9 |
+------------+------------+
14 rows in set (0.00 sec)
Let’s list all the percussion instruments sorted on the name:
mysql> SELECT instrument FROM instruments
-> WHERE type = "percussion"
-> ORDER BY instrument;
+------------+
| instrument |
+------------+
| drums |
| timpani |
+------------+
3 rows in set (0.00 sec)
You may be wondering, “Can I reverse that order?” Yup, using the qualifier
DESC
.
mysql> SELECT instrument FROM instruments
-> WHERE type = "percussion"
-> ORDER BY instrument DESC;
+------------+
| instrument |
+------------+
| timpani |
| drums |
+------------+
3 rows in set (0.00 sec)