0

I have a question.

When I run this code on this dataset:

SELECT a.customerNumber, a.checkNumber 
FROM (SELECT customerNumber,
             checkNumber, min(paymentDate) as paymentDate 
      FROM payments 
      GROUP BYcustomerNumber) AS a;

I was wondering when I do not specify other columns that are not used in group by function. MySQL allows me to do that, but I rememberer that without specifying other columns, I would get this message, You tried to execute a query that does not include the specified expression 'one of column' as part of an aggregate function.

Am I missing some key points here? I think MySQL will automatically return the first entry of unspecified column without specifying this column in an aggregate function.

1
  • Side note: GROUP BY is not a function, it is a clause. Commented Dec 5, 2019 at 16:43

1 Answer 1

1

It depends whether server option sql_mode=ONLY_FULL_GROUP_BY is enabled or not. The option is enabled by default since version 5.7.

The documentation goes into great details about the behavior of the server when the option is disabled. In a nutshell:

the server is free to choose any value from each group, so unless they are the same, the values chosen are nondeterministic, which is probably not what you want.

Bottom line: always list all non-aggregated columns in the group by clause, regardless of the setting of your server; this is a best practice and the SQL standard, and the only way to get predictable results.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.