Mysql – Is using SUM on multiple columns allowed in general SQL

MySQL

I had a question in my GATE Mock Test Paper that was as follows:

Which of the following can appear in position marked as [..]?

"Select [..] from R group by A, B"

I. SUM(C+D)

II. A, Min(C)

III. A,B, Min(C)

I answered all of the above, but my friends and answer key stated that only II and III are correct. I ran the query on mysql with no problem, and saw this code listed on few websites as well.

So is this query valid for general SQL, or it is implemented only by certain applications such as MySQL?

Best Answer

NOTE: I have no idea what 'GATE Mock Test Paper' is, or if that's supposed to have a bearing on the answer, so fwiw ...

As others have pointed out, technically all of the answers could be true ... though this will depend on the RDBMS (ie, flavor of SQL) as well as any configs/settings.


If the intention is to pick answers that are ANSI compliant, then I'd say 'III' is the correct answer since all non-aggregates should be part of the group by. Then again, if you start looking at some of the nitty-gritty ANSI details you'll find this requirement can sometimes be relaxed.

As you'll find out, most RDBMS products don't enforce such a strict standard: all non-aggregates being a member of the group by clause


As Michael Kutz has mentioned, without 'A' and/or 'B' in the select/projection list, answers 'I' and 'II' will provide some confusing answers. [And if you ever find yourself working in a real world RDBMS environment you'll find developers writing these types of queries all the time, but then not being able to describe what it is they're asking for let alone being able to explain the results they end up with.]

Again, answer 'III' is the only one I'd say can be clearly explained ... what I'm looking for ... the results I end up with.