The ORDER BY Clause

How to sort your query results

← All topics

What is ORDER BY?

By default, SQL returns rows in no guaranteed order. ORDER BY lets you sort the results by one or more columns — either ascending (smallest to largest, A to Z) or descending (largest to smallest, Z to A).

SELECT column1, column2
FROM table_name
ORDER BY column1;

ORDER BY always comes at the end of a query, after FROM and any WHERE clause.

ASC and DESC

You control sort direction with ASC (ascending) or DESC (descending). If you don't specify either, SQL defaults to ascending.

-- Cheapest drinks first (ascending — same as writing ASC)
SELECT drink_type, price_usd
FROM coffee_shop_sales
ORDER BY price_usd;

-- Most expensive drinks first (descending)
SELECT drink_type, price_usd
FROM coffee_shop_sales
ORDER BY price_usd DESC;

Sorting text and dates

Text columns sort alphabetically — A to Z for ASC, Z to A for DESC. Date columns sort chronologically — oldest first for ASC, most recent first for DESC.

-- Alphabetical by drink name
SELECT drink_type, price_usd
FROM coffee_shop_sales
ORDER BY drink_type;

-- Most recent orders first
SELECT order_id, order_date
FROM online_bookstore_orders
ORDER BY order_date DESC;

💡 Quick reference

GoalSyntax
Sort ascending (default)ORDER BY col or ORDER BY col ASC
Sort descendingORDER BY col DESC
Sort text A–ZORDER BY text_col
Sort text Z–AORDER BY text_col DESC
Oldest date firstORDER BY date_col
Most recent date firstORDER BY date_col DESC

Combining with WHERE

You can use ORDER BY together with WHERE. The clause order must always be SELECT … FROM … WHERE … ORDER BY. The filtering happens first, then the sorted results are returned.

-- Large drinks only, sorted most expensive first
SELECT drink_type, size, price_usd
FROM coffee_shop_sales
WHERE size = 'Large'
ORDER BY price_usd DESC;

Common mistakes

Putting ORDER BY before WHERE — the correct order is always WHERE first, then ORDER BY. Reversing them causes an error.

Sorting by a column you didn't SELECT — this is actually allowed in most databases. You can sort by any column in the table even if it doesn't appear in your SELECT list.

Forgetting DESC — omitting it gives you ascending order, which is correct for "cheapest first" or "oldest first" but wrong for "most expensive first" or "most recent first".


Practice: ORDER BY

Apply what you learned above. Write a query that matches each task.

ORDER BY

Table Schema

Table:
Columns:

Task

Tip: Ctrl + Enter to submit