SQL ORDER BY: sorting query results, explained and practiced

ORDER BY decides the order of your rows: a price list from cheapest up, orders by date, staff by department and salary. Add LIMIT and you keep only the first few rows, such as the three latest orders.

In short: ORDER BY price sorts ascending (smallest first), ORDER BY price DESC sorts descending. Separate several sort columns with commas. LIMIT 3 at the end keeps just the first three rows.

What you should know first: picking columns with SELECT and filtering rows with WHERE.

Try it now

Without ORDER BY there is no guaranteed order. Rows often come back the way they're stored, but you can't rely on it. In these exercises the order of the rows is part of the check.

Task For the new price list: show the name and price of every product, sorted by price with the cheapest first.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

How ORDER BY works

ORDER BY comes after FROM and WHERE, near the end of the query. After it you name the column to sort by and, if you like, the direction:

KeywordDirectionNumbersTextDates (YYYY-MM-DD)
ASC or nothingascendinglow to highA to Zoldest first
DESCdescendinghigh to lowZ to Anewest first

The warehouse wants to know which products they hold the most of:

SELECT name, stock
FROM products
ORDER BY stock DESC;

The first five of twelve rows:

namestock
Copy paper, 500 sheets420
Blue ballpoint pens, 10-pack310
Lever arch file, gray185
Notebook A5, ruled140
Black ink cartridge64

At the bottom sit the sticky notes and the shredder, both with a stock of 0. Which of the two comes first isn't fixed: the SQLite documentation says the order of rows with equal sort values is undefined. If you need it fixed, add a second sort column, for example ORDER BY stock DESC, name.

Sorting by more than one column

With several sort columns, the first one wins. Only where it's tied does the second one count, then the third. ASC and DESC apply only to the column right before them: ORDER BY department, salary DESC lists departments A to Z and, inside each department, salaries from high to low.

Task Management needs a list for the pay review: department, last_name and salary for every employee. Sort by department from A to Z, and within each department put the highest salary first.

employees 10 rows, 7 columns
employee_idfirst_namelast_namedepartmentsalaryhire_datemanager_id
1KarenMitchellManagement936002018-01-02NULL
2TomBradleySales624002019-04-011
3JuliaReyesSales468002021-06-152
4MarcusAllenSales492002020-09-012
5SarahLongWarehouse396002022-02-011
6FelixTurnerWarehouse354002024-03-185
7NinaCooperAccounting528002019-10-011
8DavidRossCustomer service384002023-05-022
9LauraHughesCustomer serviceNULL2025-09-012
10PaulWardAccounting432002022-11-147

Just the first rows: LIMIT and OFFSET

LIMIT n goes at the very end and keeps the first n rows of the sorted result. OFFSET m skips m rows first, which is how you page through results. Places 4 to 6 by stock level:

SELECT name, stock
FROM products
ORDER BY stock DESC
LIMIT 3 OFFSET 3;
namestock
Notebook A5, ruled140
Black ink cartridge64
Black toner XL22

LIMIT without ORDER BY gives you any old rows. For "the three most expensive" or "the three latest", you need both.

Task The dashboard should show the three most recent orders. Show order_id, order_date and status for those three orders, newest first.

orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

Sorting by column number

Instead of a name you can give the column's position in the SELECT list: SELECT name, price FROM products ORDER BY 2 sorts by price. It's short, but fragile. Add a column at the front later and the query quietly sorts by something else. MySQL calls this syntax deprecated, and Microsoft advises against it in SQL Server. Use the name.

Where do NULLs go?

Laura Hughes has no salary on file yet. With ORDER BY salary she comes first in these exercises, with ORDER BY salary DESC last, because SQLite treats NULL as the smallest value when sorting. Not every database agrees (see the table below). In SQLite and PostgreSQL you can decide for yourself by adding NULLS FIRST or NULLS LAST, as in ORDER BY salary DESC NULLS FIRST. The NULL lesson explains what NULL actually is.

Common mistakes

Clauses in the wrong order

... LIMIT 3 ORDER BY order_date DESC fails because LIMIT always comes last. The exercise tells you "LIMIT goes at the very end, after ORDER BY". Putting ORDER BY before WHERE fails too, with a syntax error and a reminder of the right order of the clauses.

DESC only covers one column

ORDER BY department DESC, salary reverses the departments and leaves salary ascending. The exercise tells you "The rows are right, but not their order". Put DESC straight after every column that should run high to low.

Forgetting the direction

ORDER BY order_date LIMIT 3 returns the three oldest orders instead of the newest. The exercise says these are the wrong rows and that with LIMIT the sort order decides which rows come first.

TOP or FETCH FIRST in the exercises

SELECT TOP 3 ... is SQL Server syntax and FETCH FIRST 3 ROWS ONLY is the SQL standard's. SQLite knows neither. For TOP the exercise explains that it only exists in SQL Server and shows the LIMIT version. Use LIMIT here.

ORDER BY in MySQL, PostgreSQL, SQL Server and SQLite

ORDER BY with ASC, DESC and several columns works the same everywhere. The differences are in limiting rows and in NULL handling:

DatabaseFirst 3 rowsNULLs in ascending orderNULLS FIRST / LAST
MySQLLIMIT 3, also LIMIT 3 OFFSET 6 or LIMIT 6, 3firstnot in the syntax
PostgreSQLLIMIT 3 or FETCH FIRST 3 ROWS ONLYlastyes
SQL ServerSELECT TOP (3) ... or OFFSET 0 ROWS FETCH NEXT 3 ROWS ONLY after ORDER BYfirstnot in the syntax
SQLite (these exercises)LIMIT 3, also LIMIT 3 OFFSET 6 or LIMIT 6, 3firstyes, since version 3.30.0

Watch out for the short comma form: LIMIT 6, 3 means "skip 6, then take 3", so the numbers are the other way round from LIMIT and OFFSET. The SQLite documentation explicitly recommends the OFFSET form for that reason. OFFSET … FETCH is the SQL standard's syntax since SQL:2008, and PostgreSQL supports it alongside LIMIT.

Sources: MySQL Reference Manual (SELECT Statement, Problems with NULL Values, Sorting Rows), PostgreSQL documentation (SELECT, Sorting Rows), Microsoft Learn (ORDER BY Clause, TOP), sqlite.org (SELECT, Release History 3.30.0).

FAQ

Does the sort column have to be in the SELECT list?

No. SELECT name FROM products ORDER BY price works: prices are used for sorting but not shown. Still, whoever reads the result usually finds it easier when the sort column is visible.

Why do rows sometimes repeat or go missing when paging with OFFSET?

When several rows share the same sort value, the database is free to order them differently on each run. One row can then show up on two pages while another never appears. Add a unique column, such as the ID, as the last sort key.

Why does "apple" come after "Zebra"?

That depends on the database's collation. In these exercises SQLite compares text byte by byte, so capital letters come before small ones and accented letters such as é land after z. According to the MySQL manual, MySQL normally sorts text without regard to case; PostgreSQL and SQL Server follow whatever collation is set up.

Can I sort by a calculation?

Yes, ORDER BY accepts an expression as well, for example ORDER BY price * stock DESC for stock value. How to show such a value as its own column is covered in the calculations lesson.

Learn this next: DISTINCT

Which cities do your customers come from, each listed once? DISTINCT removes duplicate rows from the result.

Practice DISTINCT

Write to us

Choose language

Select your preferred language