Aggregates & GROUP BY · Question 20 · Hard

Aggregates & GROUP BY question 20

Table Sales(sale_id, rep, region, amount) has the regions North, South and West. Compare:
Q1: SELECT region, SUM(amount) FROM Sales WHERE region <> 'West' GROUP BY region;
Q2: SELECT region, SUM(amount) FROM Sales GROUP BY region HAVING region <> 'West';
Which statement is correct?

  1. Q2 is an error, because HAVING may contain only aggregate functions
  2. Q1 returns North and South, but Q2 also returns West with a NULL total
  3. Q2 returns different totals, because HAVING changes which rows are added up
  4. Both return the same rows; Q1 discards West rows before grouping, Q2 discards the West group after it
Answer and explanation

Answer: D. Both return the same rows; Q1 discards West rows before grouping, Q2 discards the West group after it

Explanation: HAVING may test a grouping column, so Q2 is valid. Removing the West rows before grouping or the West group after grouping leaves the same North and South rows with the same totals; Q1 simply does less work.

Previous: Table Sales: sale_id | rep | region | amount 1 | Asif | North | 400 2 | Bina |…

Practise aggregates & group by

Try a fresh set of aggregates & group by questions with an explanation after every answer, free and without signing up: Aggregates & GROUP BY practice. Or sit a full placement mock test.

More aggregates & group by questions

More sql practice

Subqueries & CTEs · Window Functions · NULL Handling · SQL Functions & CASE · UNION, INTERSECT & EXCEPT · Tables, Keys & Constraints · DML & Transactions · SELECT, WHERE & ORDER BY

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge