Beginner PostgreSQL

Sorting Results with ORDER BY in PostgreSQL

Sort your query output by one or more columns in ascending or descending order.

4 min read Tutorial

Without ORDER BY, PostgreSQL returns rows in no guaranteed order. Adding this clause lets you control exactly how the result set is sorted.

Basic Sorting

-- Ascending (default)
SELECT first_name, last_name, created_at
FROM customers
ORDER BY created_at ASC;

-- Descending
SELECT first_name, last_name, created_at
FROM customers
ORDER BY created_at DESC;

ASC is the default direction and can be omitted. DESC reverses the order, putting the largest or most recent values first.

Sorting by Multiple Columns

-- Sort by country ascending, then by city descending
SELECT first_name, city, country
FROM customers
ORDER BY country ASC, city DESC;

-- You can mix directions freely
SELECT product_name, category, price
FROM products
ORDER BY category ASC, price DESC;

PostgreSQL evaluates the first column first. When two rows have the same value in that column, it uses the second column to break the tie, and so on.

Sorting with NULLS FIRST / NULLS LAST

-- Put rows with NULL phone at the end
SELECT first_name, phone
FROM customers
ORDER BY phone ASC NULLS LAST;

-- Put NULLs at the beginning
SELECT first_name, phone
FROM customers
ORDER BY phone DESC NULLS FIRST;

By default, ASC puts NULLs last and DESC puts them first. The NULLS FIRST / NULLS LAST keywords let you override this behavior.

Common Use Cases

  • Displaying the most recent orders or posts at the top
  • Alphabetical listings of names or products
  • Leaderboards sorted by score descending
  • Pagination combined with LIMIT and OFFSET

Try this query in UnifySQL

Write, optimize, and collaborate on PostgreSQL queries with AI assistance.

Start Free