In SQL, the ORDER BY, LIMIT, and OFFSET clauses are used to sort, limit, and paginate the result set, respectively. They provide powerful ways to manage the presentation of data in your queries.
The ORDER BY clause is used to sort the result set by one or more columns, either in ascending (ASC) or descending (DESC) order. By default, it sorts in ascending order if no direction is specified.
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
SELECT FirstName, LastName, Salary
FROM Employees
ORDER BY Salary ASC;
This query retrieves employee names and their salaries and orders the result by salary in ascending order.
SELECT FirstName, LastName, Salary
FROM Employees
ORDER BY DepartmentID ASC, Salary DESC;
In this query, the result is first sorted by DepartmentID in ascending order, and then within each department, employees are sorted by salary in descending order.
The LIMIT clause is used to limit the number of rows returned by the query. This is especially useful when you are only interested in retrieving a subset of the total result.
SELECT column1, column2, ...
FROM table_name
LIMIT number_of_rows;
SELECT FirstName, LastName, Salary
FROM Employees
ORDER BY Salary DESC
LIMIT 5;
This query retrieves the top 5 employees with the highest salaries.
The OFFSET clause allows you to skip a certain number of rows before returning the result. It is commonly used in conjunction with LIMIT to paginate results.
SELECT column1, column2, ...
FROM table_name
LIMIT number_of_rows OFFSET number_of_rows_to_skip;
SELECT FirstName, LastName, Salary
FROM Employees
ORDER BY Salary DESC
LIMIT 5 OFFSET 10;
This query retrieves 5 employees, starting from the 11th row (skipping the first 10 rows). This is useful for pagination where the user might want to see page 2 or beyond.