Everything PHP: MySQL ORDER BY

Published on Sep 5, 2009   //  Development

Everything PHP

When you perform a select query in MySQL, by default the result will be ordered by the primary key, in ascending order. This may not be ideal for some situations, as you may want to output or process the data in a certain order. You could achieve this in PHP, but MySQL offers a better way to have your query returns sorted.

Using an ORDER BY clause at the end of your query will allow you to specify the fields to order the results by, and how you would like those sorted (ascending [default] or descending). MySQL will then order the result appropriately based on your clause and sort based on your clause and the type of field in question. For example, a field containing numbers will sort 1-x (where x is basically infinite, higher than 1 at the least) if ascending and x-1 is descending. Let’s have a look at an example of this:

[sql]SELECT * FROM [table] ORDER BY [field][/sql]

This query will then return the results order by [field] in ascending order. To specify ascending specially, append ASC to the query, for descending, using DESC.

It is also possible to “sub-order” the queries. By specifying more than one field (comma separated), the results will first by order by the first query, then those results “sub-ordered” by the second query and so on. For example, if you’re storing country and city fields, you can order by country, then have those rows with the same country ordered by the city. You may even specify independent sorting values.

[sql]SELECT * FROM registrants ORDER BY country ASC, city ASC, age DESC[/sql]

There you have it, multiple ways to order and sort your data without using PHP to do so.

1 Comment to “Everything PHP: MySQL ORDER BY”

  • Thanks for this post. Short but still informative, especially for someone like me who’s trying to learn MySQL.