Distinct values in multiple columns

oortcloud_domicile picture oortcloud_domicile · Aug 13, 2012 · Viewed 13.8k times · Source

I am trying to get distinct values for multiple columns in table.

for example if my table has COL1,COL2,COL3 as columns and I am running a query like

SELECT DISTINCT COL1, COL2, COL3 FROM TABLEx

but what happens is depending on the data in one of the columns I am getting duplicate values in two other columns. If COL1 has 40 unique values and COL2 has only 10 unique values and COL3 has 5 unique values. I am getting 40 rows of data where COL1 is unique and COL2/COL3 has duplicate values. How do i get DISTINCT values for each column and replace the duplicate values by null values. I am doing this only to get distinct values for my drop down lists in a web page. I can always perform seperate query for each field but I think it is not very effective. Any help as I how I approach this?

Answer

Mark Byers picture Mark Byers · Aug 13, 2012

I can always perform seperate query for each field

Yes! Do this!

but i think it is not very effective.

It's probably fine. You can improve performance by adding a separate index to each column. If you are still worried that it will be slow, measure it to be sure. If it turns out that it really is a problem then you may want to consider using caching.