Sorting Data Retrieved from a MySQL Database

From Techotopia
Revision as of 19:48, 11 October 2007 by Neil (Talk | contribs)

Jump to: navigation, search

Now that we have looked at the basics of retrieving data from a MySQL database and before we look and filtering retrieved data we need to look at how to sort the output from a database retrieval.

Sorting data retrieved using SELECT

In the previous chapter we look at the SQL SELECT statement and how it is used to retrieve data from a database. Typically, a SELECT statement will extract the data from a table in the order in which it was added. Thius, however, can change if the database table has been subjected to updates and deletions. Quite simply, there is no way to predict the exact order in which data will be retrieved. For this reason SQL provides the ORDER BY keywords which enable us to sort the data as it is retrieved by the SELECT statement.

Let's begin by performing a retrieval on a sample database:

USE MySampleDB;
SELECT product_description FROM product;

When this command is executed, the data is extracted in the order of the prod_code column:

+-----------+----------------------------+-----------------------------+
| prod_code | prod_name                  | prod_desc                   |
+-----------+----------------------------+-----------------------------+
|         1 | CD-RW Model 4543           | CD Writer                   |
|         2 | EasyTech Mouse 7632        | Cordless Mouse              |
|         3 | WildTech 250Gb 1700        | SATA Disk Drive             |
|         4 | Microsoft 10-20 Keyboard   | Ergonmoc Keyboard           |
|         5 | Apple iPhone 8Gb           | Smart Phone                 |
|         6 | Moto Razr                  | Mobile Phone                |
|         7 | Dell XPS 400               | Desktop PC                  |
|         8 | Apple iPod Touch           | Portable Music/Movie Player |
|         9 | Kensington Ci20            | Optical Mouse               |
|        10 | Buffalo AirStation Turbo G | Wireless Ethernet Bridge    |
+-----------+----------------------------+-----------------------------+