Introduction to MySQL Order By grammar

  • 2020-05-13 03:39:45
  • OfStack

Today, there are 1 problems in the process of using ORDER BY, and it is found that the previous understanding of ORDER BY is wrong.

Before w3s website ORDER BY usage, thought is the selected data by keyword ascending or descending order, the result today try select data set data, found that using ORDER BY and ORDER BY DESC query results no 1 sample, according to the understanding of themselves before they should be the same result, and the internal order no 1 sample.

Asked 1 colleague, looked up 1 document, just suddenly understood. If we used ORDER BY (DESC) when executing the select statement, it would first sort all the records by keyword and then read the required records in turn, rather than selecting the records first and then sorting them in descending order. 1 conceptual error, so write it down as a warning to yourself.

MySQL Order By keyword is used to classify data in records.

MySQL Order By Keyword is classified by keyword

ORDER BY keyword is used to categorize data in records.

MySQL Order By syntax
 
SELECT column_name(s) 
FROM table_name 
ORDER BY column_name 

Note: the SQL statement is "case insensitive" (it is not case sensitive), that is, "ORDER BY" and "order by" are the same.

MySQL Order By case

The following example: select all 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); 
?> 
[html] 
 The above code will output the following results:  

Glenn Quagmire 33 

Peter Griffin 35 

 Sort in ascending or descending order  

 If you use" ORDER BY "Keyword, all records will be sorted in the default ascending order (i.e. : from 1 to 9 , from a to z )  

 The use of" DESC "Keywords can be drawn from all the data in descending order (i.e. : from 9 to 1 , from z to a ) :  
[code] 
SELECT column_name(s) 
FROM table_name 
ORDER BY column_name DESC 

MySQL Order By is classified according to two columns

Many times, we need to sort the data by two (or more) columns at the same time. When the specified number of columns is more than 1, refer to column 2 only when the values of column 1 are identical:
 
SELECT column_name(s) 
FROM table_name 
ORDER BY column_name1, column_name2 

Related articles: