Tier 1 · Foundations

ORDER BY and Result Sorting in SQL

By Owen Middleton · Updated September 2026 · Examples run on PostgreSQL 17

What is ORDER BY in SQL?

ORDER BY controls the sequence rows come back in.

Without it, SQL returns rows in whatever order it finds convenient. The database doesn't guarantee any particular sequence unless you ask for one, and that order can change between runs as data changes. The moment you need results in a specific order, you add ORDER BY.

This comes up constantly in analyst work. A sales report needs deals from largest to smallest. A customer list needs to be alphabetical. A log needs to be newest first. The underlying data doesn't care about any of that. ORDER BY is you imposing the sequence that matters for the purpose.

How do you sort query results in SQL?

Write ORDER BY after FROM and name the column to sort by. SQL defaults to ascending order — smallest first for numbers, A to Z for text:

SELECT name, price
FROM products
ORDER BY price, id

The id after the comma is a tiebreaker. When two products share the same price, SQL uses id to break the tie and produce a consistent order. Multiple sort keys work left to right: sort by the first, use each additional column to resolve ties.

How do you sort in descending order in SQL?

Add DESC to flip the direction:

SELECT name, price
FROM products
ORDER BY price DESC, id

Most-expensive-first. The id tiebreaker stays ascending by default, keeping the order predictable when prices match.

Can you ORDER BY a column alias in SQL?

You can sort by a computed column. Give the expression an alias in SELECT and reference it by name in ORDER BY — this is one of the few places in a query where a SELECT alias can be used:

SELECT name, price * stock_qty AS stock_value
FROM products
ORDER BY stock_value DESC, name

Where do NULLs sort in SQL?

When a sort column contains NULL values, SQL puts them at the end in ascending order and at the top in descending order by default. If you need NULLs in a specific position regardless of direction, NULLS LAST or NULLS FIRST makes it explicit:

SELECT name, city
FROM customers
ORDER BY city DESC NULLS LAST, id

Practice ORDER BY in SQL

Practice · easy ecommerce · Brightlane

Brightlane's product team is preparing a catalogue sorted by price for a buyer presentation.

Write a query to return each product's name and price, sorted from the least expensive to the most expensive.

Assumptions:

  • The products table contains every product in Brightlane's catalogue.
  • When two products share the same price, the product with the lower id should appear first.

Output:

  • One row per product, with columns name and price, sorted by price ascending, then by id ascending.
Schema · ecommerce5 tables? = nullable
categories
idinteger
nametext
parent_id?integer
products
idinteger
nametext
category_id?integer
pricenumeric
stock_qtyinteger
attributes?jsonb
order_items
idinteger
order_id?integer
product_id?integer
quantityinteger
unit_pricenumeric
customers
idinteger
nametext
emailtext
city?text
countrytext
created_attimestamptz
is_activeboolean
orders
idinteger
customer_id?integer
ordered_attimestamptz
statustext
total_amountnumeric

Run previews · Check grades

Write a query, then run it to see results here.

Worked solution

The full breakdown walks through the shape, each clause, why this approach beats the alternatives, and the trap to avoid.

See the full worked solution

9 ORDER BY practice problems

Start learning to practice all 9 ORDER BY problems, with instant grading and mastery tracking.

Common questions about ORDER BY

Is row order guaranteed without an ORDER BY?

No. Without ORDER BY, PostgreSQL returns rows in whatever order is convenient for the plan it chose, and that can change as the data changes. If the order matters to whoever reads the result, say so with ORDER BY rather than trusting what you saw last time.

How do you sort by more than one column?

List the columns after ORDER BY separated by commas. PostgreSQL sorts by the first, then uses each later column only to break ties in the one before it. A second key is what makes the order of equal-priced rows stable instead of arbitrary.

Can you sort by a column you are not selecting?

Yes. ORDER BY can name any column in the table, whether or not it appears in the SELECT list, so returning product names ordered by price takes no extra column in the output.

Can ORDER BY use a column alias?

Yes, and it is one of the few places that can. Sorting is worked out after the SELECT list, so the alias exists by then. You can also sort by the position of a column, though a name survives edits to the SELECT list better than a number does.

How you actually get good at SQL

Reading explains SQL. Writing it, over and over with instant feedback, is what makes you fluent.

That's the whole SQLMaxx loop: 600+ real problems, instant AI feedback, mastery you can actually see, and spaced review that won't let you forget.

A stack of SQL practice problem cards, the top card showing an employees table.
615 problems · 66 concepts

Real problems. Not toy examples.

615 hand-built problems spanning all 66 concepts, from basic SELECTs to window functions, built on real schemas and real business questions, the kind you'll actually get asked on the job. Enough reps to make SQL automatic.

A retro computer showing a SQL query marked correct with a green checkmark.
Instant AI feedback

Write a query. Know if it's right in one second.

No copying an answer and hoping it clicked. The AI grader checks your real query against real data, catches exactly what's wrong, and explains the fix in plain English, like a senior analyst reading over your shoulder on every problem.

A circular mastery progress dial filling from blue to green, the SQLMaxx diamond at its center.
Mastery tracking

Stop guessing whether you actually know it.

SQLMaxx tracks every concept and shows you what you've mastered and what's still shaky. Your skills fill in one concept at a time, so 'I think I get joins' becomes something you can prove.

A SQL query editor circled by a blue return arrow with a clock, scheduled to come back for review.
Spaced review

Learn it once. Keep it for good.

Most of what you learn this week fades by next week. So when a concept comes due for review, SQLMaxx hands you a fresh problem to solve from a blank editor, not a flashcard to re-read. A research-backed spaced-repetition algorithm (FSRS) times each return for right before you'd forget, so your SQL is still there months later, when the interview or the job actually needs it.