Group By Errors in SQL Server

Did you ever face the following error while running a query which is containing GROUP BY Clause in the query :

 Column 'STUDENTS.ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I got the above error while I was trying to run the following query  in SQL Server.

SELECT  SUBJECT, ID,NAME FROM STUDENTS GROUP BY SUBJECT

GROUP BY statement in SQL Server comes with set of predefined rules. Above statement is violating GROUP BY clause rules.


That is all the columns which are present in SELECT list should present in GROUP BY List of the query.

In the above query SELECT list contains SUBJECT,ID,NAME columns. Where as GROUP BY list contains only SUBJECT. In GROUP BY Clause ID, NAME are missing.

So, to correct this error we should include all the columns which should maintain the same column list in SELECT and GROUP BY.

The correct query for the above scenario would be:

SELECT  SUBJECT, ID,NAME FROM STUDENTS GROUP BY SUBJECT, ID,NAME

This entry was posted in . Bookmark the permalink.

Leave a reply