A Detailed Guide to SQL ORDER BY (2024)

It’s often necessary to display the output of SQL query in specific order rather than arbitrarily. In this article, I’ll explain the many ways you can do it with the SQL ORDER BY clause.

To sort records in SQL, you’ll need to use the ORDER BY clause. In this article, I’ll explain in detail how to use ORDER BY to sort output by one or more columns, in ascending (A-Z) or descending (Z-A) order, and by using existing column(s) or using column(s) calculated by an aggregate function. Don’t worry – it’s not as complicated as it sounds!

How to Sort Rows in SQL

If you don’t sort the output of your SQL query, the row order will be arbitrary. If you want the rows of the resulting table to appear in specific order, you’ll need to use the ORDER BY clause.

The basic syntax for ORDER BY is as follows:

SELECT ...columns...FROM tableORDER BY sorting_column ASC/DESC;
  • After the ORDER BY keyword, you simply list the column(s) by which you want to sort the records.
  • These columns do not need to be displayed in the output, i.e., listed in the SELECT statement.
  • You set the sorting order (ascending or descending) using the DESC and ASC keywords. The ASC keyword is optional; if no keyword is specified after the column name, the rows will be sorted in ascending order by default.
  • ORDER BY is positioned at the end of the query.

Check out this article for an animation of how ORDER BY works. Now, let’s see some practical ORDER BY use cases.

ORDER BY One Column

Imagine that we run a shop that sells Halloween costumes. We have different kinds of costumes, masks, hats, and accessories in stock. Here is the table with our products:

products
idnamecategoryquantityprice
11Wonder Womancostumes219.95
12Vampiremasks43.95
13Magic Wandaccessories62.50
14Wizard of Ozhats33.95
15Supermancostumes314.95
16Hulkcostumes212.50
17Witchhats44.95
18Rapunzelcostumes0NULL
19Snow Whitecostumes123.95
20Freddy Kruegermasks33.95
21Alienmasks0NULL
22Cowboyhats34.95
23Ghostbusteraccessories213.95
24Swordaccessories73.50
25Zombiemasks82.95

Simple ORDER BY: Sorting by One Column

Let’s start with a very basic example: ordering our items alphabetically by name. To sort items in alphabetical order, we just need to order our result set by the name column in ascending order. As we know, ascending order is the default in SQL, so the ASC keyword can be omitted. Here’s our query:

SELECT *FROM productsORDER BY name;

And here’s the result, with all the records sorted alphabetically based on the product name:

idnamecategoryquantityprice
21Alienmasks0NULL
22Cowboyhats34.95
20Freddy Kruegermasks33.95
23Ghostbusteraccessories213.95
16Hulkcostumes212.50
13Magic Wandaccessories62.50
18Rapunzelcostumes0NULL
19Snow Whitecostumes123.95
15Supermancostumes314.95
24Swordaccessories73.50
12Vampiremasks43.95
17Witchhats44.95
14Wizard of Ozhats33.95
11Wonder Womancostumes219.95
25Zombiemasks82.95

Pretty simple, right? Now let’s sort our Halloween costumes based on price, starting from the most expensive. Going from highest to the lowest price requires sorting in descending order. Thus, our ORDER BY clause should include the DESC keyword:

SELECT *FROM productsORDER BY price DESC;
idnamecategoryquantityprice
19Snow Whitecostumes123.95
11Wonder Womancostumes219.95
15Supermancostumes314.95
23Ghostbusteraccessories213.95
16Hulkcostumes212.50
17Witchhats44.95
22Cowboyhats34.95
14Wizard of Ozhats33.95
12Vampiremasks43.95
20Freddy Kruegermasks33.95
24Swordaccessories73.50
25Zombiemasks82.95
13Magic Wandaccessories62.50
21Alienmasks0NULL
18Rapunzelcostumes0NULL

Here are several interesting things to note about SQL sorts:

  • Order of rows with the same value. Some items in our table have the same price – specifically, the Witch and Cowboy hats are $4.95, while the Wizard of Oz hat and the Vampire and Freddy Krueger masks are $3.95. How does SQL order such rows? There are actually no specific rules for these cases; the result is non-deterministic. In other words, the order of rows containing the same sort column value may vary every time the query is run. If you need the order of rows to be consistent, use a unique column to sort the rows. If that’s not possible, see if you can sort the result set using a combination of columns that result in a determined order. We’ll be covering sorting by multiple columns later in this article.
  • Sorting behavior for NULL values. In the result table above, rows with NULL values in the sort column are put at the very end of the table. However, this behavior is not consistent across different relational databases. I used MySQL to run this query, and this database considers NULL values as the lowest possible value. Thus, it sorts them last when descending order is requested. The result would be the same in the SQL Server and SQLite databases. However, PostgreSQL and Oracle databases treat NULLs as the largest possible values and put them first when sorting in descending order. In most cases, you can change the default behavior of ORDER BY with respect to NULL values. Learn how in this detailed guide.

Great! Let’s move on to more complicated examples.

Sorting by a Column Calculated by an Aggregate Function

In SQL, you can sort results based on one or more calculated columns. This column can be calculated using one of the aggregated functions (like AVG(), SUM(), COUNT(), MAX(), MIN()) or another method. Let’s see how this works in practice.

In our next example, we want to see which product categories include more expensive items. In particular, we want to sort categories by their average product price, starting with the most expensive.

We’ll calculate the average price for each category, then sort rows in descending order according to this calculated column:

SELECT category, AVG(price) AS avg_priceFROM productsGROUP BY categoryORDER BY avg_price DESC;

Note that the ORDER BY clause is placed last, after the GROUP BY clause. Here’s the result:

categoryavg_price
costumes17.84
accessories6.65
hats4.62
masks3.62

It’s good to note that ORDER BY accepts number notation when referring to the sort column. For example, to sort the result set based on the first column, you can simply write ORDER BY 1.

Accordingly, the following query would give us the same result as in the above table:

SELECT category, AVG(price) AS avg_priceFROM productsGROUP BY categoryORDER BY 2 DESC;

Since the avg_price column is the second in our SELECT statement, we can refer to it in the ORDER BY clause using ‘2’.

This approach saves us time on typing, but it has one important drawback. If you modify the query by adding more fields to the SELECT statement, you should remember to check whether the number in the ORDER BY is still relevant or needs to be changed. Unfortunately, this step is quite often overlooked, resulting in the wrong order in the result set.

ORDER BY Multiple Columns

ORDER BY allows sorting the result set by two or more columns. However, to use this tool appropriately you need to understand how it works:

  • Sorting starts with ordering the data based on the first column mentioned in the ORDER BY If this column contains the same values, the corresponding rows are ordered based on the second column listed in the ORDER BY clause, and so on. Thus, the order of columns matters.
  • You can choose the order (i.e. ascending or descending) for each of the columns listed in ORDER BY. To specify the order, you simply put the DESC or ASC keyword after each of the columns listed. If you omit the DESC / ASC keyword, it will be sorted in ascending order by default.

Let’s see some examples.

Sorting by Multiple Columns in SQL

You may recall that when we were sorting our products according to price, the sorting result was non-deterministic. Specifically, there were several items with the same price that should have appeared in the same position but were actually ordered randomly. If we want more control over the sort order in such cases, we should add another column to the ORDER BY clause.

For example, we may start by sorting the items based on their price (from the most expensive to the cheapest). Then we may choose to alphabetically sort items with the same price. This implies ordering by price in descending order and then ordering by name in ascending order. Here’s the query:

SELECT id, name, priceFROM productsORDER BY price DESC, name;
idnameprice
19Snow White23.95
11Wonder Woman19.95
15Superman14.95
23Ghostbuster13.95
16Hulk12.50
22Cowboy4.95
17Witch4.95
20Freddy Krueger3.95
12Vampire3.95
14Wizard of Oz3.95
24Sword3.50
25Zombie2.95
13Magic Wand2.50
21AlienNULL
18RapunzelNULL

We have selected only three columns so that we can more easily focus on the sorting results. As you can see:

  • The Cowboy and Witch hats have the same price and are now ordered alphabetically.
  • Similarly, another group of items priced at $3.95 is also ordered alphabetically by name.
  • Finally, SQL considers the NULL values in the price column as the same value, so we have those rows ordered alphabetically according to the item name.

You can use the number notation when listing multiple columns in the ORDER BY clause; it works the same way. The following query will give us the same results as the one above:

SELECT id, name, priceFROM itemsORDER BY 3 DESC, 2;

However, you should be very careful with number notation, since editing the query may change the column order – and thus the sort output.

Sorting by Multiple Calculated Columns

Let’s add complexity to our final sorting example. In this case, we want to sort the product categories by the total number of in-stock items, starting from the category with the fewest items. If any of the categories have the same number of items in stock, we want the category with the highest product price to be listed first.

In other words, we want to sort the output by two columns, with both calculated using aggregate functions. Moreover:

  • The sum of the number of items in each category should be sorted in ascending order.
  • The maximum product price in each category should be sorted in descending order.

Here’s the query and the result:

SELECT category, SUM(quantity) AS total_quantity, MAX(price) AS max_priceFROM itemsGROUP BY categoryORDER BY total_quantity, max_price DESC;
categorytotal_quantitymax_price
costumes823.95
hats104.95
accessories1513.95
masks153.95

In this query, we calculate the total number of items (SUM(quantity)) and the maximum product price (MAX(price)) for each category (GROUP BY category). We also assign the aliases (total_quantity and max_price, respectively). Finally, we order the output by total_quantity in ascending order (omitting the ASC keyword) and by max_price in descending order (using the DESC keyword).

As expected, the table is sorted by the total number of items in each category, starting with costumes (which has the fewest items in stock). But notice that the accessories and masks categories both have 15 items in stock. In this case, sorting by the second column comes into play and these two rows are ordered according to the most expensive product in the corresponding category. Specifically, the accessories category comes first (as it includes Ghostbusters, which is priced at $13.95), while the masks category comes last (as the most expensive masks cost only $3.95).

To learn more advanced ORDER BY usages – like putting expressions in the ORDER BY condition – check out this comprehensive guide.

Time to Practice SQL ORDER BY!

ORDER BY seems quite easy to grasp. However, sorting records in SQL has many nuances that are best learned with practice. I recommend starting with the SQL Basics course; among other things, it covers everything you need to know about sorting rows in SQL. The course is interactive and includes 149 coding challenges, from the very basic to the more advanced.

If you are eager to build a solid SQL foundation, consider completing LearnSQL.com’s SQL Fundamentals track. It includes SQL Basics and two additional courses that cover standard SQL functions, creating and updating tables in SQL, and much more.

Thanks for reading, and happy learning!

A Detailed Guide to SQL ORDER BY (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 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 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.

How to use ORDER BY and WHERE clause together 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.

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.

How do you ORDER BY highest to lowest in SQL? ›

SQL ORDER BY Descending: DESC keyword

Using the DESC keyword in the SQL ORDER BY clause allows you to sort the result in descending order, meaning the data will be sorted from the highest value to the lowest value for the specified column.

Does order matter in ORDER BY SQL? ›

SQL Server is smart enough to understand that the order of columns in the GROUP BY doesn't matter.

Does ORDER BY go before limit SQL? ›

The first thing you'll learn in SQL is the order in which we write various clauses in our queries (SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, then LIMIT). However, the order in which the database interprets the query is slightly different.

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.

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!

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.

What are the order commands in SQL? ›

The order of execution in SQL follows a specific set of rules. First, the FROM clause is evaluated, followed by the WHERE clause, then the SELECT clause. The GROUP BY clause is evaluated next, followed by the HAVING clause, and finally, the ORDER BY clause.

How does SQL ORDER BY work? ›

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

What is ORDER BY clause? ›

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.

Is SQL ORDER BY stable? ›

The ORDER BY clause contains a column or combination of columns that are guaranteed to be unique. The simplest way to understand that a sort is not stable is to go back to the definition of a table. Tables are inherently unordered in SQL. So, there is no ordering to fall back on for "stability".

How to order in SQL by number? ›

Sorting By Column Number (instead of name)

In other words, if we want to order by a column, that column must be specified in the SELECT list. The rule checks for ORDER BY clauses that reference select list columns using the column number instead of the column name.

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.

Top Articles
Latest Posts
Article information

Author: Roderick King

Last Updated:

Views: 5957

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Roderick King

Birthday: 1997-10-09

Address: 3782 Madge Knoll, East Dudley, MA 63913

Phone: +2521695290067

Job: Customer Sales Coordinator

Hobby: Gunsmithing, Embroidery, Parkour, Kitesurfing, Rock climbing, Sand art, Beekeeping

Introduction: My name is Roderick King, I am a cute, splendid, excited, perfect, gentle, funny, vivacious person who loves writing and wants to share my knowledge and understanding with you.