0

I have a multi-lingual table for the country like this:

--------------------------------------------------------------------
 country | lang | name
--------------------------------------------------------------------
 US      | en-US | United States
--------------------------------------------------------------------
 US      | fr    | États-Unis
--------------------------------------------------------------------
 US      | ar | الولايات المتحدة
--------------------------------------------------------------------
 US      | de |
--------------------------------------------------------------------

I want to select the field "name" for the country 'US' for the lang 'de' but if the name field is empty fallback to the language 'en-US'.

so will a query like this should be correct:

select name from countries where country='US' and name<>"" and lang in ('de', 'en-US')

I really need optimized query.

1 Answer 1

1

Here is a way to get the answer:

select name
from countries
where country = 'US' and name<>"" and lang in ('de', 'en-US')
order by lang = 'de' desc
limit 1;

If you have an index on country, lang, name then it should perform well.

EDIT:

This might perform better with the same index:

select coalesce((select name
                 from countries
                 where country = 'US' and name <> "" and lang = 'de'
                ),
                (select name
                 from countries
                 where country = 'US' and name <> "" and lang = 'en-US'
                )
               ) as name

EDIT II:

A standard SQL approach similar to the first is:

select (case when sum(case when lang = 'de' then 1 else 0 end) > 0
             then max(case when lang = 'de' then name end)
             else max(name)
        end) 
from countries
where country = 'US' and name <> "" and lang in ('de', 'en-US');

An aggregation on two rows should be quite fast in any database. However, the coalesce() method should essentially just be two index lookups.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks Gordon for your answers, if I am looking for sql portability not only mysql, what would be the first query, and for the second query does coalesce sql protable, I know my question titled for mysql only but since I am learning would be interested to know about portability. I know for mssql it uses the "top" instead of "limit".
@daliaessam . . . The second query is standard SQL and should work in most databases. The first uses limit; different databases have different ways of implementing this functionality.

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.