Click here to Skip to main content
15,881,248 members
Articles / DevOps
Tip/Trick

SQL CASE WHEN condition THEN NumericColumn ELSE 0 END

Rate me:
Please Sign up or sign in to vote.
4.93/5 (9 votes)
7 Jun 2017CPOL 38.9K   5   4
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)


Written By
Business Analyst Linden
Lithuania Lithuania
I'm a lawyer in a law firm. Programing is my hobby.

Comments and Discussions

 
GeneralSQL Server is an exception Pin
Suvendu Shekhar Giri8-Jun-17 21:22
professionalSuvendu Shekhar Giri8-Jun-17 21:22 
GeneralRe: SQL Server is an exception Pin
Don V Nielsen9-Jun-17 7:42
Don V Nielsen9-Jun-17 7:42 
GeneralRe: SQL Server is an exception Pin
Niemand2511-Jun-17 23:59
professionalNiemand2511-Jun-17 23:59 
GeneralRe: SQL Server is an exception Pin
Member 1252223012-Jun-17 3:37
Member 1252223012-Jun-17 3:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.