PHP MySQL Order By Keyword
- Previous Page MySQL Where
- Next Page MySQL Update
The ORDER BY keyword is used to sort data in a record set.
ORDER BY keyword
The ORDER BY keyword is used to sort data in a record set.
Syntax
SELECT column_name(s) FROM table_name ORDER BY column_name
Note:SQL is not case-sensitive. ORDER BY is equivalent to order by.
Example
The following example selects all stored data from the "Persons" table and sorts the results by the "Age" column:
<?php $con = mysql_connect("localhost","peter","abc123"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM Persons ORDER BY age"); while($row = mysql_fetch_array($result)) { echo $row['FirstName']; echo " " . $row['LastName']; echo " " . $row['Age']; echo "<br />"; } mysql_close($con); ?>
The output of the above code:
Glenn Quagmire 33 Peter Griffin 35
Ascending or Descending Sort
If you use the ORDER BY keyword, the default sorting order of the record set is ascending (1 comes before 9, "a" comes before "p"):
Please use the DESC keyword to set descending order (9 comes before 1, "p" comes before "a"):
SELECT column_name(s) FROM table_name ORDER BY column_name DESC
Sort by two columns
You can sort by multiple columns. When sorting by multiple columns, only the first column is used when they are the same:
SELECT column_name(s) FROM table_name ORDER BY column_name1, column_name2
- Previous Page MySQL Where
- Next Page MySQL Update