SQLORDER BYtutorialbeginner

What is ORDER BY in SQL? Sorting query results for beginners

ORDER BY sorts the result of a SQL query. We cover ASC and DESC, multi-column sorting, NULLs in sort order, and the classic ORDER BY + LIMIT for top-N. Plenty of examples and three exercises.

7 min readSQL · ORDER BY · tutorial · beginner

ORDER BY is the SQL command for sorting query results. Without it, the database returns rows in whatever order it pleases — which looks like chaos to the user. With ORDER BY, you say explicitly: "sort by this column from low to high" (or the other way around).

Analogy: imagine a stack of books on your desk, tossed in a random pile. ORDER BY title means "arrange them alphabetically by title". ORDER BY year DESC means "newest first, oldest last".

Why ORDER BY matters

Without sorting, SQL gives you no guarantees about row order. The same query run twice in a row may return rows in different orders. So if order matters in your result (top-10 sales, news by date, leaderboards) — ORDER BY is mandatory.

Typical scenarios:

  • UI lists: show products from cheapest to most expensive
  • Rankings: top-10 users by points
  • Timelines: posts from newest to oldest
  • Alphabetical lookups: city list from A to Z

Basic syntax

SELECT *
FROM table_name
ORDER BY column_name [ASC | DESC];
  • ASC — ascending (low to high). This is the default — you can omit it.
  • DESC — descending (high to low).

Example: a library books table.

SELECT title, year
FROM books
ORDER BY year DESC;

This lists books from newest to oldest.

Example: a library

books table:

idtitleauthoryearrating
1War and PeaceLeo Tolstoy18694.8
2The Master and MargaritaMikhail Bulgakov19674.9
3And Quiet Flows the DonMikhail Sholokhov19404.7
4Crime and PunishmentFyodor Dostoevsky18664.8

Query — sort by year of publication (ascending):

SELECT title, year FROM books ORDER BY year;

Result:

titleyear
Crime and Punishment1866
War and Peace1869
And Quiet Flows the Don1940
The Master and Margarita1967

Oldest at the top. Switch to DESC and the order flips — newest first.

Sorting by multiple columns

Often one column isn't enough. Same year of publication, then break the tie by rating. Just list them with commas:

SELECT title, year, rating
FROM books
ORDER BY year DESC, rating DESC;

How it works:

  1. The database first sorts by year DESC (newest on top).
  2. Within rows that share the same year, it sorts by rating DESC.
  3. If there were a third field, it would tie-break inside identical year+rating combos.

This is called "multi-level sorting". Very common: "first by date, then by priority within a date", "first by status, then by amount within a status".

Multi-level example. employees table:

idnamedepartmentsalary
1AnnaIT4000
2BorisSales2700
3VeraIT5000
4GrishaHR2300
5DenisIT4000
6ElenaSales3200

Query: first by department (alphabetical), then within department by salary (high to low).

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

Result:

namedepartmentsalary
GrishaHR2300
VeraIT5000
AnnaIT4000
DenisIT4000
ElenaSales3200
BorisSales2700

Departments alphabetical: HR → IT → Sales. Inside IT — Vera (5000), then Anna and Denis (both 4000, undefined order between them), and so on.

Want a deterministic order between Anna and Denis? Add a third tier, e.g. by name: ORDER BY department ASC, salary DESC, name ASC.

Sorting by an expression

ORDER BY accepts not just column names but expressions too:

SELECT title, likes, views
FROM posts
ORDER BY likes::float / views DESC;

This sorts posts by "engagement rate" — likes divided by views. The table has no such column, but the database computes it on the fly.

Another common pattern — using functions:

SELECT name FROM users ORDER BY LOWER(name);

LOWER lowercases the name for case-insensitive sorting.

Top-N: ORDER BY + LIMIT

The classic combo. To get "top 3 posts by likes", you sort first, then truncate:

SELECT title, likes
FROM posts
ORDER BY likes DESC
LIMIT 3;

First ORDER BY likes DESC puts the most-liked on top, then LIMIT 3 keeps the first three. Without ORDER BY, LIMIT 3 returns three arbitrary rows — a classic beginner bug.

NULLs in sorting

If a column has NULL values, databases differ on where to put them:

  • PostgreSQL: ASC — NULLs at the end; DESC — at the beginning.
  • MySQL: ASC — NULLs at the beginning; DESC — at the end.

If you need to be explicit, PostgreSQL has NULLS FIRST / NULLS LAST:

SELECT title, published_at
FROM posts
ORDER BY published_at DESC NULLS LAST;

This gives: fresh posts first, drafts (no publish date) at the very end. MySQL has no such syntax — you have to fake it with an expression: ORDER BY published_at IS NULL, published_at DESC.

Bigger example: before and after

orders table:

idcustomeramountstatuscreated_at
1Anna500paid2024-03-10
2Boris1500paid2024-03-15
3Vera200cancelled2024-03-12
4Grisha3000paid2024-03-08
5Denis800pending2024-03-15

Goal: "paid first, then pending, then cancelled. Within each group, newest at the top; ties broken by larger amount first."

SELECT id, customer, status, amount, created_at
FROM orders
ORDER BY
  CASE status
    WHEN 'paid'      THEN 1
    WHEN 'pending'   THEN 2
    WHEN 'cancelled' THEN 3
  END,
  created_at DESC,
  amount DESC;

Result:

idcustomerstatusamountcreated_at
2Borispaid15002024-03-15
1Annapaid5002024-03-10
4Grishapaid30002024-03-08
5Denispending8002024-03-15
3Veracancelled2002024-03-12

CASE is how you express a custom order for a string column. Alphabetically, cancelled would come before paid — but we care about meaning, not alphabet.

Common beginner mistakes

1. Forgetting that without ORDER BY, order is not guaranteed. People assume "the database keeps insertion order". It doesn't — the order can be anything and may change between runs. Need an order? Write ORDER BY.

2. ORDER BY before FROM. The clause order is fixed: SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT. ORDER BY always sits near the end.

3. Sorting by a column not in SELECT. Most DBs allow this — you can sort by any column from the table even if it's not in the output. Exception: when you SELECT DISTINCT, sorting by a column not in the output errors out, because DISTINCT throws away the data needed for sorting.

4. ORDER BY 1, 2. You can sort by column ordinal in SELECT1 is the first column, 2 the second. Works, but reads poorly. Use names.

5. ORDER BY and UNION. When you UNION two queries, ORDER BY is written once at the very end and applies to the combined result. You can't put it inside individual UNION parts.

6. Numbers as strings. If a VARCHAR column stores numbers ("10", "2", "100"), sorting goes alphabetically, not numerically: "10", "100", "2". Fix by casting ORDER BY CAST(col AS INTEGER), or store numbers as numbers in the first place.

Quick recap

  • ORDER BY sorts the query result.
  • ASC (default) is ascending, DESC is descending.
  • Sort by multiple columns with commas — multi-level sort.
  • Expressions and functions are valid in ORDER BY, not just column names.
  • Without ORDER BY, no order is guaranteed.
  • Combined with LIMIT it gives you top-N.
  • Watch out for NULLs — databases place them differently.

Try it yourself

On the books table:

  1. List books from highest rating to lowest.
  2. Sort by author (alphabetical), then within an author by year (oldest to newest).
  3. Top-3 books by rating (combo ORDER BY + LIMIT).

Write the queries on your own first. Sorting is one of the most intuitive SQL operations — you'll get it fast.

Practice on real tasks

Solve tasks in the SQL trainer with instant grading and hints.

Open trainer