Learn to filter, sort, and group data in your queries.
The `WHERE`, `ORDER BY`, and `GROUP BY` clauses are fundamental tools for refining the results of a `SELECT` query. The `WHERE` clause is used for filtering. It is placed after the `FROM` clause and allows you to specify a condition that each row must meet to be included in the result set. You can use comparison operators (e.g., `=`, `>`, `<`), logical operators (`AND`, `OR`, `NOT`), and other operators like `BETWEEN`, `IN`, and `LIKE` to create complex filtering logic. For example, `WHERE amount > 100 AND order_date >= '2023-01-01'`. The `ORDER BY` clause is used for sorting the final result set. It is typically the last clause in a `SELECT` statement. You can specify one or more columns to sort by, and for each column, you can specify ascending (`ASC`, the default) or descending (`DESC`) order. For example, `ORDER BY order_date DESC, amount ASC` will sort the results primarily by the newest date, and for orders on the same date, it will sort them by the smallest amount. The `GROUP BY` clause is used to arrange identical data into groups. It follows the `WHERE` clause and precedes the `ORDER BY` clause. It is almost always used in conjunction with aggregate functions (`COUNT`, `SUM`, `AVG`, etc.) to produce a single summary row for each group. For instance, `GROUP BY customer_id` would create one group for each customer, allowing you to then calculate the `SUM(amount)` for each one.