I've got (key, value) pairs stored in two different tables - company_settings and branch_settings. A key can exist in none, one or both of the tables.
In case the key exists in both tables, I'd like to use the value stored in the branch_settings table. Otherwise, if available, I'd like to fall back to the value stored in the company_settings table.
company_settings
-------------------------
| key | value
-------------------------
| key.A | 4 |
-------------------------
| key.B | 5 |
-------------------------
branch_settings
-------------------------
| key | value
-------------------------
| key.A | 1 |
-------------------------
So, if I query for key.A the result should be 1 since key.A exists in both tables and I want to give higher precedence to records from branch_settings table.
If I query for key.B the result should be 5 since key.B exists only in company_settings table.
COALESCEis brilliant. However, I don't understand what(VALUES ('key.A')) AS prm (key)is doing? – Code Poet Dec 20 '17 at 20:21JOINbe just as efficient as the subqueries? In which case, I'd favor the improved readability and flexibility of theJOIN. – jpmc26 Dec 21 '17 at 04:00COALESCEmatched in ? – user2616355 Jun 03 '21 at 22:02CASEexpression in the SELECT list or a simple check, eg:SELECT ..., (b.value IS NOT NULL) AS value_comes_from_b ...– ypercubeᵀᴹ Jun 05 '21 at 23:07