Conceito introdutório

~5 min de leitura

ORDER BY — Sorting Results

Learn how to sort query results in ascending or descending order for better data presentation.

Iniciante

What is ORDER BY?

The ORDER BY clause lets you sort query results based on one or more columns. Without it, rows are returned in an unpredictable order.

Think of it like sorting products on Amazon by price or rating. ORDER BY does the same for your database queries, making data easier to analyze and present.

Basic Syntax

SQL Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column_name [ASC|DESC];

💡 Pro Tip: ORDER BY is the last clause in a SELECT statement (after WHERE and GROUP BY). ASC (ascending) is the default and can be omitted.

Common Patterns

Sort results from lowest to highest (default)

SQL Query
SELECT name, age 
FROM customers 
ORDER BY age ASC;

Result: Shows youngest customers first (18, 25, 30, 45...)

See Sorting In Action

Watch how ORDER BY transforms data! See the before and after states to understand how sorting works.

Sort by Name (A-Z)

Alphabetical ordering

1

Input Data

customers
idINTEGER
nameTEXT
emailTEXT
countryTEXT
ageINTEGER
1Alice Johnson[email protected]USA28
2Bob Smith[email protected]Canada35
3Carlos Silva[email protected]Brazil22
4Diana Chen[email protected]USA41
5Emma Davis[email protected]Canada19
5 rows displayed
2

SQL Query

SQL
SELECT name, country
FROM customers
ORDER BY name ASC
3

Result

5 rows
result
nameTEXT
countryTEXT
Alice JohnsonUSA
Bob SmithCanada
Carlos SilvaBrazil
Diana ChenUSA
Emma DavisCanada
5 rows displayed

Key Concepts

ASC

Ascending Order

Sorts from smallest to largest (A→Z, 0→9, oldest→newest).

ORDER BY price ASC

This is the default - you can omit ASC

DESC

Descending Order

Sorts from largest to smallest (Z→A, 9→0, newest→oldest).

ORDER BY price DESC

Must explicitly specify DESC

1,2

Multiple Columns

Sort by first column, then use second column to break ties.

ORDER BY country, age DESC

Can mix ASC and DESC

NULL

NULL Handling

NULL values typically appear last in ASC, first in DESC.

ORDER BY last_login DESC

Behavior varies by database

Sorting Different Data Types

123

Numbers

Sorted numerically: 1, 2, 10, 20, 100 (not alphabetically)

SELECT * FROM products ORDER BY price DESC;
ABC

Text (Strings)

Sorted alphabetically. Case-sensitivity depends on database settings.

SELECT * FROM customers ORDER BY name ASC;
📅

Dates & Times

Sorted chronologically. Older dates come first in ASC.

SELECT * FROM orders ORDER BY order_date DESC; -- Most recent first
✓/✗

Booleans

False (0) before True (1) in ASC order.

SELECT * FROM tasks ORDER BY completed ASC; -- Incomplete tasks first

Common Mistakes to Avoid

❌ Ordering by column not in SELECT

SELECT name FROM customers ORDER BY age;

While often allowed, it's confusing. Better to include it: SELECT name, age FROM customers ORDER BY age

❌ Forgetting DESC for reverse order

SELECT * FROM products ORDER BY price; -- Shows cheapest first!

Default is ASC. For expensive-first: ORDER BY price DESC

❌ Wrong order in multi-column sort

ORDER BY age, country -- Groups by age, then country

Order matters! For country grouping: ORDER BY country, age

❌ Using ORDER BY before WHERE

SELECT * FROM customers ORDER BY age WHERE country = 'USA';

Wrong clause order! Correct: WHERE country = 'USA' ORDER BY age

✅ Correct multi-column sort with mixed directions

SELECT name, country, age FROM customers WHERE age >= 18 ORDER BY country ASC, age DESC;

Perfect! Groups by country alphabetically, oldest first within each.

Pratique a seguirComeçar os desafios →