CASE statement in SQLite query

SqliteNestedCase

Sqlite Problem Overview


Why this query doesn't work? :( I tried to replace nested IF statement "...SET lkey = IF(lkey >= 11, lkey - 5, IF(lkey > 5, lkey + 2,lkey))"

UPDATE pages
SET lkey = CASE lkey WHEN lkey >= 11 THEN
		lkey - 5
	ELSE
		CASE lkey WHEN lkey > 5 THEN
			lkey + 2
		ELSE
			lkey
		END
	END,
	rkey = CASE lkey WHEN lkey >= 11 THEN
		rkey - 5
	ELSE
		CASE rkey WHEN rkey < 11 THEN
			rkey + 2
		ELSE
			rkey
		END
	END
WHERE rkey > 5 AND
	lkey < 12;

Sqlite Solutions


Solution 1 - Sqlite

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

or

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

Check out the documentation (The CASE expression):

http://www.sqlite.org/lang_expr.html

Solution 2 - Sqlite

Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVeroLomView Question on Stackoverflow
Solution 1 - SqliteLukas EderView Answer on Stackoverflow
Solution 2 - SqliteHrusilovView Answer on Stackoverflow