ORDER BY, LIMIT & Sorting Data
1. What is ORDER BY?
The ORDER BY clause is used to sort the result set.
- Default sorting → Ascending (ASC)
- Can sort by one or multiple columns
2. ORDER BY Syntax
SELECT column1, column2
FROM table_name
ORDER BY column_name [ASC | DESC];
3. Sorting in Ascending Order (ASC)
SELECT emp_name, salary
FROM employees
ORDER BY salary;
Same as:
ORDER BY salary ASC;
4. Sorting in Descending Order (DESC)
SELECT emp_name, salary
FROM employees
ORDER BY salary DESC;
5. Sorting by Multiple Columns
SELECT emp_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
6. ORDER BY with WHERE
SELECT emp_name, salary
FROM employees
WHERE department = 'IT'
ORDER BY salary DESC;
7. LIMIT Clause
Used to restrict number of rows returned.
SELECT * FROM employees
LIMIT 5;
8. LIMIT with OFFSET
Used for pagination.
SELECT * FROM employees
LIMIT 5 OFFSET 5;
9. LIMIT with ORDER BY (Most Important)
Used to find Top / Bottom records.
Top 3 highest salaries:
SELECT emp_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 3;
Lowest salary:
SELECT emp_name, salary
FROM employees
ORDER BY salary ASC
LIMIT 1;
10. Using Column Position in ORDER BY
SELECT emp_name, salary
FROM employees
ORDER BY 2 DESC;
Top comments (0)