Ticker

6/recent/ticker-posts

ORDER BY Clause in SQL

ORDER BY Clause in SQL


The ORDER BY clause is used in SQL to sort the result set of a query in either ascending (ASC) or descending (DESC) order based on one or more columns. It is often used in conjunction with the SELECT statement.

Syntax:

sql
SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...

Explanation:

The ORDER BY clause is placed at the end of a SQL query and specifies the column(s) by which the result set should be sorted. Multiple columns can be specified in the ORDER BY clause, separated by commas. Each column can have its own sorting order specified with ASC (ascending) or DESC (descending) keywords.

Example 1: Consider a table called "Employees" with the following columns: "EmployeeID", "FirstName", and "LastName". To retrieve all employee records sorted by their first names in ascending order, the following SQL query can be used:

sql
SELECT EmployeeID, FirstName, LastName FROM Employees ORDER BY FirstName ASC;

Example 2: To retrieve employee records sorted by the last name in descending order, and then by the first name in ascending order, the following SQL query can be used:

sql
SELECT EmployeeID, FirstName, LastName FROM Employees ORDER BY LastName DESC, FirstName ASC;

In this example, the result set will be sorted first by the "LastName" column in descending order, and for employees with the same last name, it will further sort by the "FirstName" column in ascending order.

Example 3: The ORDER BY clause can also be used with numeric columns. For instance, to retrieve products from a table called "Products" sorted by their prices in descending order, the following SQL query can be used:

sql
SELECT ProductID, ProductName, Price FROM Products ORDER BY Price DESC;

This example retrieves the product ID, name, and price from the "Products" table and sorts the result set in descending order based on the "Price" column.

Conclusion:

The ORDER BY clause is a powerful feature in SQL that allows sorting the result set based on one or more columns in ascending or descending order. It provides flexibility in organizing data and presenting it in a desired sequence.

Post a Comment

0 Comments