We use ORDER BY multiple columns to sort data by more than one rule. This helps organize results clearly.
0
0
ORDER BY multiple columns in SQL
Introduction
When you want to sort a list of people first by last name, then by first name.
When you have sales data and want to order by region, then by sales amount.
When you want to display products sorted by category and then by price.
When you want to organize events by date and then by start time.
Syntax
SQL
SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
You can choose ascending (ASC) or descending (DESC) order for each column.
If you don't specify ASC or DESC, ascending order is the default.
Examples
Sorts employees by last name ascending, then by first name ascending.
SQL
SELECT first_name, last_name FROM employees ORDER BY last_name, first_name;
Sorts products by category ascending, then by price descending.
SQL
SELECT product_name, category, price FROM products ORDER BY category ASC, price DESC;
Sorts events by date descending (newest first), then by start time ascending.
SQL
SELECT event_name, event_date, start_time FROM events ORDER BY event_date DESC, start_time ASC;
Sample Program
This creates a table of employees, adds some data, and then selects their names and departments sorted by last name and first name both ascending.
SQL
CREATE TABLE employees ( id INT, first_name VARCHAR(50), last_name VARCHAR(50), department VARCHAR(50) ); INSERT INTO employees (id, first_name, last_name, department) VALUES (1, 'John', 'Smith', 'Sales'), (2, 'Jane', 'Doe', 'Marketing'), (3, 'Alice', 'Smith', 'HR'), (4, 'Bob', 'Brown', 'Sales'); SELECT first_name, last_name, department FROM employees ORDER BY last_name ASC, first_name ASC;
OutputSuccess
Important Notes
Ordering by multiple columns helps when one column alone can't sort data clearly.
Use ASC for ascending order and DESC for descending order on each column.
ORDER BY is usually the last clause in a SELECT query.
Summary
ORDER BY multiple columns sorts data by more than one rule.
You can mix ascending and descending order for each column.
This helps organize data clearly when one column is not enough.