Search This Blog

MySQL Sorting

We have seen SQL SELECT command to fetch data from MySQL table. When you select rows, the MySQL server is free to return them in any order, unless you instruct it otherwise by saying how to sort the result. But you sort a result set by adding an ORDER BY clause that names the column or columns you want to sort by.

Here is generic SQL syntax of SELECT command along with GROUP BY clause to sort data from MySQL table:

SELECT field1, field2,...fieldN table_name1, table_name2...
GROUP BY field1, [field2...] [ASC [DESC]]

You can sort returned result on any field provided that filed is being listed out.

You can sort result on more than one field.

You can use keyword ASC or DESC to get result in ascending or descending order. By default its ascending order.

You can use WHERE...LIKE clause in usual way to put condition.

Using ORDER BY clause at Command Prompt:
This will use SQL SELECT command with ORDER BY clause to fetch data from MySQL table tutorials_tbl

Try out following example which returns result in ascending order.

root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl ORDER BY tutorial_author ASC
| tutorial_id | tutorial_title | tutorial_author | submission_date |
| 2 | Learn MySQL | Abdul S | 2007-05-24 |
| 1 | Learn PHP | John Poul | 2007-05-24 |
| 3 | JAVA Tutorial | Sanjay | 2007-05-06 |
3 rows in set (0.42 sec)