Sorting data is an important aspect of working with a MySQL database. Sorting allows you to organize data in a meaningful way, making it easier to understand and analyze. In MySQL, you can sort data using the ORDER BY clause in a SELECT statement.
1 2 3 | SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ... |
For example, to sort a table of employees by last name and then by first name, you could use the following query:
1 2 3 | SELECT first_name, last_name, salary FROM employees ORDER BY last_name, first_name; |
You can also sort by computed values, such as the result of a mathematical expression or a function. For example, to sort a table of products by price per unit, you could use the following query:
1 2 3 | SELECT product_name, unit_price, quantity_in_stock FROM products ORDER BY unit_price / quantity_in_stock DESC; |