Which of the following is not a valid SQL statement?
a. SELECT MIN(pubdate)
FROM books
GROUP BY category
HAVING pubid = 4;
b. SELECT MIN(pubdate)
FROM books
WHERE category = ‘COOKING’;
c. SELECT COUNT(*)
FROM orders
WHERE customer# = 1005;
d. SELECT MAX(COUNT(customer#))
FROM orders
GROUP BY customer#;
The Correct Answer and Explanation is :
The correct answer is:
d. SELECT MAX(COUNT(customer#)) FROM orders GROUP BY customer#;
Explanation:
Let’s break down why option d is invalid and why the others are valid.
- a.
SELECT MIN(pubdate) FROM books GROUP BY category HAVING pubid = 4;
- This is a valid SQL statement.
GROUP BYis used to aggregate rows based on thecategorycolumn, andMIN(pubdate)is applied to find the minimum publication date for each category.- The
HAVINGclause is used to filter the results after aggregation. Here, it correctly filters the result to show only groups wherepubid = 4.
- b.
SELECT MIN(pubdate) FROM books WHERE category = 'COOKING';
- This is also a valid SQL statement.
- The
WHEREclause filters the rows where thecategoryis ‘COOKING’. MIN(pubdate)finds the earliest publication date among the filtered rows. This is syntactically correct.
- c.
SELECT COUNT(*) FROM orders WHERE customer# = 1005;
- This is a valid SQL statement.
- The
COUNT(*)function counts the number of rows that match the conditioncustomer# = 1005in theorderstable. It is a common and correct usage of theCOUNTfunction.
- d.
SELECT MAX(COUNT(customer#)) FROM orders GROUP BY customer#;
- This is not valid because it misuses aggregation functions.
COUNT(customer#)is an aggregate function that counts the number of orders for eachcustomer#, andGROUP BY customer#groups the rows by customer. However, theMAX(COUNT(customer#))syntax is invalid because theCOUNT(customer#)is already an aggregated value.- You cannot nest aggregate functions like
MAX(COUNT(...)). If you want the maximum count of orders for a customer, you should first apply theCOUNTfunction withGROUP BYand then applyMAXto the result of that aggregation. The correct query would be:sql SELECT MAX(order_count) FROM (SELECT COUNT(customer#) AS order_count FROM orders GROUP BY customer#) AS subquery;
In summary, the error in option d is that it incorrectly attempts to nest two aggregation functions (MAX and COUNT) in a way that is not allowed in SQL syntax.