Selecting DISTINCT where not null in MySQL

10,277

Solution 1

SELECT DISTINCT Name, ID FROM TestTable where Name <> ''
union all
SELECT Name, ID FROM TestTable where Name = ''

Solution 2

Only slight improvement I can think of would be:

SELECT DISTINCT Name, ID FROM TestTable where Name <> ''
union all
SELECT '', ID FROM TestTable where Name IS NULL OR Name = ''
Share:
10,277
Luke Shaheen
Author by

Luke Shaheen

Updated on June 05, 2022

Comments

  • Luke Shaheen
    Luke Shaheen almost 2 years

    I've got a table that has, for example, ID and Name.

    There are multiple rows that contain blank names, but there also can be multiple rows with the same name. I'd like to select all IDs, counting each name only once (DISTINCT), but selecting ALL of the blanks.

    The following query naturally only selects ONE blank name. How can I select all the distinct names plus all of the blank names?

    SELECT DISTINCT Name, ID
    FROM TestTable
    
  • Luke Shaheen
    Luke Shaheen almost 12 years
    Can you explain the <>? I can figure it out, but would like to see a written explanation =)
  • Joseph Victor Zammit
    Joseph Victor Zammit almost 12 years
    @John not equal to, same as != in many programming languages