SQL: Can I have clauses in Groupby that don’t appear in Select?

Asked

Viewed 177 times

1

I know I can’t have clauses in select that don’t appear in Group By. But is it possible otherwise? For example:

Select B
From Table
Group By A,B

1 answer

2

I’ll answer for the two Sgbds in the question tags:

Group By gathers a set of records and produces a summary (a single record) for each of the identified groups. Groups are identified on the basis of one or more columns or expressions included in the Group By clause.

Both Mysql and Oracle allow your SELECT clause to omit columns included in Group By. For example, this instruction will work on both Dbms.

SELECT coluna1, COUNT(1)
FROM tbl_tabela
GROUP BY coluna1, coluna2

(The usefulness of an expression like the previous one can be questioned, of course. Since you lose essential information to identify the group created for each of the lines in the result.)

To top it off, and because it’s the DBMS I’ve been using lately, Sql Server, according to the information on manual, also allows Group By expressions to contain table columns, derived tables, FROM clause views. However, Group By columns do not need to appear in the SELECT clause.

A final comment regarding your question, Mysql allows that in your SELECT clause include columns that are not in GROUP BY. More info on the manual

  • Thank you! And as for the default SQL, this is also possible?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.