At least in my time with MSSQL, seeing `SELECT DISTINCT ...` was a red flag. It nearly always meant something needed to be refactored using GROUP BY.
At least in my time with MSSQL, seeing `SELECT DISTINCT ...` was a red flag. It nearly always meant something needed to be refactored using GROUP BY.
is equivalent to
select distinct userid, name from users
It's easy to add another column to the "distinct" based query and change the behavior accidentally. With the "group by" query, you'd get an error saying that the new column needs to be either aggregated or added to the group by.
It still leaves room to determine how and when to achieve the DISTINCT property, perhaps even doing no work at all.
* It can do a sort+unique or a hash, depending on cardinality, availability of memory, and a few other factors.
* It can push down a distinct or pull up a distinct, resulting in a faster plan.
* If there is another part of the plan that already implies distinct, like a GROUP BY, then it doesn't need to do any work at all. (Or similarly, if you're doing a distinct on a primary key).