Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / DevOps

SQL CASE WHEN condition THEN NumericColumn ELSE 0 END

4.93/5 (9 votes)
7 Jun 2017CPOL 41.2K  
Be careful with CASE WHEN when dealing with numeric columns and using zero literal

Recently I encountered a very interesting and hard to reproduce bug when using SQLite statement CASE WHEN. Many if not most SQL developers would consider the following (simplified) statement perfectly OK:

SQL
SELECT (CASE WHEN TableName.LogicCondition > 0 THEN TableName.NumericColumn ELSE 0 END) AS FilteredValue1, 
(CASE WHEN TableName.LogicCondition > 0 THEN 0 ELSE TableName.NumericColumn END) AS FilteredValue2 
FROM TableName WHERE TableName.SomeCondition = 1;

However, it is not OK at all at least if used in SQLite (haven't checked other SQL versions might also be affected).

The problem is the type of the FilteredValue columns returned by this query. If the first CASE WHEN execution ends with the result 0, the entire column type will be set as integer ('cause 0 is integer literal), which in turn leads to the truncation of fractional parts of the numeric column values. The first CASE WHEN hit depends on row order within the table and some specifics of the SQL engine, which leads to "random errors", i.e., very hard to reproduce.

The same holds for aggregation, e.g.: SUM(CASE WHEN TableName.LogicCondition > 0 THEN TableName.NumericColumn ELSE 0 END) sometimes will return an invalid result.

The solution - use 0.0 (numeric literal) instead of 0 (integer literal):

SQL
SELECT (CASE WHEN TableName.LogicCondition > 0 THEN TableName.NumericColumn ELSE 0.0 END) AS FilteredValue1,
(CASE WHEN TableName.LogicCondition > 0 THEN 0.0 ELSE TableName.NumericColumn END) AS FilteredValue2
FROM TableName WHERE TableName.SomeCondition = 1;

P.S.: I would be grateful if someone could check if the same problem occurs on other SQL implementations, especially MySQL.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)