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
sqlSELECT column1, column2FROM table_nameORDER BY column_name [ASC | DESC];
ASC→ Ascending (smallest to largest)DESC→ Descending (largest to smallest)
Example Dataset
Table: employees
Sorting in Ascending Order
sqlSELECT * FROM employeesORDER BY salary ASC;
Sorts employees from lowest to highest salary.
Sorting in Descending Order
sqlSELECT * FROM employeesORDER BY salary DESC;
Sorts employees from highest to lowest salary.
Sorting by Multiple Columns
sqlSELECT * FROM employeesORDER 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.
sqlSELECT * FROM employeesLIMIT 3;
Returns only the first 3 rows.
Combining ORDER BY with LIMIT
This is very common in interviews.
sqlSELECT * FROM employeesORDER BY salary DESCLIMIT 1;
Returns the employee with the highest salary.
Getting Top N Results
sqlSELECT name, salary FROM employeesORDER BY salary DESCLIMIT 3;
Returns top 3 highest-paid employees.
Key Concepts
ORDER BYcontrols result order- Default order is ascending
- Use
DESCfor highest values first LIMITrestricts number of rowsORDER BY + LIMITis used for top/bottom queries
Sorting & Limiting Results (ORDER BY, LIMIT) Missions
Solve exercises in sequence to unlock the next mission.
Sort by salary DESC
Retrieve all employees sorted by salary in descending order.
Names and salaries DESC
Retrieve names and salaries sorted by salary (highest first).
Sort by department
Retrieve all employees sorted by department (A–Z).
Department then salary DESC
Retrieve all employees sorted by department, then salary descending.
Top 2 highest-paid
Retrieve the top 2 highest-paid employees.
Lowest salary
Retrieve the employee with the lowest salary.
First 3 by salary ASC
Retrieve first 3 employees sorted by salary ascending.
Top 3 names
Retrieve names of top 3 highest-paid employees.
Second highest salary
Retrieve the second highest salary.