Q

Columns in the SELECT not in the GROUP BY

I have an SQL query where I am using the SUM function with the GROUP BY clause. I need to select a couple more columns from the table without adding those columns in the GROUP BY clause.

I have an SQL query where I am using the SUM function with the GROUP BY clause. Now what I require is that I need to select a couple of more columns from the table without adding those columns in the GROUP BY clause. Is there any way I can do this?

The answer is yes, but only in a very certain way.

Let's imagine that this is your current query:

 select foo , sum(bar) as sumbar from qux group by foo

Now, we want to add two more columns—let's call them other1 and other2—but we don't want to add them to the GROUP BY, because we still want only one row per foo in the results.

The very certain and only way that this will be allowed is by ensuring that the two new columns are inside aggregate functions.

Here's one example of many possibilities:

 select foo , sum(bar) as sumbar , max(other1) as maxcol1 , avg(other2) as avgcol2 from qux group by foo

What is NOT ALLOWED is to put "naked" columns (not inside aggregate functions) into the SELECT clause but leave them out of the GROUP BY clause:

 select foo , sum(bar) as sumbar , other1 , other2 from qux group by foo

This is invalid syntax, and only MySQL will run it (although they do warn you, in GROUP BY and HAVING with Hidden Fields, that results can be unpredictable).

This was last published in April 2007

Dig Deeper on Oracle and SQL

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close