Sobes.tech
Junior — Middle

Can you explain the purpose and working principle of the HAVING operator in SQL queries?

sobes.tech AI

Answer from AI

The HAVING operator in SQL is used to filter groups of data formed with GROUP BY. Unlike WHERE, which filters rows before grouping, HAVING is applied after grouping and allows setting conditions on aggregate functions (e.g., COUNT, SUM, AVG).

For example, if you want to select customers with more than 5 orders:

SELECT customer_id, COUNT(*) AS orders_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 5;

Here, HAVING filters customer groups where the number of orders exceeds 5.

Thus, HAVING allows restricting the results of aggregated data based on specific conditions.

Can you explain the purpose and working principle of… - sobes.tech