SQL FOUNDATIONS:Sorting & Limiting Results (ORDER BY, LIMIT)

Sort rows with ORDER BY and restrict output with LIMIT.

What is Sorting

Sorting allows you to arrange query results in a specific order using ORDER BY.

By default, SQL sorts data in ascending order (ASC).

Basic Syntax

sql
SELECT column1, column2
FROM table_name
ORDER BY column_name [ASC | DESC];
  • ASC → Ascending (smallest to largest)
  • DESC → Descending (largest to smallest)

Example Dataset

Table: employees

idnamedepartmentsalary
1JohnHR40000
2AliceIT60000
3BobIT55000
4EmmaFinance70000
5DavidHR45000

Sorting in Ascending Order

sql
SELECT * FROM employees
ORDER BY salary ASC;

Sorts employees from lowest to highest salary.

Sorting in Descending Order

sql
SELECT * FROM employees
ORDER BY salary DESC;

Sorts employees from highest to lowest salary.

Sorting by Multiple Columns

sql
SELECT * FROM employees
ORDER BY department ASC, salary DESC;
  • First sorts by department
  • Then sorts salary within each department

Limiting Results (LIMIT)

LIMIT is used to restrict the number of rows returned.

sql
SELECT * FROM employees
LIMIT 3;

Returns only the first 3 rows.

Combining ORDER BY with LIMIT

This is very common in interviews.

sql
SELECT * FROM employees
ORDER BY salary DESC
LIMIT 1;

Returns the employee with the highest salary.

Getting Top N Results

sql
SELECT name, salary FROM employees
ORDER BY salary DESC
LIMIT 3;

Returns top 3 highest-paid employees.

Key Concepts

  • ORDER BY controls result order
  • Default order is ascending
  • Use DESC for highest values first
  • LIMIT restricts number of rows
  • ORDER BY + LIMIT is used for top/bottom queries

Sorting & Limiting Results (ORDER BY, LIMIT) Missions

Solve exercises in sequence to unlock the next mission.

1

Sort by salary ASC

Retrieve all employees sorted by salary in ascending order.

Solve Mission
2

Sort by salary DESC

Retrieve all employees sorted by salary in descending order.

Locked
3

Names and salaries DESC

Retrieve names and salaries sorted by salary (highest first).

Locked
4

Sort by department

Retrieve all employees sorted by department (A–Z).

Locked
5

Department then salary DESC

Retrieve all employees sorted by department, then salary descending.

Locked
6

Top 2 highest-paid

Retrieve the top 2 highest-paid employees.

Locked
7

Lowest salary

Retrieve the employee with the lowest salary.

Locked
8

First 3 by salary ASC

Retrieve first 3 employees sorted by salary ascending.

Locked
9

Top 3 names

Retrieve names of top 3 highest-paid employees.

Locked
10

Second highest salary

Retrieve the second highest salary.

Locked