What's the difference between HAVING and WHERE?


#1

Question

What’s the difference between HAVING and WHERE, don’t they do the same thing?

Answer

While it’s true that both the HAVING and WHERE clauses are used to filter the results of a query, it’s important to know the difference in how they are used.

The WHERE clause is used when we want to filter the results of a query and extract only the records that fulfill a specified condition. For example, in the query: SELECT name, age FROM people WHERE age > 25; we are using the WHERE clause to select only the records of people who are older than 25 years of age.

The HAVING clause is used when we want to filter the results of a query that uses aggregate functions and a GROUP BY statement. Instead of checking the condition specified on each original row in the table, it checks the condition against the results after grouping the data . Here’s an example: SELECT employee_id, SUM(sale_amount) FROM transactions WHERE month = 'June' GROUP BY employee_id HAVING SUM(sale_amount) > 1000; In this query, we are getting the total sales of each employee during the month of June, and then we are using the HAVING clause to filter those results again to return only the employees who have more than $1000 in sales.