Skip to main content

How do you combine ORDER BY and LIMIT?

ORDER BY and LIMIT are often used together to get only the needed number of rows after sorting.

Syntax

sql
SELECT * FROM table_name ORDER BY column_name [ASC|DESC] LIMIT count;

Example 1: top 5 by salary

sql
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 5;

SQL first sorts all employees by salary, from largest to smallest, then returns only the first 5 rows (the top 5 highest salaries).

Example 2: earliest dates

sql
SELECT event_name, date FROM events ORDER BY date ASC LIMIT 10;

Returns the 10 earliest events.

Example 3: together with OFFSET

To skip the first rows and take the next ones:

sql
SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 5 OFFSET 5;

Skips the first 5 and returns the next 5, useful for pagination.

Summary:

  • ORDER BY sets the order,
  • LIMIT restricts the row count,
  • together they let you get, for example, the top N records or the first results from a sorted list.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.