COUNT with a non-grouped column: Analyze the statement.\n“The SQL: SELECT Name, COUNT() FROM NAME_TABLE; counts the number of name rows and displays this total in a table with a single row and a single column.”

Difficulty: Easy

Correct Answer: Incorrect

Explanation:


Introduction / Context:
Mixing aggregated and non-aggregated columns in a SELECT list requires a GROUP BY clause in standard SQL. Without GROUP BY, only aggregate expressions are allowed (or all selected columns must be functionally dependent according to vendor-specific extensions). This question examines what happens when Name appears alongside COUNT() without GROUP BY.



Given Data / Assumptions:

  • ANSI SQL-92 behavior is assumed.
  • NAME_TABLE contains a column Name and multiple rows.
  • No vendor-specific “only_full_group_by” relaxations are assumed.


Concept / Approach:
The query SELECT Name, COUNT() FROM NAME_TABLE; is invalid in standard SQL because Name is neither aggregated nor grouped. Most engines will raise a syntax or semantic error (for example, “column must appear in the GROUP BY clause or be used in an aggregate function”). Furthermore, even if a vendor allowed it with non-standard behavior, the result would not be “a single row and a single column”—the SELECT list clearly has two columns. To correctly count all rows, use SELECT COUNT() FROM NAME_TABLE; To count per name, use SELECT Name, COUNT() FROM NAME_TABLE GROUP BY Name;



Step-by-Step Solution:

Goal: total rows → SELECT COUNT() FROM NAME_TABLE; → one row, one column.Goal: count per Name → SELECT Name, COUNT(*) FROM NAME_TABLE GROUP BY Name; → multiple rows, two columns.Therefore the original statement is incorrect on both validity and shape of the result set.Fix with appropriate GROUP BY or remove the non-aggregated column.


Verification / Alternative check:
Test in PostgreSQL or SQL Server—engine rejects the non-grouped, non-aggregated column alongside an aggregate.



Why Other Options Are Wrong:

  • “Correct” misstates the rules and the output shape.
  • Uniqueness of Name does not remove the need for GROUP BY in standard SQL.
  • “Autogrouping” is not part of the standard and is rarely supported.


Common Pitfalls:
Forgetting GROUP BY when mixing aggregate and non-aggregate columns; misreading result shapes.



Final Answer:
Incorrect

More Questions from Introduction to SQL

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion