How to Use ORDER BY in SQL

Use ORDER BY when query results should appear in a specific sequence instead of the database’s default order. This is essential for sorting dates, prices, names, scores, and ranked reports.

What you’ll build or solve

You’ll learn how to use ORDER BY in SQL for ascending and descending sorting. You’ll also know how to sort by multiple columns and aggregated results.

When this approach works best

This approach is the right choice when the result order affects readability, rankings, or business logic.

Common real-world scenarios include:

  • Newest orders first
  • Highest prices first
  • Alphabetical customer lists
  • Top scores
  • Revenue leaderboards

This is a bad idea when result order does not matter and sorting would only add unnecessary query cost.

Prerequisites

You only need:

  • A SQL table with sortable columns
  • Basic SELECT knowledge

Step-by-step instructions

Step 1: Add ORDER BY after the main query

Use ascending order by default.

SELECT *
FROM products
ORDER BY price;

This sorts from lowest to highest.

Use DESC for descending order.

SELECT *
FROM orders
ORDER BY created_at DESC;

This is perfect for newest-first lists.

Sort by multiple columns when tie-breaking matters.

SELECT *
FROM users
ORDER BY country, created_at DESC;

What to look for:

  • Ascending is the default
  • Use DESC for highest/newest first
  • Multiple columns create tie-breakers
  • Great for rankings and reports
  • Sorting large datasets can add cost

Examples you can copy

Newest users

SELECT *
FROM users
ORDER BY created_at DESC;

Cheapest products

SELECT *
FROM products
ORDER BY price ASC;

Revenue leaderboard

SELECT country, SUM(total) AS revenue
FROM orders
GROUP BY country
ORDER BY revenue DESC;

Common mistakes and how to fix them

Mistake 1: Expecting DESC by default

What the reader might do:

ORDER BY created_at

Why it breaks: this sorts oldest first.

Corrected approach:

ORDER BY created_at DESC

Mistake 2: Sorting before grouping logic

What the reader might do:

SELECT country, SUM(total)
FROM orders
ORDER BY SUM(total) DESC
GROUP BY country;

Why it breaks: GROUP BY must come before ORDER BY.

Corrected approach:

Place sorting after grouping.

Mistake 3: Sorting by ambiguous column names in joins

What the reader might do:

ORDER BY created_at

Why it breaks: multiple joined tables may contain the same column.

Corrected approach:

Use the table alias.

ORDER BY orders.created_at DESC

Troubleshooting

If the order looks reversed, switch ASC and DESC.

If grouped queries error, place ORDER BY after GROUP BY.

If ties look random, add a second sorting column.

If the query slows down, sort fewer rows or add indexes.

Quick recap

  • Use ORDER BY to sort results
  • Ascending is default
  • Use DESC for highest/newest first
  • Add multiple columns for tie-breakers
  • Place it after grouping logic