SQL HAVING Clause-interview
Q1. What is the purpose of the HAVING clause in SQL?
It filters grouped records after aggregation, unlike WHERE which filters before grouping.
Q2. Can HAVING be used without GROUP BY?
Yes, but it’s rarely used alone. HAVING without GROUP BY filters aggregated results for the entire table.
SELECT COUNT(*) AS total_students FROM Students HAVING COUNT(*) > 10;
Q3. Difference between WHERE and HAVING?
- WHERE filters rows before aggregation.
- HAVING filters groups after aggregation.
Q4. Can we use multiple conditions in HAVING?
Yes, using AND/OR.
SELECT department, SUM(salary) AS total_salary
FROM Employees
GROUP BY department
HAVING SUM(salary) > 50000 AND COUNT(*) > 5;
Q5. Give a practical example of HAVING in SQL.
SELECT course_name, COUNT(student_id) AS total_students
FROM Courses
GROUP BY course_name
HAVING COUNT(student_id) > 20;
Returns courses with more than 20 students.