0
0
PostgreSQLquery~5 mins

HAVING for filtering groups in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the HAVING clause in SQL?
The HAVING clause is used to filter groups created by GROUP BY based on a condition, similar to how WHERE filters rows before grouping.
Click to reveal answer
beginner
How does HAVING differ from WHERE in SQL queries?
WHERE filters individual rows before grouping, while HAVING filters groups after aggregation is done.
Click to reveal answer
intermediate
Write a simple SQL query using HAVING to find departments with more than 5 employees.
SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY department HAVING COUNT(*) > 5;
Click to reveal answer
intermediate
Can HAVING be used without GROUP BY? Explain.
Yes, HAVING can be used without GROUP BY to filter aggregated results over the entire table, but it is less common.
Click to reveal answer
advanced
Why might you get an error if you use a column in HAVING that is not in GROUP BY or an aggregate function?
Because HAVING filters groups, any column used must be part of the grouping or an aggregate; otherwise, SQL doesn't know how to evaluate it for each group.
Click to reveal answer
What does the HAVING clause filter in an SQL query?
AGroups created by GROUP BY
BIndividual rows before grouping
COnly NULL values
DColumns in SELECT clause
Which clause is used to filter rows before grouping?
AHAVING
BGROUP BY
CORDER BY
DWHERE
Which of these is a valid use of HAVING?
AHAVING name = 'John'
BHAVING salary > 50000
CHAVING COUNT(*) > 10
DHAVING age < 30
Can HAVING be used without GROUP BY?
AYes, to filter aggregated results over the whole table
BNo, it always requires GROUP BY
COnly in MySQL
DOnly with ORDER BY
What happens if you use a non-aggregated column in HAVING that is not in GROUP BY?
AQuery runs normally
BSQL error occurs
CColumn is ignored
DResults are duplicated
Explain the difference between WHERE and HAVING clauses in SQL with an example.
Think about when filtering happens in the query process.
You got /3 concepts.
    Describe a scenario where HAVING is necessary and WHERE cannot be used.
    Consider filtering groups by their total or average.
    You got /3 concepts.