SelectFromData
AnalyticsLesson 3 of 12 · 10 min

ORDER BY: Put the Result in Order

Here's a fact that surprises everyone: without ORDER BY, a query's rows come back in no guaranteed order. It might look ordered today and shuffle tomorrow. If order matters — and for any ranking, report, or "top" question it does — you say so.

In one line

ORDER BY column sorts the result low-to-high; add DESC for high-to-low. It's the last thing the database does before handing you the rows.

Sort it

Run it, then remove DESC and run again — watch the direction flip:

Salaries, highest first
Editable · runs in your browser

ASC (ascending, low → high) is the default, so you rarely type it. DESC (descending) is the one you'll write constantly: biggest revenue first, newest order first, highest score first.

Sort by more than one thing

Ties happen. A second sort key settles them: ORDER BY department, salary DESC groups the rows by department alphabetically, then puts the best-paid first within each department. Run it:

Department A→Z, then salary high→low inside each department
Editable · runs in your browser

Your turn

Return name and salary of all employees, highest salary first.

Your turn · Exercise

Return name and salary of all employees, sorted with the highest salary first.

The data

employees

5 rows returned

namesalary
Ada62,000
Bo48,000
Cy71,000
Di52,000
Eli45,000
Runs in your browser
Check yourself

Your query has no ORDER BY, but the rows came back sorted by date. What can you rely on?


Next: sorted rows set up the most common business question there is — "give me the top N." That's LIMIT.