Course contentsShow
← Data Science
Lesson 875 of 2,14522. SQL FoundationsFree lesson

ORDER BY Basics: Sorting Query Results

Master the ORDER BY clause to sort results in ascending or descending order by one or more columns.

ORDER BY Basics: Sorting Query Results

What you'll learn: How to organize your query results in a specific order using the ORDER BY clause.

Why Sorting Matters

When you retrieve data with SELECT, rows come back in no guaranteed order—like pulling random cards from a shuffled deck. The ORDER BY clause lets you arrange results in a meaningful sequence, making patterns easier to spot and reports more readable.

The Core Syntax

Place ORDER BY at the end of your query, after WHERE (if present):

SELECT column1, column2
FROM table_name
ORDER BY column1;

This sorts results by column1 in ascending order (A to Z, 0 to 9, oldest to newest) by default.

Ascending vs. Descending

Specify the sort direction explicitly:

-- Ascending (default, lowest to highest)
SELECT product_name, price
FROM products
ORDER BY price ASC;

-- Descending (highest to lowest)
SELECT product_name, price
FROM products
ORDER BY price DESC;

Sorting by Multiple Columns

You can sort by several columns—each with its own direction. SQL applies them left-to-right as tiebreakers:

SELECT customer_name, order_date, total
FROM orders
ORDER BY order_date DESC, total DESC;

This sorts by date first (newest first), then by total amount (highest first) when dates match.

Practical Tips

  • You can order by columns not in your SELECT list
  • Text sorts alphabetically (watch for case sensitivity)
  • NULL values typically appear first in ASC, last in DESC

Key Takeaway: ORDER BY transforms unordered query results into sorted, meaningful sequences—use ASC for ascending (default) or DESC for descending, and chain multiple columns for sophisticated sorting logic.