Which of the following is not a valid SQL statement

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.

  1. a. SELECT MIN(pubdate) FROM books GROUP BY category HAVING pubid = 4;
  • This is a valid SQL statement.
  • GROUP BY is used to aggregate rows based on the category column, and MIN(pubdate) is applied to find the minimum publication date for each category.
  • The HAVING clause is used to filter the results after aggregation. Here, it correctly filters the result to show only groups where pubid = 4.
  1. b. SELECT MIN(pubdate) FROM books WHERE category = 'COOKING';
  • This is also a valid SQL statement.
  • The WHERE clause filters the rows where the category is ‘COOKING’.
  • MIN(pubdate) finds the earliest publication date among the filtered rows. This is syntactically correct.
  1. 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 condition customer# = 1005 in the orders table. It is a common and correct usage of the COUNT function.
  1. 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 each customer#, and GROUP BY customer# groups the rows by customer. However, the MAX(COUNT(customer#)) syntax is invalid because the COUNT(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 the COUNT function with GROUP BY and then apply MAX to 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.

Scroll to Top