Subquery with HAVING EXISTS
Subquery with HAVING EXISTS is a SQL statement in the Subqueries category. HAVING with EXISTS filters groups based on the existence of rows in a subquery. The syntax is SELECT col, agg_func(col) FROM t GROUP BY col HAVING EXISTS (SELECT 1 FROM t2 WHERE condition);. It returns group-filtered result. A typical example: SELECT department, COUNT(*) AS employee_count, AVG(salary) AS avg_salary FROM employees e GROUP BY department HAVING EXISTS ( SELECT 1 FROM projects p WHERE p.department = e.department AND p.budget > 100000 ); -- Only departments that have a high-budget project -- Without HAVING EXISTS, you would need: -- 1. Subquery in WHERE (cant access aggregates) -- 2. JOIN with GROUP BY (risk of duplication) -- EXISTS in HAVING is cleaner for… A close relative is Scalar Subquery, which a subquery that returns a single value (one row, one column). Can be used in SELECT, WHERE, HAVING clauses.