1. sql
  2. /references
  3. /order-by

SQL ORDER BY Statement

Definition

The ORDER BY statement in SQL is used to sort the result set of a query in ascending (ASC) or descending (DESC) order. It is used in conjunction with the SELECT statement and is typically the last clause of the query.

The basic syntax for the ORDER BY clause is:

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

The ORDER BY clause sorts the result set by one or more columns. The columns specified in the ORDER BY clause must be the same as the column names in the SELECT clause or the column aliases specified in the AS clause.

The ASC keyword is used to sort the result set in ascending order, and the DESC keyword is used to sort the result set in descending order. If the ASC or DESC keyword is not specified, the default sort order is ascending (ASC).

Examples

Here is an example of how you can use the ORDER BY clause to sort the results of a query:

SELECT * 
FROM orders 
ORDER BY date DESC;

In this example, the ORDER BY clause sorts the result set of the SELECT statement by the date column in descending order.

You can also use multiple columns in the ORDER BY clause. When you sort by multiple columns, the database will first order the result set by the first column, then by the second column, and so on.

SELECT * 
FROM orders 
ORDER BY customer_id, order_date;

This will first sort the orders by customer_id and if there is any repetition of customer_id it will sort by order_date.

It is worth noting that the ORDER BY clause only affects the way the query results are displayed. The actual data stored in the table is not modified.

Best Practices

Here are some best practices for using the ORDER BY statement in SQL:

  • Always include an ORDER BY clause in your SELECT statement to ensure that the results are returned in a predictable and consistent order.

  • Use the ASC keyword to sort the results in ascending order and the DESC keyword to sort the results in descending order. The default sort order is ascending.

  • Use the table name or table alias before the column name in the ORDER BY clause to avoid ambiguity if the same column name is used in multiple tables.

  • Consider using a combination of columns in the ORDER BY clause to sort the results based on multiple criteria.

  • When using the LIMIT clause to limit the number of rows returned, make sure that the rows returned are still in the desired order by using the ORDER BY clause.