In this third part of a four-part series on Perl and DBI, you will learn about using SELECT queries to get information from databases. This article is excerpted from chapter 15 of the book Beginning Perl (Apress; ISBN: 159059391X).
The last bit of SQL that we will look at will be how to order the output. TheORDER BYclause 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.
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 qualifierDESC .
mysql> SELECT instrument FROM instruments -> WHERE type = "percussion" -> ORDER BY instrument DESC;
+------------+ | instrument | +------------+ | timpani | | drums | +------------+ 3 rows in set (0.00 sec)