SQL ORDER BY and LIMIT Explained
Level: intermediate · ~17 min read · Intent: informational
Audience: backend developers, data analysts, data engineers, technical teams, students, software engineers
Prerequisites
- basic familiarity with databases
- basic understanding of SELECT and WHERE
Key takeaways
- ORDER BY controls the order of rows in a query result, while LIMIT restricts how many rows are returned, and the two are most useful when used together deliberately.
- The most important practical rule is to never rely on database row order without ORDER BY, and to always define a stable sort when using LIMIT for top results or pagination.
FAQ
- What does ORDER BY do in SQL?
- ORDER BY sorts the rows returned by a query based on one or more columns, either ascending or descending.
- What does LIMIT do in SQL?
- LIMIT restricts the number of rows returned by a query, which is useful for top results, previews, and pagination.
- Should I use LIMIT without ORDER BY?
- Usually no. Without ORDER BY, the database is free to return rows in any order, so LIMIT may give inconsistent or unpredictable results.
- Can I sort by more than one column in SQL?
- Yes. You can use ORDER BY with multiple columns to control primary and secondary sorting, such as sorting by department and then by salary.
ORDER BY and LIMIT are two of the most common SQL clauses because they control two very practical things:
- the order of the result
- and how many rows are returned
That sounds simple, but these two clauses are responsible for a huge amount of everyday SQL work.
They are used for:
- showing the newest records first
- finding the highest salary
- listing the cheapest products
- getting the top 10 customers by revenue
- showing the most recent support tickets
- building dashboard tables
- returning the first page of an API response
- and previewing only a small number of rows during analysis
This is why ORDER BY and LIMIT matter so much.
Without ORDER BY, a result may not appear in the order you expect.
Without LIMIT, a query may return far more data than you actually need.
This guide explains SQL ORDER BY and LIMIT clearly, including:
- what each one does
- how ascending and descending sorting work
- how to sort by multiple columns
- how
ORDER BYandLIMITwork together - common mistakes
- pagination basics
- and practical performance considerations
Why ORDER BY and LIMIT matter
A lot of beginner SQL queries work without either clause.
For example:
SELECT *
FROM users;
This is valid SQL.
But in real applications and reporting, that is usually not enough.
You often need answers like:
- show the newest users first
- show the five most expensive products
- show the latest 20 orders
- show the top 10 results only
- show page 2 of a sorted list
That is where ORDER BY and LIMIT come in.
These clauses turn a raw result into a usable result.
That is why they appear in:
- admin panels
- dashboards
- analytics queries
- search results
- feeds
- and APIs
They are basic SQL tools, but they are also extremely practical.
The most important rule
Before anything else, remember this:
If the order of the result matters, you must use ORDER BY.
That is the single most important rule in this topic.
A lot of developers assume:
- the database will naturally return rows in insertion order
- or primary key order
- or the same order every time
That is not something you should rely on.
Without ORDER BY, the database is generally free to return rows in whatever order is most convenient for the execution plan.
That means:
- the same query may not return rows in the same order every time
- or the result order may change after indexing, growth, or engine changes
So if you care about order, define it explicitly.
What ORDER BY does
ORDER BY sorts the result of a query.
That means it tells SQL:
- in what order should the rows appear?
Basic example:
SELECT *
FROM products
ORDER BY price;
This sorts rows by price in ascending order by default.
That means:
- smaller prices first
- larger prices later
This is one of the most common SQL patterns.
What LIMIT does
LIMIT restricts how many rows are returned.
Basic example:
SELECT *
FROM products
LIMIT 5;
This means:
- return only 5 rows
Without ORDER BY, it just returns some 5 rows from the result.
With ORDER BY, it returns:
- the first 5 rows in the defined sorted order
That is why LIMIT is usually most useful together with ORDER BY.
ORDER BY ascending by default
In most SQL systems, ORDER BY column_name means ascending order unless you specify otherwise.
Example:
SELECT
product_name,
price
FROM products
ORDER BY price;
This is the same idea as:
SELECT
product_name,
price
FROM products
ORDER BY price ASC;
So:
ASCmeans ascending- and it is often the default
Ascending usually means:
- smaller to larger for numbers
- earlier to later for dates
- A to Z for text
ORDER BY DESC
If you want reverse order, use DESC.
Example:
SELECT
product_name,
price
FROM products
ORDER BY price DESC;
Now the most expensive products appear first.
This is very useful for:
- newest records first
- highest values first
- latest events first
- top revenue results
- best scores
- biggest totals
DESC is one of the most commonly used modifiers in SQL.
A simple example with salaries
Suppose you have this table:
| employee_name | salary |
|---|---|
| Alice | 60000 |
| Bob | 45000 |
| Cara | 80000 |
Ascending order
SELECT employee_name, salary
FROM employees
ORDER BY salary ASC;
Result:
| employee_name | salary |
|---|---|
| Bob | 45000 |
| Alice | 60000 |
| Cara | 80000 |
Descending order
SELECT employee_name, salary
FROM employees
ORDER BY salary DESC;
Result:
| employee_name | salary |
|---|---|
| Cara | 80000 |
| Alice | 60000 |
| Bob | 45000 |
This is the simplest way to understand sorting direction.
ORDER BY with dates
Sorting by dates is one of the most common real-world uses.
Example:
SELECT
order_id,
created_at
FROM orders
ORDER BY created_at DESC;
This usually means:
- newest orders first
Or:
SELECT
invoice_id,
due_date
FROM invoices
ORDER BY due_date ASC;
This usually means:
- earliest due invoices first
That is why ORDER BY is so important in:
- admin tables
- financial systems
- logs
- reporting
- and user-facing feeds
ORDER BY with text
You can also sort text columns.
Example:
SELECT
customer_name
FROM customers
ORDER BY customer_name ASC;
This sorts names alphabetically.
That is useful for:
- customer lists
- category lists
- location lists
- and alphabetical dropdowns
Text sorting is very common in dashboards and back-office screens.
ORDER BY multiple columns
You are not limited to one column.
You can sort by multiple columns in order of priority.
Example:
SELECT
department,
employee_name,
salary
FROM employees
ORDER BY department ASC, salary DESC;
This means:
- sort by department A to Z
- inside each department, sort by salary highest to lowest
This is extremely useful.
It lets you define:
- primary sort
- secondary sort
- tertiary sort if needed
That is how you make ordering more precise.
Why multiple-column sorting matters
Suppose many rows share the same value in the first sort column.
Example: many employees may belong to the same department.
If you sort only by department:
ORDER BY department
then employees within the same department may appear in any relative order unless another sort is specified.
If you instead write:
ORDER BY department, salary DESC
then the order becomes much more meaningful.
This is very useful for:
- grouped rankings
- stable reporting
- dashboard sorting
- and tie handling
Practical example with multiple columns
Suppose you have:
| department | employee_name | salary |
|---|---|---|
| Finance | Alice | 60000 |
| Finance | Bob | 55000 |
| Marketing | Cara | 70000 |
| Marketing | Dan | 50000 |
Query:
SELECT
department,
employee_name,
salary
FROM employees
ORDER BY department ASC, salary DESC;
Result:
| department | employee_name | salary |
|---|---|---|
| Finance | Alice | 60000 |
| Finance | Bob | 55000 |
| Marketing | Cara | 70000 |
| Marketing | Dan | 50000 |
This is a great example of primary and secondary ordering.
LIMIT without ORDER BY
You can write:
SELECT *
FROM orders
LIMIT 10;
This is valid.
But it is often not what you really want, because:
- it returns 10 rows
- but not necessarily the newest 10
- not necessarily the smallest 10
- not necessarily the first 10 by any meaningful business rule
So while LIMIT works without ORDER BY, it is often not logically strong enough on its own.
That is why the best practical rule is:
Use LIMIT without ORDER BY only when you truly do not care which rows are returned.
ORDER BY with LIMIT: the most useful combination
This is one of the most common SQL patterns.
Example:
SELECT
product_name,
price
FROM products
ORDER BY price DESC
LIMIT 5;
This means:
- sort products from highest price to lowest
- return only the first 5 rows
So the result is:
- the 5 most expensive products
That is the real power of using these clauses together.
Top-N queries
Queries like:
- top 5 products
- latest 10 users
- highest 3 salaries
- newest 20 tickets
are often called top-N queries.
The basic pattern is:
SELECT ...
FROM ...
ORDER BY some_column DESC
LIMIT N;
Examples:
Top 10 highest salaries
SELECT
employee_name,
salary
FROM employees
ORDER BY salary DESC
LIMIT 10;
Latest 20 orders
SELECT
order_id,
created_at
FROM orders
ORDER BY created_at DESC
LIMIT 20;
Cheapest 5 products
SELECT
product_name,
price
FROM products
ORDER BY price ASC
LIMIT 5;
These are some of the most practical SQL query patterns.
LIMIT with OFFSET
A lot of SQL systems also support OFFSET, which is commonly used with LIMIT for pagination.
Example:
SELECT
order_id,
created_at
FROM orders
ORDER BY created_at DESC
LIMIT 10 OFFSET 20;
This means:
- sort rows first
- skip the first 20
- return the next 10
This is often used for page-based APIs or dashboards.
For example:
- page 1 might use
LIMIT 10 OFFSET 0 - page 2 might use
LIMIT 10 OFFSET 10 - page 3 might use
LIMIT 10 OFFSET 20
This is one of the most common pagination patterns.
Why ORDER BY matters even more with pagination
If you paginate without ORDER BY, the result can become inconsistent.
Example:
SELECT *
FROM orders
LIMIT 10 OFFSET 10;
This may give you:
- arbitrary rows
- or rows that shift unpredictably as data changes
That is why pagination should almost always include a stable sort.
Better:
SELECT
order_id,
created_at
FROM orders
ORDER BY created_at DESC, order_id DESC
LIMIT 10 OFFSET 10;
This gives a much more stable and meaningful result.
Stable ordering matters
Suppose many rows have the same created_at value.
If you order only by:
ORDER BY created_at DESC
then rows with identical timestamps may not have a consistent relative order.
A stronger pattern is:
ORDER BY created_at DESC, order_id DESC
This adds a tie-breaker.
That is very important for:
- pagination
- latest records
- top-N lists
- and deterministic outputs
A stable sort helps make query results predictable.
Why tie-breakers are important
Imagine two support tickets were created at the same second.
If you sort only by created_at, their relative order may not be reliable.
But if you sort by:
created_at DESC- then
ticket_id DESC
you create a deterministic sequence.
This matters more than many beginners realize, especially in:
- APIs
- cursor pagination
- reporting
- and recent-activity lists
ORDER BY after GROUP BY
ORDER BY is often used after grouped queries.
Example:
SELECT
country,
COUNT(*) AS user_count
FROM users
GROUP BY country
ORDER BY user_count DESC;
This means:
- group users by country
- count them
- then sort countries from largest user count to smallest
This is a very common reporting pattern.
It is useful for:
- ranking groups
- top categories
- revenue by month
- biggest departments
- highest-selling products
ORDER BY by selected alias
In many SQL systems, you can order by an alias defined in the SELECT list.
Example:
SELECT
country,
COUNT(*) AS user_count
FROM users
GROUP BY country
ORDER BY user_count DESC;
This is very readable.
Instead of repeating the aggregate expression, you can sort by the alias.
This makes queries simpler to understand.
ORDER BY by column position
Some SQL systems allow:
SELECT
country,
COUNT(*) AS user_count
FROM users
GROUP BY country
ORDER BY 2 DESC;
This means:
- sort by the second selected column
It can work, but it is usually less readable than sorting by the actual name or alias.
For maintainability, this is usually clearer:
ORDER BY user_count DESC
That is the better habit in most codebases.
LIMIT in development and analysis
LIMIT is also very useful when:
- previewing a table
- testing a query
- checking result shape
- or exploring data
Example:
SELECT *
FROM users
LIMIT 20;
This is a common analyst and developer habit because it avoids loading the full table unnecessarily while you inspect the data.
So LIMIT is not only for production queries.
It is also very useful during development and debugging.
Common mistakes with ORDER BY and LIMIT
There are a few mistakes that show up often.
1. Relying on natural row order
This is one of the biggest ones.
Bad assumption:
- the database will return rows in insertion order
Better rule:
- if order matters, use
ORDER BY
2. Using LIMIT without ORDER BY for top results
If the question is:
- newest 10 users
- highest 5 salaries
then LIMIT alone is not enough.
You need ORDER BY.
3. Forgetting tie-breakers
If multiple rows share the same sort value, the result may not be stable without a secondary sort column.
4. Sorting by the wrong direction
Example:
using ASC when you meant latest first or highest first.
5. Using OFFSET pagination on very deep pages without thinking about performance
This is more advanced, but it matters in larger systems.
Performance considerations
ORDER BY can require the database to sort rows, which can be expensive if:
- many rows are involved
- the rows are wide
- no useful index supports the sort
- or the result needs large offsets
That does not mean you should avoid ORDER BY.
It means you should be aware that sorting is real work.
Queries often perform better when:
- the filtered result is smaller
- the sort matches a useful index
- or the query shape is designed around the access pattern
This matters especially in:
- list endpoints
- admin dashboards
- feeds
- and large tables
ORDER BY and indexes
Indexes can sometimes help with sorting, especially when the query filters and orders in a compatible way.
Example:
SELECT
order_id,
created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;
If the database has a suitable index shaped for:
customer_id- and
created_at
this query may be much more efficient.
That is why sorting performance is often tied to indexing strategy.
LIMIT and large OFFSET values
Offset pagination is easy to write, but it can become less efficient for deep pages.
Example:
LIMIT 20 OFFSET 100000
The database may still need to work through a large number of rows before returning the final page.
That is why large-scale systems often move toward:
- keyset pagination
- or cursor-based pagination
Still, for many ordinary admin screens and smaller datasets, LIMIT and OFFSET are perfectly fine and easy to use.
A practical mindset for ORDER BY and LIMIT
A very useful way to think about these clauses is:
ORDER BY
What is the exact order I want the rows in?
LIMIT
How many rows do I actually need?
This makes query writing much clearer.
For example:
- newest 20 orders
- highest 10 scores
- cheapest 5 products
- first 50 customers alphabetically
That kind of thinking helps you choose the right sort column, direction, and row limit.
Practical examples
Example 1: newest users first
SELECT
user_id,
email,
created_at
FROM users
ORDER BY created_at DESC
LIMIT 20;
Example 2: cheapest products
SELECT
product_name,
price
FROM products
ORDER BY price ASC
LIMIT 10;
Example 3: employees sorted by department, then name
SELECT
department,
employee_name
FROM employees
ORDER BY department ASC, employee_name ASC;
Example 4: countries ranked by customer count
SELECT
country,
COUNT(*) AS customer_count
FROM customers
GROUP BY country
ORDER BY customer_count DESC;
Example 5: second page of recent orders
SELECT
order_id,
created_at,
total_amount
FROM orders
ORDER BY created_at DESC, order_id DESC
LIMIT 20 OFFSET 20;
These are all realistic uses of ORDER BY and LIMIT.
FAQ
What does ORDER BY do in SQL?
ORDER BY sorts the rows returned by a query based on one or more columns, either ascending or descending.
What does LIMIT do in SQL?
LIMIT restricts the number of rows returned by a query, which is useful for top results, previews, and pagination.
Should I use LIMIT without ORDER BY?
Usually no. Without ORDER BY, the database is free to return rows in any order, so LIMIT may give inconsistent or unpredictable results.
Can I sort by more than one column in SQL?
Yes. You can use ORDER BY with multiple columns to control primary and secondary sorting, such as sorting by department and then by salary.
Final thoughts
ORDER BY and LIMIT are simple clauses, but they are some of the most useful tools in SQL because they turn raw results into ordered, usable, focused outputs.
The most important ideas to remember are:
ORDER BYcontrols result orderASCmeans ascendingDESCmeans descendingLIMITrestricts the number of returned rowsORDER BYandLIMITare especially powerful together- multi-column ordering gives more control
- tie-breakers make sorting more stable
- and if order matters, never rely on the database without explicitly defining it
If you understand those ideas clearly, a huge number of everyday SQL tasks become easier, especially in reporting, application development, debugging, and pagination-heavy systems.