How to use “order by” and “where” together in MySQL?
In MySQL, the ORDER BY and WHERE clauses can be used together to sort and filter data.
The grammar is as follows:
SELECT 列名
FROM 表名
WHERE 条件
ORDER BY 列名 [ASC|DESC];
The WHERE clause is used to filter data that meet certain conditions, while the ORDER BY clause is used to sort the results by a specified column. ASC signifies ascending order (default), while DESC signifies descending order.
For example, suppose there is a table named “customers” with columns like “customer_id,” “customer_name,” and “customer_age.” We can use the following query to filter customers who are 18 years or older and sort them in ascending order by name:
SELECT customer_name, customer_age
FROM customers
WHERE customer_age >= 18
ORDER BY customer_name ASC;
In the above example, the WHERE clause is used to filter customers who are 18 years old or older, while the ORDER BY clause is used to sort the results in ascending order by name.