Select the SQL query expression(s) that have completely valid syntax when grouping and...
Ion technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Select the SQL query expression(s) that have completely valid syntax when grouping and filtering aggregate transactions:
Show answer & explanation
In standard SQL, any column in the SELECT list that is not part of an aggregate function must be included in the GROUP BY clause. Option A correctly groups by customer_id and uses an aggregate function in both the SELECT and HAVING clauses, which is syntactically valid.
Step-by-step Derivation:
Step 1: Analyze Option A: SELECT customer_id, MAX(is_active) FROM transactions GROUP BY customer_id HAVING MAX(is_active). The non-aggregated column customer_id is in the GROUP BY clause. The HAVING clause uses an aggregate function MAX(is_active). In many SQL dialects (like PostgreSQL or MySQL), a boolean or numeric result in the HAVING clause is treated as a predicate. This is syntactically valid.
Step 2: Analyze Option B: SELECT customer_id, is_active FROM transactions GROUP BY customer_id HAVING MAX(is_active). This is invalid because is_active is in the SELECT list but is neither aggregated nor present in the GROUP BY clause.
Step 3: Analyze Option C: SELECT customer_id, DISTINCT is_active FROM transactions GROUP BY customer_id HAVING MAX(is_active). This is invalid because DISTINCT is a keyword that applies to the entire row set in the SELECT clause (e.g., SELECT DISTINCT ...), not to a specific column within a list of other columns.
Step 4: Analyze Option D: SELECT customer_id, MAX(is_active) AS is_active FROM transactions GROUP BY customer_id HAVING is_active. This is invalid in standard SQL because the HAVING clause is processed before the SELECT alias is defined; therefore, it cannot refer to the alias is_active to represent the aggregate result.