ORDER BY keyword
The ORDER BY keyword is used to sort the data in the recordset.
Syntax SELECT column_name (s) FROM table_name ORDER BY column_name
Note: SQL is not case sensitive. ORDER BY and order by equivalent.
example
The following example picks all the data stored in the "Person" table and sorts the results according to the "Age" column:
<? php $ con = mysql_connect ("localhost", "peter", "abc123"); if ($ con) {die ('Could not connect:'. mysql_error ());} mysql_select_db ("my_db", $ ($ result = con); $ result = mysql_query ("SELECT * FROM person ORDER BY age"); while ($ row = mysql_fetch_array ($ result)) {echo $ row ['FirstName']; echo "". $ row ['LastName' echo "". $ row ['Age']; echo "<br />";} mysql_close ($ con);?>
Output of the above code:
Glenn Quagmire 33 Peter Griffin 35 Sort Ascending Or Descending
If you use the ORDER BY keyword, the recordset's sort order is by default ascending (1 before 9 and "a" before "p").
Use the DESC keyword to set descending order (9 before 1 and "p" before "a"):
SELECT column_name (s) FROM table_name ORDER BY column_name DESC Sort according to two columns
You can sort according to multiple columns. When sorting by multiple columns, the second column is used only if the first column is the same:
SELECT column_name (s) FROM table_name ORDER BY column_name1, column_name2