MYSQL Tutorial



MySQL ORDER BY


MySQL ORDER BY Clause

The ORDER BY clause is used to sort the result set of a query by one or more columns. You can sort in ascending (ASC) or descending (DESC) order.

Syntax

SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
  

Example 1: Sort by one column (ascending order)

Get all employees sorted by their last_name in alphabetical order:

SELECT first_name, last_name, department
FROM employees
ORDER BY last_name ASC;
  

Example 2: Sort by one column (descending order)

Get employees sorted by salary from highest to lowest:

SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC;
  

Example 3: Sort by multiple columns

Sort employees first by department (ascending), then by salary (descending) within each department:

SELECT first_name, last_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
  

Key Points

  • If ASC or DESC is not specified, sorting defaults to ascending.
  • You can order by columns not included in the SELECT statement.
  • Text columns are sorted alphabetically, and numeric columns are sorted numerically.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review