SQL ORDER BY CLAUSE

The ORDER BY clause is used to sort the result set in either ascending or descending order based on one or more columns. By default, SQL sorts the data in ascending order. The ORDER BY clause is useful when you want to organize your data in a specific order based on numerical values, text, or date.
The ORDER BY clause can be used with ASC (ascending order) or DESC (descending order) to control the sort direction. Additionally, it can be applied to multiple columns to sort based on more than one criterion.

The ORDER BY clause can be used in conjunction with any SELECT query, and it is often used in reports and data analysis to present the results in a meaningful order.

Some key points:

Example

In this example, we will sort the products in ascending order based on the price.

Code Example


-- Sorting products by price in ascending order
SELECT Product, Price
FROM Orders
ORDER BY Price ASC;
            

Output

Product Price
Tablet 600.00
Phone 800.00
Laptop 1200.00

Explanation

- The query selects the Product and Price columns from the Orders table.
- The ORDER BY Price ASC sorts the data in ascending order based on the Price column.

As the result is sorted by ascending order, we can clearly see that the products with the lowest prices appear first in the output.