When working with databases, the data retrieved using the SELECT statement is not always in the order we want. In real-world scenarios such as salary reports, leaderboards, job listings, or dashboards, data must be displayed in a meaningful order and often in limited quantities. SQL provides two very important clauses for this purpose: ORDER BY for sorting results and LIMIT for restricting the number of rows returned.
The ORDER BY clause is used to sort the result set of a query based on one or more columns. Sorting can be done in ascending or descending order.
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary;
salary column.Ascending order means:
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC;
DESC sorts data in reverse order.SELECT first_name, last_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
department in ascending order.salary in descending order.The LIMIT clause is used to restrict the number of rows returned by a query. This is very useful when working with large datasets or when showing data page-by-page.
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5 OFFSET 5;
This technique is widely used in:
| Clause | Purpose |
|---|---|
| LIMIT | Number of rows to return |
| OFFSET | Number of rows to skip |