×
☰ See All Chapters

MySQL ORDER BY Clause

  • ORDER BY clause is used for ordering the output of query either by ascending or descending. 

  • If ORDER BY clause is not used results are ordered in a default order. Specify DESC for descending order. 

  • A column listed in the ORDER BY clause can be abbreviated with an integer. The integer is a substitution for the actual column name (an alias for the purpose of the sort operation), identifying the position of the column after the SELECT keyword. 

SELECT ITEM_DESC, ITEM _ID, COST

FROM ITEMS

WHERE COST < 20

ORDER BY 1;

 

 

  • In this query, the integer 1 represents the column PROD_DESC. The integer 2 represents the PROD_ID column, 3 represents the COST column, and so on. 

  • We can order by multiple columns in a query, in such situations first result is sorted using column1, then in sorted table if same content is present in column1 then those rows are sorted according to column2. For example consider following Person table, in this example first sorting is done by considering column FirstName. In resulting output we have Thomas three times so these three rows are sorted considering column YearOfBirth. 

mysql-order-by-clause-0
 

All Chapters
Author