mardi 7 décembre 2021

SQL: Is there a better way than "COALESCE on two selects" to find the first non-null result in an OR clause?

Let's say I have this table:

ID LANG NAME DEFAULT
1 ENG Cinderella false
1 ENG The Ash Bride false
1 FRE Cendrillon true
1 GER Aschenputtel false

("Ash bride" is just fabrication that the same ID can have several names in the same language) The SQL query should return the name in the wanted language, if it doesn't exist, the default language.

So a search for the book title if your settings are in German (GER), the result should be "Aschenputtel", but if your settings are Spanish, they should return "Cendrillon".

This question brings up the same issue, but the answer suggests a double join through the name list, one for "lang='[preferred]'" and one for the default value, with a COALESCE to find the first non-null result. I am worried this would cause performance issues if the names list is long, when there cannot be a primary key (as there can be many names per language), and the question is quite old, so wonder if there is a method more along the likes of

SELECT NAME WHERE ID=1 and (LANG='SPA' OR DEFAULT=true)

and return the first non-null result of the OR-clause. Ideally, something like:

(not functional)
SELECT COALESCE(SELECT NAME WHERE ID=1 and (LANG='SPA' OR DEFAULT=true));

Anything? Or is a coalesce on a double select the only answer?

Aucun commentaire:

Enregistrer un commentaire