☰ Learn SQL Tutorial Menu
Sorting Results with ORDER BY
Written by CSA mentors · 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 learning points for every lesson you finish.
Example
-- A ready-to-query practice database is loaded automatically before every run —
-- no CREATE TABLE needed. Available tables:
-- departments (id, name, location)
-- employees (id, first_name, last_name, email, department_id, job_title, salary, hire_date, manager_id)
-- customers (id, customer_name, city, country, signup_date)
-- products (id, product_name, category, price, stock_quantity)
-- orders (id, customer_id, employee_id, order_date, status)
-- order_items (id, order_id, product_id, quantity, unit_price)
SELECT * FROM employees WHERE department_id = 1;
