SQL Exercises

MySQL: SQL HAVING Clause Exercises (With Answers)

0 Exercises
~0 min

This guide is specifically for MySQL syntax.

Learn SQL HAVING Clause with hands-on practice exercises. Each exercise includes the table schema, solution query, expected output, and detailed explanation.

What You'll Practice

These exercises cover HAVING Clause from basic to advanced concepts. Work through each problem to build your SQL skills.

Exercise 1

Question: Find departments with more than 5 employees.

Table Schema

CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100), department VARCHAR(50) );

Solution

SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY department HAVING COUNT(*) > 5;

Expected Output

| department | employee_count | |---|---| | Engineering | 8 |

Explanation

HAVING filters groups after aggregation. WHERE filters rows before grouping. Use HAVING with aggregate functions.

Exercise 2

Question: Find products with average rating above 4.0 and at least 10 reviews.

Table Schema

CREATE TABLE reviews ( id INT, product_id INT, rating DECIMAL(2,1) );

Solution

SELECT product_id, AVG(rating) AS avg_rating, COUNT(*) AS review_count FROM reviews GROUP BY product_id HAVING AVG(rating) > 4.0 AND COUNT(*) >= 10;

Expected Output

| product_id | avg_rating | review_count | |---|---|---| | 101 | 4.5 | 25 |

Explanation

Multiple conditions in HAVING are combined with AND/OR just like in WHERE clause.

Common Mistakes to Avoid

  • Forgetting to use proper syntax for HAVING Clause
  • Not considering NULL values in comparisons
  • Confusing similar operators or clauses

Related SQL Exercises

Continue practicing with these related topics:


MySQL-Specific Notes

This page covers MySQL syntax. Other databases may have different syntax for similar operations.

Related Content

From Our Blog

Ready for more practice?

Join SQL Mastery and get access to interactive exercises, quizzes, and more.