ORDER BY — Sorting Results

The ORDER BY clause lets you sort the results of your SQL query.
You can sort data by one or more columns, in ascending or descending order.


Syntax

SELECT column1, column2 FROM table_name
ORDER BY column1 [ASC|DESC];
  • ASC - means ascending order (default)
  • DESC - means descending order

Example 1: Sort by Age (Ascending)

SELECT name, age FROM employees
ORDER BY age;

This sorts the employee list from youngest to oldest.


Example 2: Sort by Name (Descending)

SELECT name FROM employees
ORDER BY name DESC;

This sorts names from Z to A.


Example 3: Sort by Department, then Name

SELECT name, department FROM employees
ORDER BY department, name;

This sorts first by department, and then by name within each department.


Tip

You can sort by a column that’s not shown in your SELECT list.

SELECT name FROM employees
ORDER BY age;

This still works — it sorts by age but only displays name.


The ORDER BY clause helps you make results easier to understand by organizing them in a meaningful way.