Read more

MySQL: Select a default value for NULL fields

Arne Hartherz
November 30, 2010Software engineer at makandra GmbH

If you need to do calculations inside the database and can not use Ruby objects you may run into problems when encountering fields with NULL values:

SELECT foo, bar, foo - bar AS baz FROM plop;
+-----+------+------+
| foo | bar  | baz  |
+-----+------+------+
|  30 |   20 |   10 |
|  30 | NULL | NULL |
+-----+------+------+
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Solve this by using IFNULL: it returns the selected value if present and a given alternative if it would select NULL:

SELECT foo, bar, foo - IFNULL(bar, 0) AS baz FROM plop;
+-----+------+-----+
| foo | bar  | baz |
+-----+------+-----+
|  30 |   20 |  10 |
|  30 | NULL |  30 |
+-----+------+-----+
Posted by Arne Hartherz to makandra dev (2010-11-30 10:49)