Skip to main content
The ORDER BY clause in SQL is used to sort the result set of a query in ascending or descending order based on one or more columns. It is often used to organize data in a meaningful way, such as sorting names alphabetically or numbers numerically.

Key Points

  1. Sorting Data: The ORDER BY clause sorts the result set in ascending (ASC) or descending (DESC) order.
  2. Multiple Columns: You can sort by multiple columns, with the primary sort column listed first.
  3. Default Order: If no order is specified, the default is ascending (ASC).
  4. The ORDER BY clause is used with the SELECT statement.

Syntax

  • column1, column2, ...: The columns you want to retrieve.
  • table_name: The table from which to retrieve data.
  • ASC: Sorts the result set in ascending order (default).
  • DESC: Sorts the result set in descending order.

Examples

Suppose you have a table named Employees that stores employee details. Table: Employees To retrieve employees sorted by their names in ascending order:

Sorting in Descending Order

To sort the employees by their salary in descending order:

Sorting by Multiple Columns

You can sort by multiple columns. For example, sort employees first by their state in ascending order and then by their salary in descending order.

Using ORDER BY with WHERE Clause

You can combine the ORDER BY clause with the WHERE clause to filter and sort data. For example, retrieve employees from Tamil Nadu and sort them by salary in descending order.

Practical Use Case

Suppose you have a table named Students that stores student details, and you want to retrieve students sorted by their percentage in descending order. Table: Students

Key Takeaways

  1. The ORDER BY clause is used to sort the result set in ascending (ASC) or descending (DESC) order.
  2. You can sort by one or more columns, with the primary sort column listed first.
  3. The default sorting order is ascending (ASC).
  4. The ORDER BY clause can be combined with the WHERE clause to filter and sort data.
  5. Sorting data makes it easier to analyze and interpret query results.