Skip to main content

ORDER BY

Editorial

Introduction

A table's rows have no order of their own. Without ORDER BY, a query returns them in whatever order the database reads them, and nothing promises that order. ORDER BY names the order you want.

Here you will:

  • sort rows A to Z and Z to A with ASC and DESC
  • see how text, numbers and NULL sort
  • sort by several columns, by a column's position, by an alias or by an expression
  • see what happens to rows that tie
  • keep a sort cheap

Why Sorting Matters

Without ORDER BY, the order of the rows is not part of the answer.

The Problem

SELECT customer_city, customer_state
FROM olist_customers_dataset
LIMIT 10;

It returns the first 10 rows SQLite happens to read: franca first. SQLite's documentation: "If a SELECT statement that returns more than one row does not have an ORDER BY clause, the order in which the rows are returned is undefined." The same file read the same way gives the same rows, but no rule says it must.

The Solution

SELECT customer_city, customer_state
FROM olist_customers_dataset
ORDER BY customer_city
LIMIT 10;

Now the rows come A to Z by city: abadia dos dourados first (3 rows), then abadiania.

ORDER BY puts rows in the order you name. No ORDER BY, no promised order; tied rows come back in any order. 1, before ORDER BY: the table olist_customers_dataset, eight rows as stored, with their customer_city and customer_state: sao paulo, SP; campinas, SP; rio de janeiro, RJ; sao goncalo, RJ; belo horizonte, MG; porto alegre, RS; santos, SP; salvador, BA; as stored, no order is promised. Between them the clause ORDER BY customer_city ASC: A to Z by the city. 2, after ORDER BY: the 8 rows A to Z, numbered: 1, belo horizonte, MG; 2, campinas, SP; 3, porto alegre, RS; 4, rio de janeiro, RJ; 5, salvador, BA; 6, santos, SP; 7, sao goncalo, RJ; 8, sao paulo, SP; each city differs, so there is one order only. Under them ASC, the default: text 'Banana', 'apple', 'b' (capitals first), numbers 2, 2.5, 10, dates oldest first, NULL first; and DESC, written out: text 'b', 'apple', 'Banana', numbers 10, 2.5, 2, dates newest first, NULL last. And ties, three rows of SP: by the state alone they come back in any order (SQLite returned santos, sao paulo, campinas); by the state, then the city they come back as campinas, santos, sao paulo.

Watch ORDER BY Sort the Rows

Pick a table and an ORDER BY, then read the rows into the sorter one at a time or all at once. As each row goes in, its key cells light; once every row is in, the rows leave the sorter in order and land in the result, and each socket shows the place its row went to. Rows equal on every key are bracketed as a tie.

The same eight customers and six products as the WHERE stepper, and three words, each order as SQLite gives it. Read one row at a time, or every row at once.

Basic ORDER BY Syntax

ORDER BY comes after FROM and WHERE, and before LIMIT.

Syntax

SELECT columns
FROM table_name
ORDER BY column_name [ASC|DESC];

Sort Directions

DirectionMeaningOrderDefault?
ASCAscendingA to Z, 1 to 100Yes
DESCDescendingZ to A, 100 to 1No

Examples

SELECT customer_city, customer_state
FROM olist_customers_dataset
ORDER BY customer_city ASC
LIMIT 10;

ASC is the default, so this is the order of the block above: abadia dos dourados first.

SELECT customer_city, customer_state
FROM olist_customers_dataset
ORDER BY customer_city DESC
LIMIT 10;

DESC starts from the other end: zortea (2 rows), then ze doca.

Sorting Text Data

Text sorts character by character, by each character's code, so capitals come before small letters. In SQLite's words: "BINARY - Compares string data using memcmp(), regardless of text encoding."

Capitals First

SELECT column1 AS word
FROM (VALUES ('apple'), ('Banana'), ('cherry'))
ORDER BY word;

Banana, apple, cherry: the capital B comes before every small letter.

Ignoring Case

SELECT column1 AS word
FROM (VALUES ('apple'), ('Banana'), ('cherry'))
ORDER BY word COLLATE NOCASE;

apple, Banana, cherry. COLLATE NOCASE compares as if every letter were small: "Hence the 26 upper case characters of ASCII are folded to their lower case equivalents before the comparison is performed."

Every city in this dataset is written in small letters (none have a capital), so its cities sort the same either way. PostgreSQL sorts text by the database's collation: in the C collation it puts Banana, apple, cherry in that order, as SQLite does; other collations can differ.

Sorting Numeric Data

Numbers sort by their value.

Smallest First

SELECT order_id, product_id, price
FROM olist_order_items_dataset
ORDER BY price ASC
LIMIT 10;

The cheapest items cost 0.85: 3 of them, a tie (see Rows That Tie below).

Largest First

SELECT order_id, product_id, price
FROM olist_order_items_dataset
ORDER BY price DESC
LIMIT 10;

The most expensive item costs 6735.

Practical Use Cases

ScenarioORDER BY
Most expensive itemsORDER BY price DESC
Cheapest itemsORDER BY price ASC
Newest ordersORDER BY order_purchase_timestamp DESC
Oldest ordersORDER BY order_purchase_timestamp ASC
Largest paymentsORDER BY payment_value DESC

Sorting by Multiple Columns

ORDER BY can take several columns: the second one orders the rows that tie on the first, and so on.

Syntax

ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...

Example: State Then City

SELECT customer_state, customer_city
FROM olist_customers_dataset
ORDER BY customer_state ASC, customer_city ASC
LIMIT 20;

The rows of AC come first, its cities A to Z: brasileia, then cruzeiro do sul.

Mixed Directions

Each column takes its own direction:

SELECT s.seller_state, i.price
FROM olist_order_items_dataset AS i
JOIN olist_sellers_dataset AS s ON i.seller_id = s.seller_id
ORDER BY s.seller_state ASC, i.price DESC
LIMIT 20;

States run A to Z, and inside each state the prices run from the highest: AM starts at 949, then 114.

Rows That Tie

Rows equal on every column of the ORDER BY are a tie, and SQL does not say which comes first: "The order in which two rows for which all ORDER BY expressions evaluate to equal values are returned is undefined." Sorted by the state alone, the stepper above brackets the rows of SP as a tie; adding the city orders them. A LIMIT that cuts through a tie keeps whichever tied rows come first, so add a column that tells them apart when it matters.

Sorting by Column Position

A number in ORDER BY names a column of the result by its position, counting from 1.

Syntax

SELECT col1, col2, col3
FROM table_name
ORDER BY 2;

Example

SELECT customer_state, customer_city, customer_zip_code_prefix
FROM olist_customers_dataset
ORDER BY 1, 2
LIMIT 10;

ORDER BY 1, 2 is ORDER BY customer_state, customer_city here: SQLite reads "a constant integer K" as "an alias for the K-th column of the result set".

When to Use Position Numbers

Useful for:

  • a long expression you would otherwise write twice
  • a quick query you will not keep

Avoid for:

  • queries that others read or that stay in a program: a column added to the SELECT moves every number after it
SELECT customer_city || ', ' || customer_state AS location,
       customer_zip_code_prefix
FROM olist_customers_dataset
ORDER BY 1
LIMIT 10;

ORDER BY 1 sorts by the joined text: abadia dos dourados, MG first.

Sorting by Aliases

ORDER BY can name a column of the result by its alias.

Example

SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customer_count DESC
LIMIT 5;

It sorts by the alias customer_count: SP first with 41,746 rows, then RJ with 12,852.

Three Ways to Name It

SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY COUNT(*) DESC
LIMIT 5;
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY 2 DESC
LIMIT 5;

The expression COUNT(*) and the position 2 give the same 5 rows in the same order. A name in ORDER BY is read as an alias first: "If the ORDER BY expression is an identifier that corresponds to the alias of one of the output columns, then the expression is considered an alias for that column." So an alias that reuses a column's name sorts by the alias.

Handling NULL Values

SQLite counts NULL as smaller than any value: "SQLite considers NULL values to be smaller than any other values for sorting purposes. Hence, NULLs naturally appear at the beginning of an ASC order-by and at the end of a DESC order-by."

NULLs First in ASC

SELECT product_id, product_category_name
FROM olist_products_dataset
ORDER BY product_category_name ASC
LIMIT 10;

The 610 products with no category come first.

NULLs Last in DESC

SELECT product_id, product_category_name
FROM olist_products_dataset
ORDER BY product_category_name DESC
LIMIT 10;

DESC starts at utilidades_domesticas; the products with no category come last.

NULLS FIRST and NULLS LAST

SELECT product_id, product_category_name
FROM olist_products_dataset
ORDER BY product_category_name ASC NULLS LAST
LIMIT 10;

NULLS LAST moves them to the end: agro_industria_e_comercio comes first now. SQLite has had it since version 3.30.0: "Add support for the NULLS FIRST and NULLS LAST syntax in ORDER BY clauses." The older way sorts on a flag first, 1 for a NULL, and gives the same order:

SELECT product_id, product_category_name
FROM olist_products_dataset
ORDER BY
    CASE WHEN product_category_name IS NULL THEN 1 ELSE 0 END,
    product_category_name ASC
LIMIT 10;

PostgreSQL does the opposite by default, as its documentation says: "By default, null values sort as if larger than any non-null value; that is, NULLS FIRST is the default for DESC order, and NULLS LAST otherwise." The same three categories sort as esporte_lazer, perfumaria, NULL there in ASC.

Sorting with Expressions

ORDER BY can sort by a value worked out from the columns.

Example: Sort by Total Cost

SELECT order_id, price, freight_value,
       price + freight_value AS total_cost
FROM olist_order_items_dataset
ORDER BY price + freight_value DESC
LIMIT 10;

The item with the highest price and freight together comes first: 6735 plus 194.31, 6929.31.

Example: Sort by Name Length

SELECT customer_city,
       LENGTH(customer_city) AS city_name_length
FROM olist_customers_dataset
ORDER BY LENGTH(customer_city) DESC
LIMIT 10;

vila bela da santissima trindade has the longest name: 32 characters.

Practice

Each exercise runs on the course's tables: press Run to see its rows.

Exercise 1: Basic Ascending Sort

Sort the customers A to Z by city:

-- Sort by city name (A to Z)

SELECT customer_id, customer_city, customer_state
FROM olist_customers_dataset
ORDER BY customer_city ASC
LIMIT 10;

The page shows 10 rows, from abadia dos dourados.

Exercise 2: Descending Numeric Sort

Find the most expensive order items:

-- Sort by price, highest first

SELECT order_id, product_id, price
FROM olist_order_items_dataset
ORDER BY price DESC
LIMIT 10;

The first costs 6735.

Exercise 3: Multiple Column Sort

Sort the customers by state, then by city inside each state:

-- Primary sort: state, Secondary sort: city

SELECT customer_state, customer_city, customer_id
FROM olist_customers_dataset
ORDER BY customer_state ASC, customer_city ASC
LIMIT 20;

The rows of AC come first, from brasileia.

Exercise 4: Sort with Aggregation

Find the states with the most customer rows:

-- Count customers per state and sort by count

SELECT
    customer_state,
    COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
ORDER BY customer_count DESC
LIMIT 10;

SP leads with 41,746 rows.

Exercise 5: Mixed Sort Directions

Sort payments by type A to Z, and by value from the highest inside each type:

-- Mixed sort: type ASC, value DESC

SELECT payment_type, payment_value, order_id
FROM olist_order_payments_dataset
ORDER BY payment_type ASC, payment_value DESC
LIMIT 20;

boleto comes first, from 7274.88.

Performance Considerations

A sort costs work, and the plan SQLite makes for a query shows when it does. Every number here was measured on the site's engine (SQLite 3.54.1), the median of six runs after a first one.

How Sorting Works

  1. SQLite reads the rows the query needs.
  2. It puts them in a sorter: its plan says USE TEMP B-TREE FOR ORDER BY.
  3. It hands the rows out in order.

Performance Tips

1. An index in the sort's order. The dataset has an index on customer_state, so ORDER BY customer_state reads the index in order and needs no sorter: ten rows took 0.02 ms, against 10.84 ms for ORDER BY customer_city, which has no index. All 99,441 rows: 4.77 ms against 90.43 ms.

2. A LIMIT keeps the sorter small. The ten most expensive items took 13.75 ms; keeping the top 100,000 took 104.72 ms.

SELECT order_id, product_id, price
FROM olist_order_items_dataset
ORDER BY price DESC
LIMIT 10;

3. Filter first when the filter keeps few rows. Sorting only the 625 canceled orders by date took 1.11 ms, against 13.78 ms for every order. A filter that keeps nearly every row does not help: the 96,478 delivered orders, read through the index on order_status, took 19.69 ms.

SELECT order_id, order_purchase_timestamp
FROM olist_orders_dataset
WHERE order_status = 'delivered'
ORDER BY order_purchase_timestamp DESC
LIMIT 10;

4. An expression has no index. ORDER BY price + freight_value always goes through the sorter (16.55 ms for the top ten); a column with an index in the sort's order need not.

Summary

Key Takeaways

  • Without ORDER BY no order is promised
  • ASC is the default, smallest first; DESC puts the largest first
  • Text sorts by character codes, capitals first; COLLATE NOCASE ignores case
  • More columns order the rows that tie on the earlier ones; rows equal on all of them come in any order
  • A number names a result column by position, an alias by name
  • On SQLite NULL comes first in ASC and last in DESC; NULLS FIRST and NULLS LAST change that
  • An index in the sort's order, a LIMIT and a filter that keeps few rows make a sort cheaper

Quick Reference

-- Ascending (default)
ORDER BY column_name ASC

-- Descending
ORDER BY column_name DESC

-- Multiple columns
ORDER BY col1 ASC, col2 DESC

-- NULLs at the end
ORDER BY column_name ASC NULLS LAST

-- Ignoring case
ORDER BY column_name COLLATE NOCASE

-- By position
ORDER BY 1, 2

-- By alias
ORDER BY my_alias DESC

-- By expression
ORDER BY price + freight_value DESC

What's Next?

GROUP BY folds rows that share a value into one row each.