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.
SELECT column_name(s) FROM table_name ORDER BY column_name [ASC | DESC], column_name2 [ASC | DESC], ...;
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).Get all products sorted by their price
in ascending order:
SELECT product_name, price FROM products ORDER BY price ASC;
Get all products sorted by price
in descending order:
SELECT product_name, price FROM products ORDER BY price DESC;
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;
ASC
or DESC
, the default sorting order is ascending.SELECT
list.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!