9

Can I create in SQLite a statement like this?

update books set
(if number_of_pages > 0 then number_of_pages = number_of_pages - 1)
where book_id = 10

Is there a working syntax for this?

xralf
  • 5,997
  • 40
  • 115
  • 180

3 Answers3

26

A CASE statement should work with the following syntax:

UPDATE
  books
SET number_of_page = CASE WHEN number_of_pages > 0 THEN (number_of_pages - 1) ELSE 0 END
WHERE whatever_condition
Michael Berkowski
  • 260,803
  • 45
  • 432
  • 377
4

Isnt that equal to this statement ?

update books set number_of_pages = number_of_pages - 1 where number_of_pages>0

Edit:

according to new statement :

update books set number_of_pages = number_of_pages - 1 where number_of_pages>0 and book_id = 10
Pheonix
  • 6,003
  • 5
  • 27
  • 48
1

If you just want to conditionally update some rows and leave others intact, this should do:

update books
set number_of_pages = number_of_pages - 1
where number_of_pages > 0 AND book_id = 10

If you want to update all rows (with book_id = 10) to different values, you can use 2 statements with "opposite" conditions. Assuming 0 is the "other" value, that would look like this:

update books
set number_of_pages = number_of_pages - 1
where number_of_pages > 0 AND book_id = 10

update books
set number_of_pages = 0
where number_of_pages <= 0 AND book_id = 10

Or just use CASE as others have suggested.

Branko Dimitrijevic
  • 49,132
  • 10
  • 90
  • 159