Getting Data in Order: Using ORDER BY in SQL

Advertisement

Jun 04, 2025 By Tessa Rodriguez

Mention too

In SQL, there are a few commands you end up using almost every day. SELECT, WHERE, and JOIN tend to show up often. However, if you're working with any amount of data that needs to make sense to people, the ORDER BY clause becomes equally important. It's simple, but it does a lot.

Whether you're putting dates in order, sorting by name, or determining who made the highest sales, this clause helps keep the output readable and logical. Knowing how it works—and how to use it right—can make your queries much cleaner and more useful.

What ORDER BY Does in SQL?

The ORDER BY clause in SQL lets you sort the results of a query by one or more columns. You sort in ascending order (ASC) or descending order (DESC). SQL, by default, operates in ascending order unless otherwise specified. The clause occurs only at the end of a SELECT statement, after WHERE, GROUP BY, or HAVING clauses if they are present. It is not merely a matter of sorting alphabetically or numerically—it also influences the way humans read and interpret the results, particularly when those results are lengthy or grouped.

Sorting can be done on numeric values, text, dates, or even expressions. For example, if you sort a list of employees by last name, you're working with text. If you sort by salary or hire date, you're using numbers and dates. The ORDER BY clause works on all of these and can be layered, so you can sort by one column and then by another if there are ties.

How It Works in Practice?

Suppose you have a table named employees with columns such as name, salary, and hire_date. When you issue a simple query:

SELECT name, salary FROM employees ORDER BY salary;

SQL will list employees from the lowest salary to the highest. If you add DESC, like this:

SELECT name, salary FROM employees ORDER BY salary DESC;

It flips the order and shows the highest-paid employees first. You can also sort by multiple columns. If two people have the same salary, and you want them listed alphabetically by name, the query would be:

SELECT name, salary FROM employees ORDER BY salary DESC, name ASC;

This adds a layer of sorting. It first checks the salary. If there are duplicates, it then sorts those by name. It works the same way with dates, so a query like:

SELECT name, hire_date FROM employees ORDER BY hire_date;

will show employees from the earliest hire date to the latest.

This clause also works with expressions or functions. For example, you might want to sort by the length of a name:

SELECT name FROM employees ORDER BY LENGTH(name);

This orders names based on the number of characters they have. You can also use case statements inside the sorting process if you need something more custom.

When Sorting Gets Complicated

Sorting data seems easy at first, but there are some things to watch for. One common issue is trying to sort by a column that isn’t included in the SELECT list. SQL allows this, but it depends on how you’re using aliases or joins. If you have renamed a column or used an expression, you can refer to it in the ORDER BY using its alias. For example:

SELECT name, salary * 1.1 AS adjusted_salary FROM employees ORDER BY adjusted_salary;

Here, the alias adjusted_salary is used directly in the ORDER BY. You don’t need to repeat the expression.

Another detail is that ORDER BY can work with column indexes in a SELECT list. So, if your query is:

SELECT name, salary FROM employees ORDER BY 2;

SQL understands this as “order by the second column,” which is salary. While this is shorter, it can make your queries harder to read, especially if you go back to them later. It’s generally better to use column names or aliases for clarity.

Sorting also interacts with NULL values in different ways depending on the database. Some systems put NULLs at the top when sorting in ascending order, while others put them at the bottom. You can often control this by adding NULLS FIRST or NULLS LAST to the clause:

SELECT name FROM employees ORDER BY hire_date NULLS LAST;

This way, any employees without a hire date appear at the end of the list rather than at the beginning.

ORDER BY with LIMIT and Subqueries

The ORDER BY clause becomes more useful when paired with LIMIT, especially when trying to retrieve top or bottom results. For instance, if you want to see the three highest-paid employees:

SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3;

Without the ORDER BY clause, LIMIT would simply return three random rows. When sorting matters, the two clauses usually go together.

Subqueries can also include ORDER BY, but the outer query doesn’t care about that order unless you specifically order the outer result. For example, in this query:

SELECT * FROM (

SELECT name, salary FROM employees ORDER BY salary DESC

) AS subquery;

The outer query isn't sorted unless you add another ORDER BY. SQL doesn't guarantee the order of the final output unless the top-level query includes the clause.

There is another subtle point to consider when using sorting in views. Some developers expect the view to preserve order if the ORDER BY is defined inside it. But again, SQL only guarantees order when it’s in the final query. If you build a view like this:

CREATE VIEW top_employees AS

SELECT name, salary FROM employees ORDER BY salary DESC;

And later query it:

SELECT * FROM top_employees;

There’s no guarantee that the result will be sorted. You’d need to use ORDER BY again in the SELECT from the view if you want to ensure the order is preserved.

Conclusion

The ORDER BY clause makes SQL results easier to read and more practical. It sorts text, numbers, or dates and works well with aliases, functions, and the LIMIT clause. Just remember, sorting only applies when used in the top-level query. Once you understand its behavior, using ORDER BY becomes a natural part of writing cleaner SQL.

Advertisement

You May Like

Top

Climbing Smarter: How Hill Climbing Works in Artificial Intelligence

How the hill climbing algorithm in AI works, its different types, strengths, and weaknesses. Discover how this local search algorithm solves complex problems using a simple approach

May 23, 2025
Read
Top

Vertex AI Model Garden: A Growing Hub for Open LLMs

How the Vertex AI Model Garden supports thousands of open-source models, enabling teams to deploy, fine-tune, and scale open LLMs for real-world use with reliable infrastructure and easy integration

May 26, 2025
Read
Top

Is Junia AI the Writing Assistant You’ve Been Looking For

Looking for a reliable and efficient writing assistant? Junia AI: One of the Best AI Writing Tool helps you create long-form content with clear structure and natural flow. Ideal for writers, bloggers, and content creators

May 16, 2025
Read
Top

Orca LLM: A Smarter Way to Train AI

How Orca LLM challenges the traditional scale-based AI model approach by using explanation tuning to improve reasoning, accuracy, and transparency in responses

May 20, 2025
Read
Top

Sisense Integrates Embeddable Chatbot: A Game-Changer for Generative AI

Sisense adds an embeddable chatbot, enhancing generative AI with smarter, more secure, and accessible analytics for all teams

Jun 18, 2025
Read
Top

Meet the Innovators: 9 Data Science Companies Making an Impact in the USA

Which data science companies are actually making a difference in 2025? These nine firms are reshaping how businesses use data—making it faster, smarter, and more useful

May 31, 2025
Read
Top

Step-by-Step Guide to Building a Waterfall Chart in Excel

Learn how to create a waterfall chart in Excel, from setting up your data to formatting totals and customizing your chart for better clarity in reports

May 31, 2025
Read
Top

Maia 100 and Cobalt CPU: Microsoft’s Move to In-House AI and Cloud Chips

Microsoft’s in-house Maia 100 and Cobalt CPU mark a strategic shift in AI and cloud infrastructure. Learn how these custom chips power Azure services with better performance and control

May 28, 2025
Read
Top

How Construction Is an Industry 4.0 Application for AI: A Revolutionary Shift

Discover how AI in the construction industry empowers smarter workflows through Industry 4.0 construction technology advances

Jun 13, 2025
Read
Top

How MobileNetV2 Makes Deep Learning Work on Phones and Edge Devic-es

How MobileNetV2, a lightweight convolutional neural network, is re-shaping mobile AI. Learn its features, architecture, and applications in edge com-puting and mobile vision tasks

May 20, 2025
Read
Top

Breaking the Cycle of Algorithmic Bias in AI Systems: What You Need to Know

Know how to reduce algorithmic bias in AI systems through ethical design, fair data, transparency, accountability, and more

Jun 02, 2025
Read
Top

Streamline Machine Learning with Hugging Face + PyCharm Integration

How using Hugging Face + PyCharm together simplifies model training, dataset handling, and debugging in machine learning projects with transformers

May 14, 2025
Read