lassence.net

Field notes from the AI frontier

Join on multiple SQL tables with fallback on first non-Null value

--- archive: codebook, 2020–2023 · topic: SQL ---

If you want to select the first non-Null value of several tables:

SELECT id,
       COALESCE(a.name, b.name, c.name) AS name
  FROM table1 AS a
  JOIN table2 AS b 
    ON a.id = b.id
  JOIN table3 AS c USING (id)
    ON a.id = c.id