I have some legacy code I’m maintaining and there’s a SQL query in there that I don’t understand. I’m hoping someone here can explain the purpose of this to me. The query looks like this:
select * from product_performance
where merchantid = 2151277 and clickday >= '2011-09-01'
group by null;
When I run this query without the group by null at the end, I get 44 rows. When I run it with the group by null, I get 1 row — the first row in the previous set. What is happening here, and what is the purpose of using this grouping?
It’s grouping the entire query by a constant value, which makes it pick a row effectively at random to return. You could get the same results using
LIMIT 1.Note that this idiom is not standard SQL, and may cause errors if you try it in other databases. In MySQL, you can disable this behavior by specifying the
ONLY FULL GROUP BYSQL mode. See the documentation for more details.OTOH,
LIMIT 1is non-standard as well, but more widely supported, and the same effect may be achieved in databases compliant with SQL:2008 with theFETCH ... ONLYclause. See this for details on that.