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
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 Correct Answer Q and R
The correct answer is option 3
EXPLANATION:
GROUP BY clause:
- The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".
- The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
Example:
SELECT COMPANY, COUNT(*)
FROM PRODUCT_MAST
GROUP BY COMPANY
Therefore all attributes used in the GROUP BY clause must appear in the SELECT clause
HAVING clause:
- HAVING clause is used to specify a search condition for a group or an aggregate.
- Having is used in a GROUP BY clause.
- If you are not using GROUP BY clause then you can use HAVING function like a WHERE clause.
Syntax:
SELECT column1, column2
FROM table_name
WHERE conditions
GROUP BY column1, column2
HAVING conditions
ORDER BY column1, column2;
Example:
SELECT COMPANY, COUNT(*)
FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING COUNT(*)>2;
Therefore an SQL query can contain a HAVING clause only if it has a GROUP BY clause.
Confusion Points
The answer is as per standard SQL
মোঃ আরিফুল ইসলাম
Feb 20, 2025