The MySQL order BY keyword is used to classify the data in the record.
MySQL ORDER BY keyword classified by keyword
The ORDER BY keyword is used to classify the data in a record.
MySQL ORDER BY syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name
NOTE: The SQL statement is a "letter case insensitive" statement (it does not distinguish between uppercase and lowercase letters), that is, "order by" is the same as the "by".
MySQL ORDER BY case
The following example: Select all the records from the person table and categorize 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 person ORDER BY age");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName']
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con);
?>
The above code will output the following result:
Glenn Quagmire 33
Peter Griffin 35
Sort by ascending or descending order
If you use the "ORDER BY" keyword, all records will be sorted by default ascending (i.e.: from 1 to 9, from A to Z)
Use the "DESC" keyword to make all the data in descending order (that is, from 9 to 1, from Z to a):
SELECT column_name(s)
FROM table_name
ORDER BY column_name DESC
MySQL order BY is sorted by two columns
Many times, we need to classify data based on two columns of content (or more). When the specified number of columns is more than one column, the second column is referenced only when the value of the first column is exactly the same:
SELECT column_name(s)
FROM table_name
ORDER BY column_name1, column_name2
Reference documents:
MySQL ORDER by index optimization: http://www.phpq.net/mysql/mysql-order-by.html
MySQL ORDER BY Syntax: http://www.phpq.net/mysql/mysql-order-by-syntax.html
MySQL ORDER BY Rand () Efficiency: http://www.phpq.net/mysql/mysql-order-by-rand.html
MySQL ORDER BY Usage: http://www.phpq.net/mysql/mysql-order-by-use.html