Skip to main content
Back to Documentation
DocsFundamentalsORDER BY

ORDER BY

Fundamentals

Concept

Without ORDER BY, SQL does not guarantee any particular row order. The database engine is free to return rows in whatever sequence is most efficient. If your application relies on a specific order — most recent first, alphabetical, lowest price — you must specify ORDER BY explicitly.

You can sort by one or more columns or expressions. Each sort key can be ASC (ascending, the default) or DESC (descending). When you sort by multiple columns, the database orders by the first key and uses subsequent keys only to break ties.

ORDER BY is one of the last clauses evaluated in query processing. This means you can reference column aliases from the SELECT list, ordinal positions (ORDER BY 1), and even expressions that do not appear in SELECT. However, using ordinal positions is discouraged because it makes queries fragile when columns are reordered.

Syntax

-- Single column, descending
SELECT * FROM products
ORDER BY price DESC;

-- Multiple columns
SELECT * FROM orders
ORDER BY customer_id ASC, order_date DESC;

-- Using a SELECT alias
SELECT
  name,
  price * quantity AS line_total
FROM order_items
ORDER BY line_total DESC;

Practical Example

Using the ecommerce schema (customers, orders, order_items, products)

-- Top 10 most expensive products
SELECT name, price, category
FROM products
ORDER BY price DESC
LIMIT 10;

-- Customer orders sorted by date, then amount
SELECT
  c.first_name || ' ' || c.last_name AS customer,
  o.order_date,
  o.total_amount
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
ORDER BY o.order_date DESC, o.total_amount DESC;

Common Pitfalls & Tips

  • 1NULL values sort differently across databases. In PostgreSQL NULLs come last for ASC; in MySQL they come first. Use NULLS FIRST / NULLS LAST to be explicit.
  • 2ORDER BY with large result sets can be expensive — make sure to combine with LIMIT when you only need the top N rows.
  • 3Avoid ORDER BY 1, 2 in production queries — positional references break silently when someone adds a column.
Practice ORDER BY sorting