Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is SQL GROUP BY a design flaw? [closed]

Tags:

sql

Why does SQL require that I specify on which attributes to group? Why can't it just use all non-aggregates?

If an attribute is not aggregated and is not in the GROUP BY clause then nondeterministic choice would be the only option assuming tuples are unordered (mysql kind of does this) and that is a huge gotcha. As far as I know, Postgresql requires that all attributes not appearing in the GROUP BY must be aggregated, which reinforces that it is superfluous.

  • Am I missing something or is this a language design flaw that promotes loose implementations and makes queries harder to write?
  • If I am missing something, what is an example query where group attributes can not be inferred?   
like image 451
Samuel Danielson Avatar asked Feb 22 '10 13:02

Samuel Danielson


People also ask

What are limitations of GROUP BY clause in SQL?

The SELECT statement used in the GROUP BY clause can only be used contain column names, aggregate functions, constants and expressions. SQL Having Clause is used to restrict the results returned by the GROUP BY clause.

Which statement is wrong about GROUP BY clause?

Answer: D. GROUP BY clause must contain all the columns appearing in the SELECT statement. It raises error because JOB is not a selected column.

Why we Cannot use WHERE with GROUP BY?

WHERE is used to filter records before any groupings take place that is on single rows. GROUP BY aggregates/ groups the rows and returns the summary for each group. HAVING is used to filter values after they have been groups.


1 Answers

You don't have to group by the exactly the same thing you're selecting, e.g. :

SQL:select priority,count(*) from rule_class group by priority  

PRIORITY COUNT(*) 70 1 50 4 30 1 90 2 10 4

SQL:select decode(priority,50,'Norm','Odd'),count(*) from rule_class group by priority

DECO COUNT(*) Odd 1 Norm 4 Odd 1 Odd 2 Odd 4

SQL:select decode(priority,50,'Norm','Odd'),count(*) from rule_class group by decode(priority,50,'Norm','Odd')

DECO COUNT(*) Norm 4 Odd 8

like image 197
John Ormerod Avatar answered Oct 07 '22 16:10

John Ormerod