Let's say:
I want to query colA, colB and colC in my table.
I want to see DISTINCT values but I don't want colA to be a criteria for distinction.
Omitting colA isn't an option.
What's the best way to structure that query?
Adding the DISTINCT keyword to a SELECT query causes it to return only unique values for the specified column list so that duplicate rows are removed from the result set.
Yes, DISTINCT works on all combinations of column values for all columns in the SELECT clause.
Well, GROUP BY and DISTINCT have their own use. GROUP BY cannot replace DISTINCT in some situations and DISTINCT cannot take place of GROUP BY. It is as per your choice and situation how you are optimizing both of them and choosing where to use GROUP BY and DISTINCT.
Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns.
There are two cases here. Let's say you have the data
A B C (columns)
a b c1
a b c2
Taking distinct values of A, B gives just one result (a,b), with two values for column C. So the question is do you want to see all values of C or just one value for each distinct value of columns A and B?
If you want to see just one value of C, then you can write
SELECT A, B, MAX(C) FROM YourTable
GROUP BY A, B
On the other hand, if you want to see all values for C then
SELECT DISTINCT A, B, C FROM YourTable WHERE ROW(A,B) IN
(SELECT A, B FROM YourTable
GROUP BY A, B)
gives you that. This last alternative is needed if there are other columns in the table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With