datalitico.com

Sorting Data Using the ORDER BY Clause

In SQL, the ORDER BY clause is used to sort the result set of a SELECT statement based on one or more columns. It allows you to arrange the retrieved data in either ascending or descending order.

Basic Syntax

The basic syntax of a SELECT statement with the ORDER BY clause is:

SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
  • column1, column2, …: Specifies the columns to retrieve from the table.
  • table_name: Specifies the table from which to retrieve the data.
  • ORDER BY: Indicates that the result set should be sorted.
  • column1, column2, …: Specifies the columns by which the result set should be sorted.
  • ASC (optional): Specifies ascending order (default if not specified).
  • DESC: Specifies descending order.

Sorting by Single Column

To sort the result set by a single column, simply specify the column name after the ORDER BY keyword

SELECT *
FROM employees
ORDER BY last_name;

This query will retrieve all columns from the “employees” table and sort the result set in ascending order based on the “last_name” column.

Sorting by Multiple Columns

If you want to sort the result set by multiple columns, specify the columns in the desired order after the ORDER BY keyword.

SELECT *
FROM employees
ORDER BY department_id, last_name;

This query will sort the result set first by the “department_id” column in ascending order, and then by the “last_name” column in ascending order within each department.

Sorting in Descending Order

To sort the result set in descending order, add the DESC keyword after the column name.

SELECT *
FROM employees
ORDER BY salary DESC;

The query above will sort the result set in descending order based on the “salary” column.

Sorting by Expression or Function

In SQL, you can also sort the result set based on expressions or function results.

SELECT *
FROM orders
ORDER BY total * quantity DESC;

This query will sort the result set based on the product of the “total” and “quantity” columns in descending order.

With ORDER BY clause, you can sort the result set of a SELECT statement based on one or more columns. Sorting the data allows you to arrange it in a meaningful way, making it easier to analyze and interpret the information. Whether you need a simple ascending sort or a more complex sort involving multiple columns or expressions, the ORDER BY clause provides the necessary flexibility to meet your requirements.

Scroll to Top