Back to Blog
Lesson 9 of the PostgreSQL: SQL & PostgreSQL from Scratch course
DatabasesJuly 27, 20264 min read

Sorting Query Results: Mastering ORDER BY in PostgreSQL

Learn how to use the ORDER BY clause to sort query results in PostgreSQL. Master ascending and descending orders and multi-column sorting for clean data.

PostgreSQLSQLDatabasesORDER BYQuerying
A close-up view of a laptop displaying a search engine page.

Previously in this course, we covered Introduction to SELECT Queries to fetch data from our tables. While retrieving the right data is essential, presenting it in a logical, readable format is equally critical for any application—whether you're displaying a product catalog or a customer list.

In this lesson, we introduce the ORDER BY clause, which provides the tools necessary for effective data organization within your SQL queries.

Understanding Data Organization with ORDER BY

By default, PostgreSQL returns rows in the order they were physically inserted into the table, which is often effectively random from a user's perspective. The ORDER BY clause allows you to explicitly define how your results should be presented.

Think of it as the "Sort" button in a spreadsheet. It tells the database engine to perform a final pass over the result set to arrange rows based on the values in one or more specified columns.

Sorting in Ascending and Descending Order

The most basic use of ORDER BY is to sort a single column. By default, PostgreSQL sorts in ascending order (ASC), meaning lowest-to-highest (for numbers) or A-to-Z (for text).

If you want to reverse this—for example, showing the most expensive items first—you use the DESC keyword.

Worked Example: Sorting Products

Imagine our products table has a price column. To view our inventory sorted by price, we write:

SQL
-- Ascending order (default)
SELECT product_name, price 
FROM products 
ORDER BY price ASC;

-- Descending order (highest price first)
SELECT product_name, price 
FROM products 
ORDER BY price DESC;

Sorting by Multiple Columns

Real-world data often requires more nuance. What if two products have the same price? You might want them sorted by price, and then alphabetically by name. You can achieve this by chaining column names in the ORDER BY clause separated by commas.

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

In this example, PostgreSQL sorts by price first. If two rows have an identical price, the database then looks at the product_name to break the tie, ordering those specific items alphabetically.

Hands-on Exercise

Close-up of foam handle hand grippers for enhancing grip strength during workouts.

Using the products table you created in Designing the Products Table, try the following:

  1. Write a query to retrieve all products, ordered by product_name in alphabetical order.
  2. Write a query to list all products, but sort them by category (A-Z) and then by price (highest to lowest).

Pro tip: Don't forget that you can combine these techniques with the Filtering Data with WHERE logic you learned earlier to organize only the subset of data you actually care about.

Common Pitfalls

  • Performance Overhead: Sorting large datasets is computationally expensive. If you find yourself needing to sort millions of rows frequently, you will eventually need to learn about indexes (which we'll cover in future lessons). For now, keep your results sets focused using WHERE clauses.
  • NULL Values: By default, NULL values are treated as "larger" than non-null values. In an ascending sort, NULLs appear at the end. You can control this using NULLS FIRST or NULLS LAST if your business logic requires specific handling.
  • Forgetting the Clause: Beginners often forget that ORDER BY must come after the WHERE clause. The logical order of operations is FROM -> WHERE -> SELECT -> ORDER BY.

FAQ

Q: Does sorting change the data in my table permanently? A: No. ORDER BY only affects the presentation of the result set returned by that specific query. Your stored data remains untouched.

Q: Can I sort by a column that isn't in my SELECT list? A: Yes, you can. You can sort by any column present in the table you are querying, even if you don't display it in the output.

Q: Is there a shorthand for ascending order? A: Yes. Because ASC is the default, you can simply write ORDER BY column_name without specifying the direction.

Recap

In this lesson, we moved from raw data retrieval to data organization. You now know how to:

  • Use ASC and DESC to flip the view of your data.
  • Chain columns in ORDER BY to handle tie-breakers.
  • Place ORDER BY correctly at the end of your query statement.

Mastering these basic sorting techniques is foundational for building clean, user-friendly interfaces in your store application.

Up next: Limiting and Offsetting Results to manage large datasets and implement simple pagination.

Similar Posts