TExcelTAD
Home › PostgreSQL › PostgreSQL ORDER BY

PostgreSQL ORDER BY

Without ORDER BY, a database may return rows in any order it likes. ORDER BY sorts the result by one or more expressions, each ascending (ASC, the default) or descending (DESC).

Sorting by one column

pgsql · try it yourself
SELECT title, price
FROM books
WHERE category_id = 1
ORDER BY price;
       title       | price
-------------------+-------
 Harbor Lights     | 12.50
 Starlight Kitchen | 13.75
 The Salt Road     | 14.99
 Paper Lanterns    | 15.20
 Winter in Sofia   | 17.80
(5 rows)

Add DESC for the opposite direction:

pgsql · try it yourself
SELECT name, salary
FROM employees
ORDER BY salary DESC;
      name      | salary
----------------+---------
 Rachel Adams   | 9500.00
 Nadia Hussein  | 6400.00
 Victor Chen    | 6200.00
 Omar Farouk    | 4800.00
 Sara Lindqvist | 3200.00
 Paul Becker    | 3100.00
 Lucy Evans     | 3000.00
 Tim Novak      | 2900.00
(8 rows)

Sorting by several columns

When the first sort key is equal, the second one decides, and so on. Each key has its own direction:

pgsql · try it yourself
SELECT country, city, first_name
FROM customers
WHERE country IN ('UK', 'Japan', 'Ireland')
ORDER BY country ASC, first_name DESC;
 country |  city   | first_name
---------+---------+------------
 Ireland | Dublin  | Liam
 Japan   | Osaka   | Keiko
 UK      | Leeds   | Olivia
 UK      | Glasgow | Isla
 UK      | Leeds   | Ben
(5 rows)

Sorting by an expression, alias or position

You can sort by a computed expression, by a column alias from the select list, or by the column's position number (1 is the first column):

pgsql · try it yourself
SELECT title, price * stock AS stock_value
FROM books
ORDER BY stock_value DESC
LIMIT 4;

SELECT title, length(title)
FROM books
ORDER BY 2, 1
LIMIT 4;
           title           | stock_value
---------------------------+-------------
 Algorithms on a Napkin    |      385.00
 Learning SQL the Calm Way |      359.10
 Clockwork Garden          |      315.00
 Ten Tiny Dragons          |      269.70
(4 rows)

     title     | length
---------------+--------
 Moon Socks    |     10
 Harbor Lights |     13
 The Map Thief |     13
 The Salt Road |     13
(4 rows)

Tip: Positional sorting (ORDER BY 2) is handy in quick queries, but in code that lives long, name the column: positions break silently when someone edits the select list.

Where do NULLs go?

In PostgreSQL, NULL sorts as if it were larger than every other value: last in ascending order, first in descending order. NULLS FIRST / NULLS LAST overrides that:

pgsql · try it yourself
SELECT name, birth_year FROM authors ORDER BY birth_year DESC LIMIT 3;

SELECT name, birth_year FROM authors ORDER BY birth_year DESC NULLS LAST LIMIT 3;
    name     | birth_year
-------------+------------
 Jonas Weber |
 Priya Nair  |       1990
 Aiko Tanaka |       1988
(3 rows)

    name     | birth_year
-------------+------------
 Priya Nair  |       1990
 Aiko Tanaka |       1988
 Grace Liu   |       1985
(3 rows)

Text sort order

Text is sorted according to the database's collation. This database uses the simple C rules, where every uppercase letter comes before every lowercase letter, so you can make text sorting case-insensitive by sorting on lower(...):

pgsql · try it yourself
CREATE TABLE words (w text);
INSERT INTO words VALUES ('banana'), ('Apple'), ('cherry'), ('apple'), ('Banana');

SELECT w FROM words ORDER BY w;
SELECT w FROM words ORDER BY lower(w), w;
CREATE TABLE
INSERT 0 5
   w
--------
 Apple
 Banana
 apple
 banana
 cherry
(5 rows)

   w
--------
 Apple
 apple
 Banana
 banana
 cherry
(5 rows)

Note: A server installed with a language-aware collation (for example en_US.UTF-8) sorts apple and Apple next to each other by default. If an exact order matters, specify it with lower() or an explicit COLLATE "C".

Custom orders

To sort by a meaning rather than alphabetically, sort by a CASE expression or by array_position in a list of values:

pgsql · try it yourself
SELECT id, status
FROM orders
WHERE customer_id IN (2, 4, 5)
ORDER BY array_position(ARRAY['pending', 'shipped', 'delivered', 'cancelled'], status), id;
 id |  status
----+-----------
 18 | pending
 16 | shipped
  2 | delivered
  6 | delivered
  8 | delivered
 15 | delivered
  5 | cancelled
(7 rows)

Test yourself

What is the default direction of ORDER BY price?

  1. Descending
  2. Ascending
  3. Random
  4. Insertion order

Where do NULL values appear with ORDER BY birth_year DESC in PostgreSQL?

  1. First
  2. Last
  3. They are removed
  4. In the middle

In ORDER BY country, first_name DESC, what does DESC apply to?

  1. Both columns
  2. Only first_name
  3. Only country
  4. Neither