bhylu.com

Advertisements

SQL Order By

ORDER BY makes a result predictable. A table is not a spreadsheet whose current visible row order can be relied on. Ask for a specific order whenever the order matters to a person or another part of your program.

Understand the idea

ASC means ascending and is the default. DESC reverses the direction. Multiple sort columns are evaluated from left to right: a later column breaks ties in an earlier one. Adding a unique identifier as the last sort key gives stable results when other values are equal, which matters for pagination.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

SELECT name, category, price_cents
FROM products
ORDER BY category ASC, price_cents DESC, product_id ASC;

Read the result

Products are arranged by category. Within Stationery, Pencil set comes before Pocket notebook because 450 is greater than 250. Other categories each contain one product in this sample.

Try one change

Sort products by stock from lowest to highest, with product_id breaking ties. Predict the first product before running it.