Database Basics
An employee table (name, dept, salary) has eight rows, with salaries by department as follows: Sales 320, 280, 350; Dev 400, 310; Admin 260, 300; Planning 330. How many rows does SELECT dept, COUNT(*) FROM employee WHERE salary >= 300 GROUP BY dept HAVING COUNT(*) >= 2 return?
- A2 rows
- B3 rows
- C4 rows
Show answer and explanation
Answer: A. 2 rows
First, WHERE keeps only rows with a salary of 300 or more. Sales keeps two rows (320 and 350), Dev two (400 and 310), Admin one (300) and Planning one (330); Sales' 280 and Admin's 260 are removed. Next, GROUP BY gathers the rows by department into four groups with counts Sales 2, Dev 2, Admin 1 and Planning 1. Finally, HAVING COUNT(*) >= 2 keeps only groups with two or more rows, so the result is two rows: Sales and Dev. Counting without WHERE gives Sales 3, Dev 2, Admin 2 and Planning 1, and three rows would satisfy HAVING. The order in which WHERE works before grouping and HAVING works after it determines the result.
- A. Correct. Sales and Dev each still have two or more rows after WHERE filters, giving two rows.
- B. This counts before WHERE removes salaries below 300, so Admin wrongly remains.
- C. This is the number of groups before HAVING filters them.