MySQL Select DISTINCT multiple columns based on the uniqueness of a single row?

I am trying to understand what exactly this query does:

SELECT DISTINCT `state`, `state_name` FROM `geo` ORDER BY `state_name` ASC 

All I'm trying to do is select 2 columns (state and state_name), I want only unique rows that do not have duplicate values ​​for the state field. I don't care if there are duplicate values ​​in the state_name field.

Is my query checking both columns for uniqueness or just state?

+7
source share
2 answers

DISTINCT will return only single lines, therefore:

Is my query checking both columns for uniqueness or just state?

Both speakers

Instead, you can switch to GROUP BY.

 SELECT `state`, `state_name` FROM `geo` group by 'state', 'state_name' ORDER BY `state_name` ASC 
+18
source

It checks for unique combinations of states and state_name. Distinct works with all columns included in your selection list.

To include only unique state values, simply select a single state

+1
source

All Articles