Search code examples
sqlsqlitecaseshort-circuiting

CASE expression that does NOT have short-circuit evaluation?


I recently began teaching myself (terrible) SQLite. One thing that struck me as annoying was the CASE expression, namely the fact that it employs short-circuit evaluation.

Is there any way to get around this? I am looking for a CASE statement that does not employ short-circuit evaluation.

UPDATE [table]SET [counting_column] =

(
CASE
    when [column1] = NULL 
    then [counting_column] + 1

    ...

    when [column31] = NULL
    then [counting_column] + 1
end
)

I would like each entry in the database to be tested by each case statement, not just the first one that evaluates to true. Any help would be much appreciated.

NOTE: I apologize if there's some glaring error-- I'm quite new at this so go easy please.


Solution

  • If you are indeed just adding 1 to counting_column for each condition that is met, you can use a chain of n CASE statements and add the results together. Each individual CASE supplies a 0 or 1, all of which are added together and added to the current value of counting_column.

    UPDATE [table] SET [counting_column] =
    (
      [counting_column] + 
      (CASE when [column1] IS NULL then 1 ELSE 0 END) +
      (CASE when [column2] IS NULL then 1 ELSE 0 END) +
        ...
        ...
      (CASE when [column30] IS NULL then 1 ELSE 0 END) +
      (CASE when [column31] IS NULL then 1 ELSE 0 END)
    )
    

    Note that I have changed the = NULL to IS NULL. NULL is a special non-value that cannot be compared with an equality =.

    I'll also point out that although [] enclosed identifiers are ok in SQLite, this is mostly for compatibility with T-SQL. The more standard approach is to use double-quotes as in UPDATE "table" SET "counting_column" = ...