How to Use ORDER BY in SQL

SQL ORDER BY sorts query results by one or more columns in ascending (ASC) or descending (DESC) order after filtering but before limiting. Use ORDER BY column_name [ASC|DESC] and list multiple columns for tie-breakers. Always place it last in the SELECT statement, right before LIMIT or OFFSET clauses.

Learning
June 10, 2025
Galaxy Team
Sign up for the latest notes from our team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
SQL ORDER BY sorts rows by specified columns after filtering. Add ORDER BY column [ASC|DESC] at the end of a SELECT to return data in the desired sequence.

SQL ORDER BY Explained

SQL ORDER BY sorts result sets by one or more columns after filtering, giving you predictable row order for reports, APIs, and analytics.

What Does ORDER BY Do in SQL?

ORDER BY arranges the rows returned by a SELECT statement in a specified sequence. Without it, SQL engines may return rows in any order—even if data looks sorted in the table.

Where Does ORDER BY Sit in the Query?

ORDER BY runs after FROM, JOIN, WHERE, and GROUP BY but before LIMIT or OFFSET. Always place ORDER BY as the last major clause in your SELECT.

How Do I Write Basic ORDER BY Syntax?

Use SELECT columns FROM table ORDER BY column_name [ASC|DESC];. ASC is the default and can be omitted. DESC reverses the order.

How Can I Sort by Multiple Columns?

List columns in priority order: ORDER BY first_col DESC, second_col ASC. The engine sorts by the first column, then breaks ties with the next.

Can I ORDER BY a Column Not in SELECT?

Yes. SQL lets you order by any column in the queried tables, even if that column is not returned in the final projection.

Is It Possible to ORDER BY an Alias or Expression?

You can sort by computed expressions or aliases defined in the SELECT list: SELECT price*quantity AS total FROM sales ORDER BY total DESC;

What About NULL Sorting Rules?

ANSI SQL places NULL values first in ascending order and last in descending. Some databases allow NULLS FIRST or NULLS LAST modifiers for explicit control.

Why Does ORDER BY Impact Performance?

Sorting requires memory and CPU. Large, unsatisfied ORDER BY clauses create temp files and slow queries. Use indexes on the sort columns when possible.

How Do Indexes Help ORDER BY?

A covering index with the same column order lets the engine read rows already sorted, avoiding extra sort operations and boosting speed.

When Should I Combine ORDER BY with LIMIT?

Pagination queries like ORDER BY id DESC LIMIT 20 return only the needed rows after sorting, reducing network traffic and rendering time.

Can I ORDER BY Before GROUP BY?

No. GROUP BY always precedes ORDER BY logically. To sort grouped results, place ORDER BY after the GROUP BY clause.

How Do Window Functions Interact with ORDER BY?

Inside OVER(), ORDER BY defines row order for window calculations, independent of the query’s final ORDER BY. You can use both in one statement.

What Are Best Practices for ORDER BY?

Limit column count, use indexed columns, avoid random ORDER BY RAND(), and paginate. Always test execution plans to ensure indexes are used.

Does ORDER BY Guarantee Deterministic Output?

Only if the sort columns uniquely identify each row. Add a primary key as the last sort key to avoid nondeterministic tie breaks.

How Can I Randomize Row Order?

Use ORDER BY RANDOM() or ORDER BY RAND() depending on the database. Beware: this forces a full table scan and heavy sorting overhead.

How Do I Sort Case-Insensitively?

Apply LOWER() or COLLATE rules: ORDER BY LOWER(name). This normalizes case before sorting so "apple" and "Apple" group together.

Can I Sort by JSON or Array Elements?

Yes in modern engines. PostgreSQL example: ORDER BY payload->>'userId'::int. Always cast to the correct data type for numeric sort accuracy.

When Should I Skip ORDER BY?

Avoid ORDER BY in subqueries feeding aggregations unless necessary. Extra sorts slow queries without affecting the final grouped result.

Key Takeaways on ORDER BY

ORDER BY controls row sequence, supports multi-column sorts, and impacts performance. Index wisely, paginate results, and specify ASC or DESC explicitly.

Frequently Asked Questions (FAQs)

Does ORDER BY slow down queries?

Sorting adds CPU, memory, and sometimes disk I/O. Indexes on the sort columns and limiting returned rows mitigate the cost.

Can I use ORDER BY in subqueries?

Most databases ignore ORDER BY inside subqueries unless LIMIT/TOP is also present. Rely on an outer query’s ORDER BY for final sorting.

What’s the default sort direction?

Ascending (ASC) is the default in ANSI SQL, so ORDER BY column and ORDER BY column ASC are equivalent.

How are NULLs ordered?

ANSI SQL places NULLs first in ASC and last in DESC. Some engines support NULLS FIRST / LAST for explicit control.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Check out our other posts!

Trusted by top engineers on high-velocity teams
Aryeo Logo
Assort Health
Curri
Rubie
BauHealth Logo
Truvideo Logo