Order By Limit in SQL
ORDER BY with LIMIT in SQL
The ORDER BY clause sorts the result set, and the LIMIT clause restricts the number of rows returned. Together, they are often used to get the top N records based on a certain order.
? Syntax:
SELECT column1, column2, ...FROM table_nameORDER BY column_name [ASC | DESC]LIMIT number_of_rows;ORDER BYsorts the results.LIMITrestricts output to the specified number of rows.
? Example:
Get the top 5 highest paid employees:
SELECT employee_name, salaryFROM employeesORDER BY salary DESCLIMIT 5;This returns the 5 employees with the highest salaries.
Example with ascending order:
Get the 3 earliest events:
SELECT event_name, event_dateFROM eventsORDER BY event_date ASCLIMIT 3;Notes:
LIMITsyntax works in MySQL, PostgreSQL, SQLite.In SQL Server, use
TOPinstead:
SELECT TOP 5 employee_name, salaryFROM employeesORDER BY salary DESC;In Oracle, use
FETCH FIRSTsyntax (12c+):
SELECT employee_name, salaryFROM employeesORDER BY salary DESCFETCH FIRST 5 ROWS ONLY;Want me to show how to paginate results using ORDER BY and LIMIT?