SQL ORDER BY – The Complete Guide (2024)

The SQL ORDER BY clause and functionality is an important part of a SELECT statement. Learn what it does and how to use it in this article.

Table of Contents

What Is The SQL ORDER BY Clause?

The SQL ORDER BY clause allows you to order your results. You can specify what you want to order by, and can even order by multiple columns.

By default, the SQL results are not ordered in any specific order. Without the ORDER BY clause in your SQL query, the results may look like they are in a certain order. However, the Oracle database cannot guarantee that the results will always be in the same order.

So, if you need results to be ordered, then add the ORDER BY clause.

Syntax and Parameters of SQL ORDER BY

The syntax of the SQL ORDER BY clause is:

ORDER BY {column_name | column_position | expression}[ ASC | DESC ][ NULLS FIRST | NULLS LAST ]

In this clause:

  • column_name is one of the columns in your SELECT clause or in your table that you want to order by.
  • column_position is a number that refers to the position of a column in your SELECT statement.
  • expression is a valid SQL expression that you want to order your results by
  • ASC or DESC can be used to specify the order of the data. ASC is ascending, and DESC is descending. This is optional, and if it is not provided, the default sort order is ASC.
  • NULLS FIRST or NULLS LAST can be used to specify how NULL values are sorted. This only applies to Oracle SQL. NULLS FIRST means that NULL values are shown at the top of the list, and NULLS LAST means that NULL values are shown at the bottom of the list. The default treatment if this is not specified is NULLS FIRST if the sort is DESC, or NULLS LAST if the sort is ASC or not specified.

Also, the column that you order by does not need to exist in the SELECT clause. So you don’t need to see the column in your results to use it in the ORDER BY.

Examples

I think the easiest way to learn is to see examples. So, I’ll show you a few ways you can use the SQL ORDER BY clause in Oracle.

I’ll be using this table to perform the SELECT queries on.

SALESPERSON_IDFIRST_NAMESALARYCOMMISSIONHIRE_DATE
1John9000010001-Jan-16
2Sally950005005-Sep-16
3Mark10100080012-Aug-16
4Tina8700090024-Oct-16
5Steve1000005002-Feb-16
6Michelle1200006003-Dec-16
7Alex85000(null)17-Jan-16
8Jo115000120030-Oct-16

Example 1 – ORDER BY Column Name

This example orders by a single column name.

SELECTsalesperson_id,first_name,salary,commission,hire_dateFROM salespersonORDER BY first_name;

Result:

SALESPERSON_IDFIRST_NAMESALARYCOMMISSIONHIRE_DATE
7Alex85000(null)17-Jan-16
8Jo115000120030-Oct-16
1John9000010001-Jan-16
3Mark10100080012-Aug-16
6Michelle1200006003-Dec-16
2Sally950005005-Sep-16
5Steve1000005002-Feb-16
4Tina8700090024-Oct-16

All of the records are ordered by the first_name column. ASC or DESC was not specified, so by default, they are ordered in ASC order.

Example 2 – ORDER BY Column Name using ASC

This example orders by a column name and uses the ASC keyword.

SELECTsalesperson_id,first_name,salary,commission,hire_dateFROM salespersonORDER BY salary ASC;

Result:

SALESPERSON_IDFIRST_NAMESALARYCOMMISSIONHIRE_DATE
7Alex85000(null)17-Jan-16
4Tina8700090024-Oct-16
1John9000010001-Jan-16
2Sally950005005-Sep-16
5Steve1000005002-Feb-16
3Mark10100080012-Aug-16
8Jo115000120030-Oct-16
6Michelle1200006003-Dec-16

This sorts the data in the table by salary in ascending order, which for numbers, is from smallest to highest.

Example 3 – ORDER BY Column Name using DESC

This example orders by a column name and uses the DESC keyword.

SELECTsalesperson_id,first_name,salary,commission,hire_dateFROM salespersonORDER BY salary DESC;

Result:

SALESPERSON_IDFIRST_NAMESALARYCOMMISSIONHIRE_DATE
6Michelle1200006003-Dec-16
8Jo115000120030-Oct-16
3Mark10100080012-Aug-16
5Steve1000005002-Feb-16
2Sally950005005-Sep-16
1John9000010001-Jan-16
4Tina8700090024-Oct-16
7Alex85000(null)17-Jan-16

This sorts the data in the table by salary in descending order, which for numbers, is from highest to smallest.

Example 4 – ORDER BY Column Number

This example shows you how to order your results by specifying a column number.

SELECTsalesperson_id,first_name,salary,commission,hire_dateFROM salespersonORDER BY 2 DESC;

Result:

SALESPERSON_IDFIRST_NAMESALARYCOMMISSIONHIRE_DATE
4Tina8700090024-Oct-16
5Steve1000005002-Feb-16
2Sally950005005-Sep-16
6Michelle1200006003-Dec-16
3Mark10100080012-Aug-16
1John9000010001-Jan-16
8Jo115000120030-Oct-16
7Alex85000(null)17-Jan-16

This sorts the results by the second column in the SELECT clause. In this case, it is the first_name column (salesperson_id is column 1, first_name is column 2, salary is 3, and so on).

This is the order of the columns in the SELECT clause, and not the table.

I try to avoid using column numbers when ordering, as it’s not clear which column is being ordered. Also, if the sequence that the columns are mentioned in the SELECT clause is changed, then the ordering will break, or order by the incorrect values.

Example 5 – ORDER BY a Column Alias

This example shows you how you can order by a column alias. This is very helpful to reduce the amount of code you write and to keep your logic in one place (the SELECT clause, for example).

SELECTsalesperson_id,first_name,salary + commission AS total_earningsFROM salespersonORDER BY total_earnings DESC;

Result:

SALESPERSON_IDFIRST_NAMETOTAL_EARNINGS
7Alex(null)
6Michelle120600
8Jo116200
3Mark101800
5Steve100500
2Sally95500
1John91000
4Tina87900

This query shows the salespeople in order of their total earnings. Using a column alias in the SQL ORDER BY clause is helpful, especially when working with complicated functions.

Example 6 – ORDER BY an Expression

This example shows how you can order by an expression.

SELECTsalesperson_id,first_name,salary/52FROM salespersonORDER BY salary/52 DESC;

Result:

SALESPERSON_IDFIRST_NAMESALARY/52
6Michelle2307.692308
8Jo2211.538462
3Mark1942.307692
5Steve1923.076923
2Sally1826.923077
1John1730.769231
4Tina1673.076923
7Alex1634.615385

This query shows the weekly salary of each salesperson.

Example 7 – ORDER BY Function

This example shows how you can use ORDER BY with a function.

SELECTsalesperson_id,first_name,FLOOR(salary/52)FROM salespersonORDER BY FLOOR(salary/52) DESC;

Result:

SALESPERSON_IDFIRST_NAMEFLOOR(SALARY/52)
6Michelle2307
8Jo2211
3Mark1942
5Steve1923
2Sally1826
1John1730
4Tina1673
7Alex1634

You can see that the results have been ordered by the function value.

Example 8 – ORDER BY with NULLS FIRST (Oracle)

This example shows how the NULLS FIRST keyword works.

SELECTsalesperson_id,first_name,salary,commissionFROM salespersonORDER BY commission NULLS FIRST;

Result:

SALESPERSON_IDFIRST_NAMESALARYCOMMISSION
7Alex85000(null)
2Sally95000500
5Steve100000500
6Michelle120000600
3Mark101000800
4Tina87000900
1John900001000
8Jo1150001200

As you can see, the NULL values are shown at the top of the list.

Example 9 – ORDER BY with NULLS LAST

(Oracle)

This example shows how the NULLS LAST keyword works.

SELECTsalesperson_id,first_name,salary,commissionFROM salespersonORDER BY commission NULLS LAST;

Result:

SALESPERSON_IDFIRST_NAMESALARYCOMMISSION
2Sally95000500
5Steve100000500
6Michelle120000600
3Mark101000800
4Tina87000900
1John900001000
8Jo1150001200
7Alex85000(null)

As you can see, the NULL values are shown at the bottom of the list.

Example 10 – ORDER BY Two Columns

This example shows how you can use SQL ORDER BY with two columns.

SELECTsalesperson_id,first_name,salary,commissionFROM salespersonORDER BY commission, salary;

Result:

SALESPERSON_IDFIRST_NAMESALARYCOMMISSION
2Sally95000500
5Steve100000500
6Michelle120000600
3Mark101000800
4Tina87000900
1John900001000
8Jo1150001200
7Alex85000(null)

This query orders by the commission values in ascending order, then for records where the commission is the same, it orders by salary in ascending order.

Example 11 – ORDER BY Two Columns in Different Order

This example orders by two columns, but they are in a different order.

SELECTsalesperson_id,first_name,salary,commissionFROM salespersonORDER BY commission ASC, salary DESC;

Result:

SALESPERSON_IDFIRST_NAMESALARYCOMMISSION
5Steve100000500
2Sally95000500
6Michelle120000600
3Mark101000800
4Tina87000900
1John900001000
8Jo1150001200
7Alex85000(null)

This query orders by the commission values in ascending order, then for records where the commission is the same, it orders by salary in descending order.

Common Questions

Here are some common questions when it comes to using the Order By clause.

What Is SQL Order By 1?

ORDER BY 1 means that the results of the query are ordered by the first column specified in the SELECT clause.

You might see an SQL query that has “ORDER BY 1” in it:

SELECTsalesperson_id,first_name,salary,commissionFROM salespersonORDER BY 1;

This would order the results by the first column in the SELECT clause, which is the salesperson_id column in this example.

What Is SQL Order By 2?

This means that the results of the query are ordered by the second column specified in the SELECT clause.

For example:

SELECTsalesperson_id,first_name,salary,commissionFROM salespersonORDER BY 2;

This would order the results by the first_name column as it is the second column in the SELECT list.

You can change the ORDER BY 2 to any other number, up to the number of columns in the select clause.

ORDER BY 3 will order by the third column, for example.

Can we use WHERE with ORDER BY?

Yes, you can use the WHERE clause with or without the ORDER BY clause.

When you use WHERE in a query with ORDER BY, the results are filtered to only those that match the WHERE clause, and then the results are ordered based on what criteria you specified in the ORDER BY clause.

Which comes first – ORDER BY or WHERE?

The WHERE clause must come before the ORDER BY clause in the SELECT query. In almost all cases, the ORDER BY clause is the last clause in the query.

Can we use two columns in the ORDER BY clause?

Yes, you can use two columns (or as many columns as you like). You can separate each column with a comma, and can even specify ascending or descending for each column.

For example:

SELECTsalesperson_id,first_name,salary,commissionFROM salespersonORDER BY commission ASC, salary DESC;

This query will order the results by commission in ascending order and then salary in descending order.

Conclusion

So, that’s how you can use the SQL ORDER BY clause in Oracle SQL to order your results. It’s a powerful clause and has a few keywords to get you the result that you need.

Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!

SQL ORDER BY – The Complete Guide (2024)

FAQs

How do you do ORDER BY in SQL? ›

ORDER BY is used with the SQL SELECT statement and is usually specified after the WHERE, HAVING, and GROUP BY clauses. Some databases sort the query results in an ascending order by default. To sort the data in ascending order, we use the keyword ASC. To sort the data in descending order, we use the keyword DESC.

What is the correct order of a SQL? ›

It also helps to predict the outcome of queries, troubleshoot issues, and optimize performance. What is the correct order of execution for a given query? The correct order of execution in SQL is FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and LIMIT.

What is the rule of ORDER BY in SQL? ›

The ORDER BY command is used to sort the result set in ascending or descending order. The ORDER BY command sorts the result set in ascending order by default. To sort the records in descending order, use the DESC keyword.

What is the ORDER BY ASC or DESC in SQL? ›

ASC | DESC

Specifies that the values in the specified column should be sorted in ascending or descending order. ASC sorts from the lowest value to highest value. DESC sorts from highest value to lowest value. ASC is the default sort order.

What is the alternative of ORDER BY in SQL Server? ›

The ORDER BY clause in a query forces the database to return rows in the specified order. The only alternative is to just not use ORDER BY which means that the database is free to return the rows in any order it likes. This often results is faster performance and never in slower performance.

What is the condition in ORDER BY in SQL? ›

SQL ORDER BY clause is used after the WHERE clause (i.e. after filtering the data) to sort the result in either Ascending or Descending order. DESC: Keyword is used to arrange the result in Descending Order. Note: Ascending is a default sort order.

What is the mnemonic for SQL order? ›

The order of clauses MUST always be as below. The mnemonic I learned to help me remember the order is Some French Waiters Grow Healthy Oranges & Lemons. It is kind of weird and takes a few tries to memorize but it works for me!

Does the order matter in SQL? ›

No the sequence of columns doesn't matter as long as they are in the same SQL scope. Your query should run fine.

How to rank order SQL? ›

To define the ranks for each field individually, the SQL server provides a RANK() function. The RANK() function allocates a rank, that is, an integer number to each row within a group of data sets. The RANK() function is also known as the window function.

How to manually order rows in SQL? ›

How to Sort Rows in SQL
  1. After the ORDER BY keyword, you simply list the column(s) by which you want to sort the records.
  2. These columns do not need to be displayed in the output, i.e., listed in the SELECT statement.
  3. You set the sorting order (ascending or descending) using the DESC and ASC keywords.
May 13, 2021

Can there be two ORDER BY in SQL? ›

You can also ORDER BY two or more columns, which creates a nested sort . The default is still ascending, and the column that is listed first in the ORDER BY clause takes precedence. The following query and Figure 3 and the corresponding query results show nested sorts.

How many ways we use order in SQL? ›

Six Operations to Order: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY. By using examples, we will explain the execution order of the six most common operations or pieces in an SQL query. Because the database executes query components in a specific order, it's helpful for the developer to know this order.

What happens if you don't specify ASC or DESC after SQL ORDER BY? ›

Explanation: If we have not specified any sorting with the ORDER BY clause, SQL always uses the ASC as a default sorting order.

What is the ORDER BY clause in SQL? ›

The ORDER BY clause specifies the particular order in which you want selected rows returned. The order is sorted by ascending or descending collating sequence of a column's or an expression's value.

What is the difference between ORDER BY ASC and DESC date? ›

You can use the ASC and DESC keywords to specify ascending (smallest value first) or descending (largest value first) order. The default order is ascending. For DATE and DATETIME data types, smallest means earliest in time and largest means latest in time.

How to ORDER BY and limit in SQL? ›

The solution is to combine ORDER BY and LIMIT in the same query. The DESC clause used in ORDER BY . specifies the results in descending order. Combined with the LIMIT 1 , the query returns a single record in the result set.

How to ORDER BY and GROUP BY in SQL? ›

When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement:
  1. The GROUP BY clause is placed after the WHERE clause.
  2. The GROUP BY clause is placed before the ORDER BY clause.
Mar 25, 2021

How do you ORDER BY in Access SQL? ›

ORDER BY is usually the last item in an SQL statement. You can include additional fields in the ORDER BY clause. Records are sorted first by the first field listed after ORDER BY. Records that have equal values in that field are then sorted by the value in the second field listed, and so on.

Does ORDER BY or WHERE come first in SQL? ›

The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query. Use ASC or DESC to specify the sorting order after the column name. Use ASC to sort the records in ascending order or use DESC for descending order.

Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated:

Views: 5881

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.