Contact Our Development Team
Free Code Tutorials & Open Source Code
MySQL Queries - Order By
Tutorials > MySQL > Queries - Order By
Sorting results in MySQL
You've probably see sortable tables all over the internet, where you can click the column headings to change the order of the items contained within. This is normally achieved using the "ORDER BY" operator in MySQL, which forms part of the SELECT query. Say we had a SELECT query which selects everything from our example customers table:
SELECT * FROM `customers`
Name: Steve Smith - Address: 123 Fake Street - Tax ID: 123456 - Customer ID: 1
Name: Daniel Davidson - Address: 45 Made Up Road - Tax ID: 789012 - Customer ID: 2
Name: Tom Thompson - Address: 1 Not Real Close - Tax ID: 654321 - Customer ID: 3
Name: Eddie Ericson - Address: 975C Imaginary Drive - Tax ID: 135792 - Customer ID: 4
This will give you the entries in the order they were entered into the database (there are some occasions when this is not strictly true, but as a general rule it is good). Using order by, we can sort the data by any column which can be compared (alphabetically or numerically) either descending (DESC) or ascending (ASC):
SELECT * FROM `customers` ORDER BY `name` ASC
Name: Daniel Davidson - Address: 45 Made Up Road - Tax ID: 789012 - Customer ID: 2
Name: Eddie Ericson - Address: 975C Imaginary Drive - Tax ID: 135792 - Customer ID: 4
Name: Steve Smith - Address: 123 Fake Street - Tax ID: 123456 - Customer ID: 1
Name: Tom Thompson - Address: 1 Not Real Close - Tax ID: 654321 - Customer ID: 3
SELECT * FROM `customers` ORDER BY `taxid` DESC
Name: Daniel Davidson - Address: 45 Made Up Road - Tax ID: 789012 - Customer ID: 2
Name: Tom Thompson - Address: 1 Not Real Close - Tax ID: 654321 - Customer ID: 3
Name: Eddie Ericson - Address: 975C Imaginary Drive - Tax ID: 135792 - Customer ID: 4
Name: Steve Smith - Address: 123 Fake Street - Tax ID: 123456 - Customer ID: 1
Page Responses
Currently there have been no responses to this page...
If you have anything to contribute to this tutorial, found a bug, or know a better way of achieving the same goal, please leave your response below.
     
Copyright ©2009, Wired IDS Ltd. | Licensed under Creative Commons Attribution Share-Alike | Load time: 0.3108 seconds