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.
A D V E R T I S E M E N T
Syntax:
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
Example:
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)
mysql>
Verify all the author names are listed out in ascending order.
Using ORDER BY clause inside PHP Script:
You can use similar syntax of ORDER BY clause into PHP function
mysql_query(). This function is used to execute SQL command and later
another PHP function mysql_fetch_array() can be used to fetch all the
selected data.
Example:
Try out following example which returns result in descending order of
tutorial author.
Share And Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
Keywords:
MySQL Sorting Results, Mysql Tutorial, Mysql tutorial pdf, history of mysql, basic mysql, syntax use in mysql, mysql software download, learn mysql, mysql insert, mysql delete, mysql data types, mysql administrator.