What does GROUP BY do in SQL, and when would you use HAVING?

Prepare for the TJR Bootcamp Test with targeted questions and detailed explanations. Use mock exams to enhance understanding and boost your confidence. Gear up for success!

Multiple Choice

What does GROUP BY do in SQL, and when would you use HAVING?

Explanation:
Grouping collects rows that share the same values in one or more columns into distinct groups so you can compute an aggregate for each group. After those groups are formed, HAVING filters which groups to keep based on the results of those aggregates. For example, you might group by department and sum the sales in each department, then keep only departments where that total exceeds a threshold. A concrete query would be: select department, SUM(sales) as total_sales from orders group by department having SUM(sales) > 1000. Here, first the data is divided into departments, then total_sales is calculated for each, and finally groups with total_sales <= 1000 are removed by the HAVING clause. If you used a WHERE clause, you’d filter individual rows before grouping; HAVING is used specifically to filter after the aggregation has occurred, based on aggregate values.

Grouping collects rows that share the same values in one or more columns into distinct groups so you can compute an aggregate for each group. After those groups are formed, HAVING filters which groups to keep based on the results of those aggregates.

For example, you might group by department and sum the sales in each department, then keep only departments where that total exceeds a threshold. A concrete query would be: select department, SUM(sales) as total_sales from orders group by department having SUM(sales) > 1000. Here, first the data is divided into departments, then total_sales is calculated for each, and finally groups with total_sales <= 1000 are removed by the HAVING clause.

If you used a WHERE clause, you’d filter individual rows before grouping; HAVING is used specifically to filter after the aggregation has occurred, based on aggregate values.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy