Pathubs SQL Curriculum • Module 07

SQL ORDER BY & LIMIT

Master result set sorting and row limitation: learn ascending (ASC) and descending (DESC) sorting, multi-column tie-breaking, expressions sorting, and constructing reliable Top-N queries with ORDER BY + LIMIT.

⏱️ Estimated Time:45 Minutes
🎯 Level:Beginner
📊 Track:Data Analytics & SQL Mastery
✨ Mode:Interactive Sort & Slicing Lab
1

Introduction

In relational database theory, tables are treated as unordered mathematical sets. When you execute SELECT * FROM employees;, the database does not guarantee any specific row order. Rows might arrive in insertion order, disk storage order, or parallel worker order.

To control the order and volume of your output, SQL provides two fundamental clauses:

📊 ORDER BY

Controls the sort order (ascending or descending) of returned rows.

✂️ LIMIT

Controls the maximum number of rows returned in the result set.

2

What Is ORDER BY?

The ORDER BY clause sorts query results according to one or more specified columns:

SELECT *
FROM employees
ORDER BY salary;

This sorts all employees by salary from lowest to highest.

3

ASC — Ascending Order

ASC sorts data from lowest to highest (numbers), A to Z (text), or oldest to newest (dates).

Because ASC is the default direction in mainstream SQL engines (PostgreSQL, MySQL, SQLite, Oracle), both queries below produce identical results:

SELECT * FROM employees ORDER BY salary;
-- is 100% equivalent to:
SELECT * FROM employees ORDER BY salary ASC;
4

DESC — Descending Order

The DESC keyword reverses the sort direction, ordering results from highest to lowest:

-- Highest salary first:
SELECT name, salary
FROM employees
ORDER BY salary DESC;
Diagram 1: ORDER BY DESC Transformation
Unsorted Table Rows:
Amit (85k), Priya (48k), Vikram (92k), Rahul (62k)
➔ ORDER BY salary DESC ➔
Sorted Result:
1. Vikram (92k)
2. Amit (85k)
3. Rahul (62k)
4. Priya (48k)
5

Sorting Text and Dates

ORDER BY sorts text alphabetically and dates chronologically:

-- Alphabetical sorting (A to Z)
SELECT * FROM employees ORDER BY name ASC;

-- Newest orders first (Recent to Oldest)
SELECT * FROM orders ORDER BY order_date DESC;
ℹ️
Note on Text Sorting: Exact alphabetical order (such as case sensitivity and accent handling) depends on database collation and character set settings.
6

Sorting by Multiple Columns (Tie-Breaking)

You can separate multiple column sort expressions with commas:

SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;

How SQL executes this:

  1. First, all rows are grouped and sorted by department ASC (Engineering, HR, Sales).
  2. When two or more rows have the same department (a tie), SQL sorts those specific tied rows by salary DESC (highest earner in that department first).
Diagram 2: Multi-Column Tie-Breaking Logic
Primary Sort: Department ASC
[Engineering, Engineering, HR, Sales, Sales]
➔ Ties Found ➔
Secondary Sort on Ties: Salary DESC
Engineering: Vikram (92k) before Amit (85k)
7

Sorting by Expressions and Aliases

ORDER BY can sort by computed expressions or column aliases declared in the SELECT clause:

SELECT item_name, price * quantity AS total_amount
FROM order_items
ORDER BY total_amount DESC;
8

What Is LIMIT?

The LIMIT clause restricts the maximum number of rows returned in the final result set:

SELECT * FROM products LIMIT 5;

If the table contains 1,000 products, only 5 rows are sent back to your application, conserving memory and network bandwidth. If fewer than 5 rows exist, all matching rows are returned.

9

ORDER BY + LIMIT (The Top-N Pattern)

Combining ORDER BY and LIMITis the standard design pattern for answering "Top-N" or "Bottom-N" business questions:

-- Top 3 highest-earning employees in the company:
SELECT name, salary
FROM employees
ORDER BY salary DESC
LIMIT 3;
Diagram 3: The Top-N Evaluation Flow
All 1,000 Table Rows
➔ ORDER BY salary DESC ➔
1,000 Ranked Rows
#1 Highest ... #1000 Lowest
➔ LIMIT 3 ➔
Top 3 Rows Returned
10

Why LIMIT Without ORDER BY Can Be Misleading

Writing SELECT * FROM employees LIMIT 3; does notmean "Get the 3 highest earners" or "Get the 3 newest staff".

⚠️
Arbitrary Result Warning: Without an explicit ORDER BY, the database simply returns whatever 3 rows happen to be processed first. This result can change between database restarts or server queries! To guarantee deterministic, meaningful results, always pair LIMIT with ORDER BY.
11

LIMIT Combined With WHERE

You can filter subsets of rows before sorting and limiting:

-- Top 2 highest-paid employees specifically in Sales:
SELECT name, salary
FROM employees
WHERE department = 'Sales'
ORDER BY salary DESC
LIMIT 2;
12

Understanding Complete SQL Query Structure

ClauseSyntax OrderCore Purpose
SELECT1Specifies which columns/expressions to display in output
FROM2Specifies the source table(s) to read
WHERE3Filters which individual rows qualify
ORDER BY4Defines the sorting criteria and direction (ASC/DESC)
LIMIT5Slices the maximum row count of the sorted result
Live Interactive Sort & Limit Lab
⚙️ Dynamic Sorting & Slicing ControlsInteractive Knobs
LIMIT 5
📋 Output Result Set5 of 8 Rows Shown
# Ranknamedepartmentsalarycity
#1Vikram SinghEngineering92,000Delhi
#2Amit VermaEngineering85,000Bengaluru
#3Rohan JoshiSales71,000Bengaluru
#4Kavita NairEngineering68,000Mumbai
#5Rahul SharmaSales62,000Mumbai
✍️ Generated SQL Query● Live Sync
SELECT * FROM employees
ORDER BY salary DESC
LIMIT 5;
💡 What is happening in this query:
  • Rows are sorted by salary (DESC).
  • Only the top 5 sorted records are sliced off and returned.
13

Common ORDER BY & LIMIT Mistakes

1. Using LIMIT Without ORDER BY for Top-N Queries

SELECT * FROM sales LIMIT 5 does NOT give you the 5 best sales. Always write ORDER BY amount DESC LIMIT 5.

2. Forgetting that ORDER BY Does Not Alter Disk Tables

Running an ORDER BY query changes only the immediate response format, never the physical storage of data.

3. Putting LIMIT Before ORDER BY

Writing SELECT * FROM employees LIMIT 5 ORDER BY salary triggers a syntax error. LIMIT must always be placed at the very end of the query.

🧠 Interactive Challenge: Predict The Result (1 of 3)
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3;
Which employees will appear in the final output (in order)?
14

Practical Step-by-Step Exercises

Task GoalTarget TableRequired SQL SolutionPattern Used
1. Sort by Salary AscendingemployeesSELECT * FROM employees ORDER BY salary ASC;Basic ASC sort
2. Most Expensive Products FirstproductsSELECT * FROM products ORDER BY price DESC;Basic DESC sort
3. Top 5 Highest SalariesemployeesSELECT * FROM employees ORDER BY salary DESC LIMIT 5;Top-N pattern
4. Top 3 Newest OrdersordersSELECT * FROM orders ORDER BY order_date DESC LIMIT 3;Chronological Top-N
5. Multi-Column Tie-BreakeremployeesSELECT * FROM employees ORDER BY department ASC, salary DESC;Hierarchical sort
6. Top 3 Salaries in SalesemployeesSELECT * FROM employees WHERE department = 'Sales' ORDER BY salary DESC LIMIT 3;WHERE + ORDER BY + LIMIT
15

ORDER BY & LIMIT Best Practices

  • Always Specify Sort Direction Explicitly: While ASC is default, writing ASC or DESC makes intent obvious to team members.
  • Always Pair LIMIT with ORDER BY for Top-N: Never write bare LIMIT queries when looking for best/worst/recent items.
  • Index Frequently Sorted Columns: In high-scale databases, sorting millions of unindexed rows in memory causes performance lag. Indexes accelerate ORDER BY ... LIMIT queries drastically.
  • Keep Syntax Order Strict: Remember the sequence: SELECT ➔ FROM ➔ WHERE ➔ ORDER BY ➔ LIMIT.
16

What You Should Know Now

  • ORDER BY: Sorts query output
  • ASC: Low to high / A to Z (Default)
  • DESC: High to low / Z to A
  • Multiple Columns: Breaks ties hierarchically
  • LIMIT: Restricts total rows returned
  • Top-N Pattern: ORDER BY + LIMIT combined

🎯 Knowledge Check Quiz: SQL ORDER BY & LIMIT

Test your understanding of result set sorting, ascending vs descending directions, multi-column tie-breaking, and Top-N slicing.

1. What is the default sort direction in SQL when ORDER BY is used without specifying ASC or DESC?
2. Which keyword should you append to ORDER BY to sort rows from highest price to lowest price?
3. In a query with "ORDER BY city ASC, salary DESC", how does SQL evaluate the sorting?
4. What is the primary role of the LIMIT clause?
5. Why is "ORDER BY ... LIMIT N" the required pattern for Top-N analytical queries?
6. What is the syntactically correct order of clauses in a standard SQL SELECT statement?
7. Does running an "ORDER BY" query permanently change the physical row order inside the disk table?
8. Which query correctly retrieves the 2 newest orders placed in 2026?