SQL ORDER BY Keyword

The SQL ORDER BY keyword is used to sort the result set of a SELECT statement in ascending or descending order. The result set can be sorted by one or more columns in a table.

Syntax

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, column1, column2, ... are the columns that you want to sort by, and table_name is the name of the table. You can specify the sort order of each column by using the ASC (ascending) or DESC (descending) keyword.

If no keyword is specified, the default sort order is ascending.

For example, to sort the result set of the "customers" table by the "name" column in ascending order, you would use the following query:

SELECT * FROM customers
ORDER BY name ASC;

Sorting by Multiple Columns

You can also sort the result set by multiple columns. To do this, you would specify multiple columns in the ORDER BY clause, separated by commas.

The order of the columns in the ORDER BY clause determines the sort order.

For example, to sort the result set of the "orders" table by the "customer_name" column in ascending order and then by the "order_date" column in descending order, you would use the following query:

SELECT * FROM orders
ORDER BY customer_name ASC, order_date DESC;

Sorting by Column Alias

You can also sort the result set by a column alias. A column alias is a temporary name given to a column in the SELECT statement.

To sort by a column alias, you would use the alias name in the ORDER BY clause.

For example, to sort the result set of the "employees" table by the "salary" column, but display the salary as "Annual Salary" in the result set, you would use the following query:

SELECT name, salary * 12 AS "Annual Salary"
FROM employees
ORDER BY "Annual Salary" DESC;

Sorting by Expressions

You can also sort the result set by an expression.

An expression is a combination of one or more values, operators, and/or functions that evaluate to a single value. To sort by an expression, you would include the expression in the ORDER BY clause.

For example, to sort the result set of the "products" table by the product price and then by the product name, you would use the following query:

SELECT name, price FROM products
ORDER BY price*(1-discount) DESC, name ASC;

Conclusion

The SQL ORDER BY keyword is a powerful tool that allows you to sort the result set of a SELECT statement in ascending or descending order by one or more columns. It is an essential part of any SQL query, and it can be used in a variety of ways to retrieve and manipulate data.

SQL Basics