65.9K
CodeProject is changing. Read more.
Home

SQL CASE WHEN condition THEN NumericColumn ELSE 0 END

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.93/5 (9 votes)

Jun 8, 2017

CPOL
viewsIcon

41236

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:

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):

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.