Skip to content
Advertisement

How can I get this query when a column is NULL?

I’m trying to execute this query to get a list of all users, groups and emails, but my problem is when the user is not related to any group, so the column radcheck.id_group is = NULL, but I still want to list it.

SELECT 
    radcheck.username AS username, 
    group.name AS groupname, 
    group.id as gid, 
    useremail.email as email 
FROM useremail, group, radcheck 
WHERE 
    radcheck.username = useremail.username 
    AND group.id = radcheck.id_group;

How can I write it correctly?

Advertisement

Answer

Use explicit, LEFT JOINs:

SELECT 
    r.username AS username, 
    g.name AS groupname, 
    g.id as gid, 
    u.email
FROM useremail u
LEFT JOIN radcheck r ON r.username = u.username
LEFT JOIN group g ON g.id = r.id_group

It is also often a good practice to use table aliases: they make the query easier to read and maintain (and also allow self-joining tables when needed…).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement