The SQL Order By Clause
The SQL ORDER BY clause is used to sort the record or result set of a query based on one or more columns in ascending or descending order. This is useful when you want your query results to be presented in a specific order.
SQL ORDER BY clause syntax:
SELECT column1, column2, column3 FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], column3 [ASC | DESC];
SELECT: This specifies the columns you want to retrieve.
FROM: To specifies the table from which you’re retrieving data.
ORDER BY: This clause is used for sorting the results.
column1, column2, column3, These are the columns by which you want to sort the results.
ASC: Ascending order (default if not specified).
DESC: Descending order.
Below is an example using the “Employees” table
Fetch the employee names and salaries,sorted by salary in descending order.
SQL> SELECT EmployeeName, Salary FROM Employees
ORDER BY Salary DESC;
In the above example, the query fetches the “EmployeeName” and “Salary” columns from the “Employees” table and sorts the results in descending order based on the “Salary”. That means the highest salaries will appear first in the result.
One more example of a SQL ORDER BY clause:
To fetch customer information, it is sorted by last name in ascending order and then by first name in ascending order.
SELECT FirstName, LastName, Email FROM Customers
ORDER BY LastName ASC, FirstName ASC;
The above query retrieves the first name, last name, and email of customers from the “Customers” table and sorts the results first by last name in ascending order and then by first name in ascending order.
Here, we have results in a list of customers sorted alphabetically by last name, and within each last name,
The SQL ORDER BY clause is a powerful tool in SQL that allows you to control the presentation of your query results and make them more meaningful for your application or reporting needs.