Suppose we have a large amount of data in a database. When we perform a select query on the data, we get a whole bunch of data. Now suppose we wanted to sort that data, that is, we wanted to arrange the data in alphabetical order before showing it to a user in their browser. Would we sort the data using PHP? Of course not.
MySQL has its own built-in sorting engine and we can invoke it using order by in our SQL.
If we had the table "employees" which looked like this:
| first_name | last_name |
|---|---|
| Paul | Pitterson |
| Francine | Beecham |
| Raul | DiNozzo |
| Anthony | DiNozzo |
And we wanted to output the entire table sorting in ascending order by last name we would use the following code:
SELECT * FROM employees ORDER BY last_name ASC;
The result would be:
| first_name | last_name |
|---|---|
| Francine | Beecham |
| Raul | DiNozzo |
| Anthony | DiNozzo |
| Paul | Pitterson |
If we wanted to sort in descending order we would use:
SELECT * FROM employees ORDER BY last_name DESC;
If we wanted to sort by another field, for example first_name, we would simply specify it in our SQL:
SELECT * FROM employees ORDER BY first_name ASC;
If we do not specify "ASC" or "DESC", MySQL will default to "ASC" or ascending. It is usually a good idea to explicitly set what order we want to sort our data.
We hope this MySQL tutorial has been helpful.