Tuesday, April 3, 2012

select distinct sql vs select with group by

Yesterday while trying to modify a query I had a bit of a realization about queries with DISTINCT in them and it seems simple and I probably even realized it before and forgotten, it wasn't a ground breaking realization but useful.

SELECT DISTINCT column_name FROM table

is basically the same as

SELECT column_name FROM table GROUP BY column_name

This was taken from one of my favourite query types, the nested query using union logic:

SELECT table.* FROM table WHERE id in (SELECT DISTINCT id FROM maybe_other_table WHERE lots_of_stuff)

That's it, I could probably comment on how they are implemented but you can search the internet for that, I usually just see what stackoverflow has to say about it, here you go http://stackoverflow.com/questions/581521/whats-faster-select-distinct-or-group-by-in-mysql

Peace.

No comments:

Post a Comment