DISTINCT works globally, on all the columns you SELECT. Here you're getting distinct pairs of (sp_id, company_name) values, but the individual values of each column may show duplicates.
That being said, it's extremely deceiving that MySQL authorizes the syntax SELECT DISTINCT(company_name), sp_id
when it really means SELECT DISTINCT(company_name, sp_id)
. You don't need the parentheses at all, by the way.
Edit
Actually there's a reason why DISTINCT(company_name), sp_id
is valid syntax: adding parentheses around an expression is always legal although it can be overkill: company_name
is the same as (company_name)
or even (((company_name)))
. Hence what that piece of SQL means is really: “DISTINCT [company_name in parentheses], [sp_id]”. The parentheses are attached to the column name, not the DISTINCT keyword, which, unlike aggregate function names, for example, does not need parentheses (AVG sp_id
is not legal even if unambiguous for a human reader, it's always AVG(sp_id)
.)
For that matter, you could write SELECT DISTINCT company_name, (sp_id)
or SELECT DISTINCT (company_name), (sp_id)
, it's exactly the same as the plain syntax without parentheses. Putting the list of columns inside parentheses – (company_name, sp_id)
– is not legal SQL syntax, though, you can only SELECT “plain” lists of columns, unparenthesized (the form's spell-checker tells me this last expression is not an English word but I don't care. It's Friday afternoon after all).
Therefore, any database engine should accept this confusing syntax :-(