Docs
Docs/Filtering & Sorting/ORDER BY

SQL ORDER BY to sort results

Sort query results by one or more columns, in ascending or descending order.

ORDER BY sorts the result set by one or more columns.

Basic Sorting

-- Ascending (A-Z, 0-9) - default
SELECT * FROM users ORDER BY name;
SELECT * FROM users ORDER BY name ASC;

-- Descending (Z-A, 9-0)
SELECT * FROM users ORDER BY created_at DESC;

Multiple Columns

Sort by first column, then by second column for ties:

-- Sort by country A-Z, then by name A-Z within each country
SELECT * FROM users 
ORDER BY country, name;

-- Mix directions
SELECT * FROM products 
ORDER BY category ASC, price DESC;

-- Most expensive first within each category
SELECT * FROM products 
ORDER BY category, price DESC;

Sorting by Expressions

-- Sort by calculated value
SELECT *, price * quantity AS total 
FROM order_items 
ORDER BY price * quantity DESC;

-- Sort by alias
SELECT *, price * quantity AS total 
FROM order_items 
ORDER BY total DESC;

-- Sort by column position (not recommended)
SELECT name, email, created_at FROM users 
ORDER BY 3 DESC;  -- Orders by 3rd column (created_at)

NULL Handling

-- PostgreSQL: Control NULL position
SELECT * FROM users ORDER BY phone NULLS FIRST;
SELECT * FROM users ORDER BY phone NULLS LAST;

-- SQLite/MySQL: NULLs are smallest (first in ASC, last in DESC)
-- To put NULLs last in ascending order:
SELECT * FROM users 
ORDER BY phone IS NULL, phone ASC;

Custom Sort Order

-- Custom priority order using CASE
SELECT * FROM orders 
ORDER BY 
    CASE status
        WHEN 'urgent' THEN 1
        WHEN 'pending' THEN 2
        WHEN 'processing' THEN 3
        WHEN 'completed' THEN 4
        ELSE 5
    END;

Need help?

Join our Discord community for support and discussions.

Join Discord