Which of the following statements are TRUE about an SQL query? P : An SQL…

2012

Which of the following statements are TRUE about an SQL query?

P : An SQL query can contain a HAVING clause even if it does not have a GROUP BY clause

Q: An SQL query can contain a HAVING clause only if it has a GROUP BY clause

R : All attributes used in the GROUP BY clause must appear in the SELECT clause

S : Not all attributes used in the GROUP BY clause need to appear in the SELECT clause

  1. A.

    P and R

  2. B.

    P and S

  3. C.

    Q and R

  4. D.

    Q and S

Attempted by 715 students.

Show answer & explanation

Correct answer: B

Key insight: the HAVING clause can be used without GROUP BY, and GROUP BY attributes do not all have to appear in the SELECT list.

  • HAVING without GROUP BY: HAVING filters groups created by GROUP BY. If GROUP BY is omitted, SQL treats the entire result as a single group, so HAVING can still be used with aggregate expressions to filter that single-group result. (Behavior can vary slightly across SQL dialects, but this is the standard interpretation.)

  • GROUP BY vs SELECT: It is not required that every attribute listed in GROUP BY also appear in the SELECT list. The rule is that any non-aggregated column in SELECT must appear in GROUP BY; however, you may group on columns and return only aggregates in SELECT.

  • Conclusion: The true statements are the one saying HAVING can be used without GROUP BY and the one saying not all GROUP BY attributes need to appear in SELECT. The statements claiming HAVING is only allowed with GROUP BY and that all GROUP BY attributes must appear in SELECT are false.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir