Ticker

6/recent/ticker-posts

Mysql COALESCE | very useful

Example: You have a relational model where one table serves as a lookup-table (tblDefault) with default values for another table (tblInstance). tblInstance contains NULL-values in the cells where defaults are to be retrieved from tblDefault. The following query will do the merging:

SELECT i.id, i.name, i.whatever,
COALESCE(i.specific1, d.default1) as val1,
COALESCE(i.specific2, d.default2) as val2
FROM tblInstance i
LEFT OUTER JOIN tblDefault d
ON i.foreignKey = d.primaryKey;

COALESCE selects the first non-null value of its arguments, and the left outer join makes sure all records from the left table are returned.

Oh, and whitespace matters in this case. Placing a space between COALESCE and ( produces a general syntax error.

Post a Comment

0 Comments