ORDER BY
In SQL, the ORDER BY
clause is used to sort the result set of a query based on one or more columns. It allows you to control the order in which the rows are returned by the SELECT statement. By default, SQL does not guarantee any specific order for query results, so using the ORDER BY
clause is essential when you want to retrieve the data in a particular sequence.
The basic syntax of the ORDER BY
clause is as follows:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
Here's an explanation of the ORDER BY
clause and its components:
SELECT
statement: TheSELECT
statement specifies the columns you want to retrieve from the table.FROM
clause: TheFROM
clause indicates the table from which you want to retrieve data.ORDER BY
clause: TheORDER BY
clause is used to specify the columns by which you want to sort the result set. You can specify one or more columns, and each column can be sorted in ascending (ASC) or descending (DESC) order. By default, the sorting order is ascending.
Example:
Suppose we have a table named "Products" with columns ProductID
, ProductName
, and Price
. We want to retrieve all products sorted by their price in descending order.
SELECT ProductID, ProductName, Price
FROM Products
ORDER BY Price DESC;
In this example, the ORDER BY
clause is used to sort the result set by the Price
column in descending order, which will display products with higher prices first.
You can also sort by multiple columns. If two rows have the same value for the first column, the ORDER BY
clause will consider the second column for sorting and so on.
Example:
SELECT FirstName, LastName, Age
FROM Employees
ORDER BY Age DESC, LastName ASC;
In this example, the result set will be sorted primarily by the Age
column in descending order, and if two employees have the same age, they will be sorted by the LastName
column in ascending order.
The ORDER BY
clause is versatile and allows you to control the order in which data is returned, making it a powerful tool for organizing query results to meet specific requirements.