Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CASE statement in SQLite query

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; 
like image 797
VeroLom Avatar asked Feb 11 '11 12:02

VeroLom


People also ask

What is case in SQL query?

The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By, and Group By clause. It can be used in the Insert statement as well.

Can we use CASE statement in SQL?

CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.

Is SQLite query case-sensitive?

The important point to be noted is that SQLite is case insensitive, i.e. the clauses GLOB and glob have the same meaning in SQLite statements.

Which of the following is the syntax for CASE statement?

Which of the following is correct syntax for CASE statement? Explanation: The CASE statement is started with the keyword CASE followed by any identifier or expression and the IS.


1 Answers

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

like image 60
Lukas Eder Avatar answered Oct 13 '22 13:10

Lukas Eder