MYSQL Tutorial



SORTING IN MYSQL


Sorting in MySQL

Sorting data in MySQL is done using the ORDER BY clause. It allows you to sort the result set by one or more columns either in ascending or descending order.

Syntax

SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC | DESC], column_name2 [ASC | DESC], ...;
  

Explanation

  • ORDER BY sorts the results by the specified column(s).
  • ASC means ascending order (smallest to largest). This is the default.
  • DESC means descending order (largest to smallest).
  • You can sort by multiple columns, separated by commas.

Example 1: Sort by one column (ascending)

Get all products sorted by their price in ascending order:

SELECT product_name, price
FROM products
ORDER BY price ASC;
  

Example 2: Sort by one column (descending)

Get all products sorted by price in descending order:

SELECT product_name, price
FROM products
ORDER BY price DESC;
  

Example 3: Sort by multiple columns

Sort products first by category ascending, then by price descending within each category:

SELECT product_name, category, price
FROM products
ORDER BY category ASC, price DESC;
  

Important Notes

  • If you omit ASC or DESC, the default sorting order is ascending.
  • You can sort by columns not in the SELECT list.
  • Sorting by text columns sorts alphabetically (A-Z for ASC, Z-A for DESC).

🌟 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