Ctrl + K
SQL17 min read

SQL ORDER BY Explained

Learn how to sort SQL query results with ORDER BY, ASC, DESC, multiple columns, expressions, and conditional sorting.

Published: 2026-10-05

SQL ORDER BY is used to control the order of rows returned by a query. Without ORDER BY, a database generally does not guarantee a particular result order, even if the rows appear to be sorted in a specific way during testing. ORDER BY lets you explicitly sort results by one or more columns or expressions.

You can use ORDER BY to sort names alphabetically, prices from lowest to highest, dates from newest to oldest, scores from highest to lowest, or grouped results by an aggregate such as COUNT() or SUM(). Understanding ORDER BY is essential for reports, search results, dashboards, pagination, and almost any SQL query where result order matters.

What Does ORDER BY Do in SQL?

The ORDER BY clause tells the database how to sort the rows in the final query result. You specify one or more columns or expressions and optionally choose the direction of the sort.

SELECT name, age
FROM users
ORDER BY age;

When no direction is specified, ASC is normally used, meaning ascending order. For numbers, ascending order goes from smaller values to larger values. For text, it generally follows the database's collation rules.

You can explicitly write ASC even though it is the default.

SELECT name, age
FROM users
ORDER BY age ASC;

Basic ORDER BY Syntax

The basic syntax places ORDER BY after the other clauses that define and filter the result. A common query structure is SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, and then an optional LIMIT or OFFSET depending on the SQL dialect.

SELECT column1, column2
FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING group_condition
ORDER BY column1 ASC
LIMIT 20;

Not every query needs all of these clauses. ORDER BY can be used with a simple SELECT query or together with filtering, grouping, joins, aggregation, pagination, and other SQL features.

ASC: Ascending Order

ASC specifies ascending order. It is the default sorting direction in most SQL implementations, so ORDER BY price and ORDER BY price ASC normally produce the same ordering.

SELECT product_name, price
FROM products
ORDER BY price ASC;

For numeric values, the smallest values appear first. For dates, earlier dates generally appear first. For text, the exact ordering depends on the database's collation and comparison rules.

DESC: Descending Order

DESC specifies descending order. It reverses the normal ascending direction.

SELECT product_name, price
FROM products
ORDER BY price DESC;

This query places the most expensive products first. DESC is especially common when displaying newest records, highest scores, largest totals, or most expensive items.

Sorting by Text

ORDER BY can sort text columns as well as numeric columns. For example, you can sort users by their names.

SELECT first_name, last_name
FROM users
ORDER BY last_name ASC;

The exact ordering of text can depend on the database's collation. Case sensitivity, accents, locale-specific rules, and character ordering can therefore affect the result.

⚠️ Do not assume that alphabetical ordering is identical across every database or configuration. If sorting behavior for international text is important, check the collation rules used by your database.

Sorting by Dates

Dates can be sorted chronologically using ORDER BY. Ascending order returns earlier dates first, while descending order returns later dates first.

SELECT title, published_at
FROM articles
ORDER BY published_at DESC;

This is a common pattern for displaying the newest articles first. The same approach can be used for orders, events, log entries, messages, and other time-based records.

Sorting by Multiple Columns

ORDER BY can contain multiple columns. SQL sorts by the first expression first and uses the following expressions to break ties when rows have the same value for the earlier expression.

SELECT first_name, last_name, age
FROM users
ORDER BY last_name ASC, first_name ASC;

The result is primarily sorted by last name. If several users have the same last name, their first names determine the order within that group.

Each sorting expression can have its own direction.

SELECT product_name, category, price
FROM products
ORDER BY category ASC, price DESC;

Here, categories are sorted alphabetically, and products inside each category are sorted from the highest price to the lowest price.

How Multiple ORDER BY Columns Work

The order of expressions in ORDER BY matters. SQL evaluates the first sorting expression as the primary ordering rule, then applies the second expression only when the first values are equal.

ORDER BY expressionPrimary sortTie-breaker
last_name ASC, first_name ASCLast nameFirst name
category ASC, price DESCCategoryPrice, highest first
score DESC, name ASCScore, highest firstName

Adding more columns makes the ordering more deterministic when earlier columns contain duplicate values.

ORDER BY and SELECT

In many SQL systems, ORDER BY can reference a column that is not included in the SELECT list when querying ordinary tables.

SELECT name
FROM users
ORDER BY created_at DESC;

The query returns only name, but the rows are ordered using created_at. Rules can differ in more complex queries, especially when DISTINCT, set operations, or database-specific features are involved, so check the SQL dialect when necessary.

ORDER BY Column Aliases

An alias defined in SELECT can often be used in ORDER BY. This is particularly convenient when sorting by a calculated expression.

SELECT
  product_name,
  quantity * price AS total
FROM order_items
ORDER BY total DESC;

The alias total represents the calculated value and can be used to sort the final result in many SQL dialects.

ORDER BY Expressions

Instead of sorting by a simple column, you can sort by an expression. This is useful when the desired order depends on a calculated value.

SELECT product_name, price, discount
FROM products
ORDER BY price - discount DESC;

The rows are ordered by the calculated value of price minus discount. Expressions can be useful for computed scores, totals, dates, string transformations, and other derived values.

ORDER BY with CASE

CASE can be used to create a custom sorting priority. This is useful when the desired order does not follow normal alphabetical or numeric ordering.

SELECT title, status
FROM tasks
ORDER BY CASE status
  WHEN 'urgent' THEN 1
  WHEN 'in_progress' THEN 2
  WHEN 'pending' THEN 3
  WHEN 'completed' THEN 4
  ELSE 5
END;

This creates a custom priority order instead of sorting the status values alphabetically. CASE-based sorting is useful for statuses, priorities, categories, and other business-specific ordering rules.

ORDER BY and NULL Values

NULL values require special attention when sorting. The position of NULL values can differ between database systems and between ascending and descending sorts.

For example, one database may place NULL values before non-NULL values in ascending order, while another may place them after non-NULL values. Some SQL dialects also provide NULLS FIRST and NULLS LAST to explicitly control this behavior.

SELECT name, score
FROM users
ORDER BY score DESC NULLS LAST;

When supported by the database, NULLS LAST makes the intended behavior explicit. If your database does not support this syntax, you may need an expression such as CASE to control the placement of NULL values.

ORDER BY with WHERE

WHERE filters rows, while ORDER BY sorts the resulting rows. They are often used together.

SELECT name, salary
FROM employees
WHERE department = 'Engineering'
ORDER BY salary DESC;

The query first restricts the result to employees in the Engineering department and then sorts those employees by salary from highest to lowest.

ORDER BY with GROUP BY

ORDER BY is especially useful after GROUP BY because grouped queries often produce summary values that need to be sorted.

SELECT category,
       COUNT(*) AS product_count
FROM products
GROUP BY category
ORDER BY product_count DESC;

The query creates one result row per category, counts the products in each category, and then sorts the grouped results from the largest count to the smallest.

You can also sort by SUM(), AVG(), MIN(), MAX(), or another aggregate expression.

SELECT customer_id,
       SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
ORDER BY total_spent DESC;

ORDER BY with HAVING

HAVING filters grouped results, while ORDER BY controls their final order. Both clauses can be used in the same query.

SELECT customer_id,
       COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 5
ORDER BY order_count DESC;

Only customers with at least five orders remain after HAVING. ORDER BY then places the customers with the most orders first.

ORDER BY with LIMIT

ORDER BY and LIMIT are frequently combined to retrieve the first N rows according to a particular ordering.

SELECT product_name, price
FROM products
ORDER BY price DESC
LIMIT 10;

This pattern requests the ten most expensive products. The exact syntax for limiting rows differs between SQL dialects, but the general idea is widely supported.

⚠️ When using LIMIT for top-N queries, include ORDER BY if the selected rows need to have a defined meaning. LIMIT by itself does not guarantee which rows will be returned.

ORDER BY and Pagination

Pagination often combines ORDER BY with LIMIT and OFFSET. A stable ordering is important because the application needs a consistent way to determine which records belong to each page.

SELECT id, title, created_at
FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 40;

The second sorting column can act as a tie-breaker. If several rows have the same created_at value, id provides an additional ordering rule.

For large datasets, OFFSET-based pagination can become less efficient as the offset grows. Cursor-based or keyset pagination is often considered for high-volume applications, using an ordered column or combination of columns as the position marker.

Why ORDER BY Does Not Guarantee Permanent Table Order

A database table should not be treated as an inherently ordered list. Rows can be physically stored, accessed, or returned in different ways depending on indexes, query plans, database operations, and other factors.

If your application requires a particular result order, specify it explicitly with ORDER BY. An apparent order observed during development is not a reliable substitute for an ORDER BY clause.

ORDER BY and Indexes

Indexes can sometimes help a database retrieve rows in a required order without performing a separate sorting operation, but the exact behavior depends on the database engine, index definition, query conditions, and execution plan.

For example, an index on a frequently filtered or sorted column may be useful for certain queries. However, adding indexes solely because a column appears in ORDER BY is not always beneficial. Indexes also consume storage and can increase the cost of writes and maintenance.

When ORDER BY becomes a performance bottleneck, inspect the query execution plan and evaluate the actual access path used by the database.

ORDER BY with JOIN

ORDER BY can sort results produced by a query that joins multiple tables. It is often useful when the selected result combines information from related entities.

SELECT
  customers.name,
  orders.amount,
  orders.created_at
FROM customers
JOIN orders
  ON orders.customer_id = customers.id
ORDER BY orders.created_at DESC;

The result contains information from both tables and is sorted by the order creation date, with the newest orders first.

Using table aliases can make ORDER BY expressions easier to read when several tables contain columns with similar names.

SELECT
  c.name,
  o.amount
FROM customers AS c
JOIN orders AS o
  ON o.customer_id = c.id
ORDER BY o.amount DESC;

Sorting by Column Position

Some SQL dialects allow ORDER BY to reference the position of a selected column instead of its name.

SELECT name, age, created_at
FROM users
ORDER BY 2 DESC;

Here, 2 refers to the second expression in the SELECT list, which is age. Although positional ordering can be concise, using explicit column names or aliases is often easier to understand and maintain.

Common ORDER BY Mistakes

Forgetting the Sort Direction

A frequent mistake is using ASC when DESC is required or vice versa. If you need the newest records first, for example, a date normally needs descending order.

SELECT title, created_at
FROM posts
ORDER BY created_at DESC;

Assuming Rows Have a Default Order

Another mistake is relying on the order in which rows happen to be returned. Without ORDER BY, the database is generally free to return rows in an order that is not guaranteed by the SQL query.

Using LIMIT Without ORDER BY

LIMIT restricts the number of returned rows, but without ORDER BY it does not define which rows are selected as the first rows.

SELECT *
FROM products
LIMIT 10;

If the application needs the ten newest, cheapest, most expensive, or otherwise specific records, define that ordering explicitly.

Sorting by the Wrong Column

A query can be syntactically valid but still produce the wrong business result if ORDER BY uses an incorrect column. For example, sorting by updated_at instead of created_at changes the meaning of 'newest' records.

Using Too Many Sorting Expressions

Multiple ORDER BY columns are useful, but unnecessary expressions can make the query harder to understand. Add tie-breakers when they provide a meaningful deterministic order rather than adding arbitrary columns.

Ignoring NULL Ordering

If a sorted column can contain NULL values, verify where those rows should appear. Database-specific NULL ordering can otherwise produce results that differ from what the application expects.

ORDER BY Query Evaluation

A simplified conceptual processing order helps explain where ORDER BY fits into a SQL query.

  • FROM and JOIN determine the source row set.
  • WHERE filters individual rows.
  • GROUP BY creates groups when grouping is requested.
  • Aggregate functions calculate group-level values.
  • HAVING filters grouped results.
  • SELECT defines the returned expressions.
  • ORDER BY sorts the resulting rows.
  • LIMIT and OFFSET restrict the final result when supported by the SQL dialect.

This is a conceptual model rather than a description of every internal database implementation detail. Query optimizers can execute operations in different physical ways while preserving the required SQL result semantics.

How to Debug ORDER BY

  • Check that ORDER BY references the column or expression you actually intend to sort by.
  • Verify whether the direction should be ASC or DESC.
  • If multiple columns are used, check their priority from left to right.
  • Inspect NULL values and database-specific NULL ordering.
  • Add a tie-breaker when identical sort values need deterministic ordering.
  • If using GROUP BY, verify that the aggregate value being sorted is correct.
  • If using JOIN, check whether duplicate rows affect the apparent ordering.
  • When using LIMIT, always define ORDER BY if the selected rows have a specific meaning.
  • For slow queries, inspect the execution plan rather than assuming an index will solve the problem.
💡 When debugging a complicated query, temporarily select the column used for sorting. Seeing the actual sort values next to the returned rows often makes an unexpected ordering immediately obvious.

ORDER BY Best Practices

  • Use ORDER BY whenever the application requires a defined result order.
  • Use ASC and DESC explicitly when clarity matters.
  • Put the most important sorting column first.
  • Use additional columns as meaningful tie-breakers when necessary.
  • Use aliases for complex calculated sort values when supported by your SQL dialect.
  • Be explicit about NULL placement when the database supports NULLS FIRST or NULLS LAST.
  • Combine ORDER BY with LIMIT for clearly defined top-N queries.
  • Use a stable ordering strategy for pagination.
  • Do not rely on physical table order or an order observed during testing.
  • Check collation behavior when sorting international or case-sensitive text.
  • Use execution plans when investigating ORDER BY performance.

Frequently Asked Questions

What is ORDER BY in SQL?

ORDER BY sorts the rows returned by a SQL query according to one or more columns or expressions. It can sort values in ascending or descending order.

What is the difference between ASC and DESC?

ASC sorts values in ascending order and is normally the default. DESC sorts values in descending order. For numbers, ASC goes from smaller to larger while DESC goes from larger to smaller.

Can ORDER BY sort by multiple columns?

Yes. Multiple expressions can be supplied to ORDER BY. SQL uses the first expression as the primary sort and later expressions as tie-breakers when earlier values are equal.

Can ORDER BY use a column that is not in SELECT?

In many SQL systems, yes. However, restrictions can apply to specific query forms such as DISTINCT or set operations. Check the rules of the SQL dialect when using ORDER BY with more advanced queries.

What happens if ORDER BY is not used?

The SQL query generally does not guarantee a particular row order. The database may return rows in an order that happens to look consistent, but applications should not rely on that behavior without an explicit ORDER BY.

Can ORDER BY be used with GROUP BY?

Yes. ORDER BY can sort grouped results using grouping columns, aggregate functions, or aliases for calculated aggregate values. This is common in reports and analytical queries.

How do I sort NULL values in SQL?

NULL ordering depends on the database system. Some dialects support NULLS FIRST and NULLS LAST, while others require an expression such as CASE to explicitly control where NULL values appear.

Helpful SQL Sorting Tools

Several SQL development tools can make ORDER BY queries easier to write and troubleshoot. SQL formatters help keep queries with multiple sorting expressions readable. Query validators can detect syntax problems, while query explainers can help clarify how ORDER BY interacts with filtering, grouping, joins, and aggregation. Syntax highlighters make sorting clauses easier to identify visually, and keyword tools can help maintain consistent SQL formatting.

Conclusion

SQL ORDER BY provides explicit control over the order of query results. It can sort numeric values, text, dates, calculated expressions, aggregate results, and values from joined tables.

The basic rules are simple: ASC sorts in ascending order, DESC sorts in descending order, and multiple expressions are evaluated from left to right. ORDER BY can be combined with WHERE, GROUP BY, HAVING, JOIN, LIMIT, and pagination techniques to build predictable and useful database queries.

The most important practical rule is to never rely on an accidental row order when the order matters. If an application, report, or API response requires a particular ordering, express that requirement directly with ORDER BY and use meaningful tie-breakers when deterministic results are important.

Found an issue?

Found an error, outdated information, or something missing from this article? Let me know through the Contact page.

Your feedback helps improve our articles and keep them accurate and useful.