☰ Learn SQL Tutorial Menu

Sorting Results with ORDER BY

Written by Faisal Adnan · Updated 16 Sept 2026 · 3 min read


ORDER BY controls the order rows come back in. Without it, a database makes no guarantee about row order — never rely on "the order it happens to come back in."

Basic sorting

SELECT first_name, salary FROM employees
ORDER BY salary;

By default, sorting is ascending (ASC) — smallest/earliest first. Use DESC for descending:

SELECT first_name, salary FROM employees
ORDER BY salary DESC;

Sorting by multiple columns

Ties in the first column are broken by the second, and so on:

SELECT department_id, first_name, salary FROM employees
ORDER BY department_id ASC, salary DESC;

This sorts employees into department order, and within each department, highest paid first.

Sorting by column position

You can refer to columns by their position in the SELECT list (1-based) — handy for quick queries, but avoid it in real code since it breaks if you reorder columns:

SELECT first_name, salary FROM employees
ORDER BY 2 DESC;

Combining with LIMIT / TOP

Sorting and limiting together is one of the most common query patterns — "top 5 highest earners":

-- SQLite / PostgreSQL / MySQL
SELECT first_name, salary FROM employees
ORDER BY salary DESC
LIMIT 5;

-- SQL Server
SELECT TOP 5 first_name, salary FROM employees
ORDER BY salary DESC;

Open the Code Playground, pick any SQL engine (SQLite, PostgreSQL, MySQL, or SQL Server), and paste these queries in directly — the practice database above is already loaded for you, every time.

Lesson 6 of 27

Sign in to track your progress and earn XP for every lesson you finish.

Practice tip: the built-in code runner is being upgraded. Until it is back, copy the examples into any SQL or Python tool you have (for example SQLite, PostgreSQL, MySQL, SQL Server or a free online editor) and run them there. You can keep reading and earning XP here.