
MySQL ORDER BY
The MySQL ORDER BY clause is used to sort the result set of a SELECT query based on one or more columns. You can use it to specify the order in which you want the rows to appear in the query result. By default, ORDER BY sorts the rows in ascending order, but you can also sort them in descending order.
The basic syntax of the ORDER BY clause is as follows:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
Here’s how it works:
column1,column2, and so on represent the columns by which you want to sort the result set.table_nameis the name of the table from which you are selecting data.ORDER BYspecifies the sorting criteria for the rows.- You can specify one or more columns by which you want to sort the data.
- You can use
ASC(ascending) orDESC(descending) to control the sorting order. The default isASC.
Here are some examples of how to use the ORDER BY clause in MySQL:
- Sort the result set of a
SELECTquery in ascending order based on theproduct_namecolumn:
SELECT product_name, price
FROM products
ORDER BY product_name;
- Sort the result set in descending order based on the
pricecolumn:
SELECT customer_name, order_date, total_amount
FROM orders
ORDER BY total_amount DESC;
- Sort the result set by multiple columns. If there is a tie in the first column, it will be sorted by the second column:
SELECT product_category, product_name, price
FROM products
ORDER BY product_category, price;
- Sort the result set in ascending order by one column and in descending order by another column:
SELECT employee_name, hire_date
FROM employees
ORDER BY hire_date ASC, employee_name DESC;
The ORDER BY clause is essential for controlling the order in which rows appear in the result set. It is commonly used for presenting data in a meaningful way, such as sorting results by alphabetical order, date, or numerical values. You can sort data based on one or more columns, and you have the flexibility to choose between ascending and descending order for each column.