If I have a table
CREATE TABLE users (
id int(10) unsigned NOT NULL auto_increment,
name varchar(255) NOT NULL,
profession varchar(255) NOT NULL,
employer varchar(255) NOT NULL,
PRIMARY KEY (id)
)
and I want to get all unique values of profession
field, what would be faster (or recommended):
SELECT DISTINCT u.profession FROM users u
or
SELECT u.profession FROM users u GROUP BY u.profession
?
If you have an index on
profession
, these two are synonyms.If you don't, then use
DISTINCT
.GROUP BY
inMySQL
sorts results. You can even do:and get your professions sorted in
DESC
order.DISTINCT
creates a temporary table and uses it for storing duplicates.GROUP BY
does the same, but sortes the distinct results afterwards.So
is faster, if you don't have an index on
profession
.If the problem allows it, try with EXISTS, since it's optimized to end as soon as a result is found (And don't buffer any response), so, if you are just trying to normalize data for a WHERE clause like this
A faster response would be:
This isn't always possible but when available you will see a faster response.
well distinct can be slower than group by on some occasions in postgres (dont know about other dbs).
tested example:
http://www.pgsql.cz/index.php/PostgreSQL_SQL_Tricks_I
so be careful ... :)