2

I have two tables, one is for individuals and the other is for their company.

Each table has a column for locale, this is mandatory for the company, but not for the individual. The idea seems to be that if the individual doesn't set a preference, they are assumed to be in the locale of their company.

I would like to select the locale for the individual, using the company default if the individual locale is null and I thought of doing the following (which I don't think is possible in MySql)...

SELECT
    ISNULL(individual.Locale, company.Locale) `Locale`
FROM
    individual
INNER JOIN
    company ON company.CompanyId = individual.CompanyId
WHERE
    individual.IndividualId = 1

Is there a nice way to do this - or am I just going to end up sending both Locale's back and making the decision in the code?

3 Answers 3

4

You can use the COALESCE() function which returns the first non-NULL value among its arguments. This function can also be used in most other RDBMS like SQL-Server, Oracle 9, Postgres 8:

SELECT
    COALESCE(individual.Locale, company.Locale) AS Locale
FROM
    individual
INNER JOIN
    company ON company.CompanyId = individual.CompanyId
WHERE
    individual.IndividualId = 1
Sign up to request clarification or add additional context in comments.

Comments

3

You pretty much had it, what you want is IFNULL()

SELECT
    IFNULL(individual.Locale, company.Locale) `Locale`
FROM
    individual
INNER JOIN
    company ON company.CompanyId = individual.CompanyId
WHERE
    individual.IndividualId = 1

1 Comment

+1 as this is a great answer - I had to go with COALESCE in the end as it will work on other databases too and performs about the same unless you use it as part of a sub-query.
2

Try the CASE...WHEN...THEN statement

SELECT 
    (CASE
       WHEN individual.Locale IS NULL THEN company.Locale
       ELSE individual.Locale
    END) 'Locale'
FROM
    individual
INNER JOIN
    company ON company.CompanyId = individual.CompanyId
WHERE
    individual.IndividualId = 1

2 Comments

This will not work, Change it into: CASE WHEN individual.Locale IS NULL THEN ...
Yes, because CASE expression WHEN checks for equality and NULL=NULL is not True (unfortunately :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.