In response to a data query, SQL does not provide any default order of rows in the query evaluation result. To specify the order of the resulting rows, use the ORDER BY clause in a query.
Let's take a look at the example below for a hotel booking service database:
At the end of the SELECT statement, there is a specification that the resulting rows should be sorted by the price_per_night attribute.
One may sort the rows by expressions as well. For example, in the query below, hotels are ordered by price for two nights with an early check-in:
Ascending and descending order
The sorting is based on the definition of the expression type's comparison operator (<). It can specify whether greater or smaller values should be placed higher in the list. Consider an example:
Here, the ORDER BY clause is ORDER BY expr [ASC, DESC]; the ORDER BY keyword, correct expression, and an optional keyword; either ASC or DESC, specify whether the order is ascending or descending. By default, the order is assumed to be ascending.
Level up your tech skills and advance your career
• Wide range of SQL and Databases tracks
• Study at your own pace with your personal study plan
• Focus on practice and real-world experience