← Back to PostgreSQL Course | Chapter 2: Basic Queries | Lesson 5 of 7

ORDER BY

ORDER BY sorts the result by one or more columns, ascending or descending.

In this page:

  1. ORDER BY
Syntax
sql
SELECT columns
FROM table_name
ORDER BY column1 DESC, column2 ASC;

ORDER BY

ASC is the default and DESC reverses the order. List several columns to break ties in order.

Sorting by an alias or column position is allowed. In PostgreSQL, NULLs sort last in ascending order by default, and NULLS FIRST or NULLS LAST can override that.

Note: Without ORDER BY the row order is not guaranteed.

Example: ORDER BY

sql
CREATE TABLE players (id INTEGER PRIMARY KEY, name TEXT, team TEXT, score INTEGER);
INSERT INTO players VALUES (1, 'Ada', 'red', 30), (2, 'Bob', 'blue', 50), (3, 'Cy', 'red', 50), (4, 'Di', 'blue', 10);
SELECT name, score FROM players ORDER BY score DESC, name ASC;
SELECT team, name FROM players ORDER BY team, score DESC;

-- Output:
-- name | score
-- Bob | 50
-- Cy | 50
-- Ada | 30
-- Di | 10
-- team | name
-- blue | Bob
-- blue | Di
-- red | Cy
-- red | Ada
Related Topics
Common Mistakes
  1. Relying on an unsorted result order
  2. Forgetting DESC for top-N queries
  3. Sorting large results without an index
Chapter Summary
  • ORDER BY sorts the result
  • ASC default, DESC reverses
  • Multiple columns break ties
  • No ORDER BY means no guaranteed order
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.