This is going to be a rant about mysql, please do not be offended!
I want everyone who writes SQL for moodle to consider the following table, 'foo':
+------+------+------+
| f1 | f2 | f3 |
+------+------+------+
| 1 | 2 | 3 |
| 1 | 4 | 5 |
| 1 | 6 | 7 |
+------+------+------+
Now, if we do
SELECT * FROM foo GROUP BY f1;
What do we expect to see returned? f1 is going to be 1, sure. What about in f2 and f3? Postgres doesn't allow this query; it says:
ERROR: column "f1" must appear in the GROUP BY clause or be used in an aggregate function
Which makes sense to me - what else would we expect to see in the other columns? f1 is distinct, but f2 and f3 have three results between them that need to fit in our 1 result from f1.
If we replaced f2 and f3 with aggregate functions that returned exactly 1 result, it would be fine. Example:
SELECT f1,count(f2),sum(f3) FROM foo GROUP BY f1;
it makes perfect sense.
Now, mysql happily allows the first query and doesn't complain about it, and this piqued my curiosity - what would it actually return? The answer:
+------+------+------+
| f1 | f2 | f3 |
+------+------+------+
| 1 | 2 | 3 |
+------+------+------+
Conclusion - mysql happily allows this query, even though it doesn't make sense, and not only does it not complain, it just randomly decides to return whatever the **** it wants! In this case, the first row of results for f2 and f3. Now, I'm not convinced that this is actually the result we want most of the time - surely it's better to complain bitterly rather than do it silently and return data we don't actually want?
Penny (viva la postgres!