> MySQL: Distinct in a query to make it faster?

MySQL: Distinct in a query to make it faster?

Posted at: 2014-12-18 
Are you selecting all 30.000 rows? Or at least all the distinct rows?

Or are you only asking for some of them with a WHERE clause?

Are you sorting the results with an ORDER BY clause?

If you are using a WHERE or ORDER BY, then most likely you will need an index on the column(s) that you specify in where and/or order by.

Even if you are getting all rows, an index on the column you are using in the DISTINCT clause should speed things up as well.

If you are getting all rows, do you really need to? Do you actually use them all, or just some of them. If only some, then ask for only the ones you need.

An index can speed up a query more than any other optimization, sometimes by many orders of magnitude. So I would start there.

Is it possible to make a query so that it will change the run time depending on if we use "distinct" or not? An example would be great!

My largest table Im able to run on is 30.000 rows, and if I use distinct on one of the columns, it gets down to 8.000. I have tried plenty of operators that I though would go faster, but it didnt. You can make an example just using t1 and c1 etc, if it is possible at all :)