WHERE and HAVING are two keywords in SQL that are used to filter the results of a query. WHERE is used to filter the results based on the values in columns, and HAVING is used to filter the results based on the values in the resulting aggregated columns.
WHERE can be used to filter the results based on the values in any column in a table. For example, the following query will return all records from the customers table where the age field is greater than 18:
SQL
SELECT *
FROM customers
WHERE age > 18;
HAVING can be used to filter the results based on the values in the resulting aggregated columns. For example, the following query will return all records from the orders table where the total amount of orders is greater than $1,000:
SQL
SELECT order_id, SUM(amount) AS total
FROM orders
GROUP BY order_id
HAVING total > 1000;
The difference between WHERE and HAVING is that WHERE is used to filter the results based on the values in columns before the aggregated columns are calculated, and HAVING is used to filter the results based on the values in the resulting aggregated columns after they have been calculated.