Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite - increase value by a certain number

Tags:

sqlite

is it possible to increase a certain value in a table by a certain number without reading last value and afterwards updating it?

i.e. I have columns "product" and "quality": product: iLamp quality: 50

I want to increase(or decrease) quality by x. To achieve this I am first reading last value (50), increasing or decreasing it, and writing it back.

Is there a direct way to complete this task?

like image 657
Ilya Suzdalnitski Avatar asked Apr 13 '09 15:04

Ilya Suzdalnitski


People also ask

Does SQLite have auto increment?

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment. The keyword AUTOINCREMENT can be used with INTEGER field only.

How does auto increment work in SQLite?

AUTOINCREMENT guarantees that automatically chosen ROWIDs will be increasing but not that they will be sequential. Because AUTOINCREMENT keyword changes the behavior of the ROWID selection algorithm, AUTOINCREMENT is not allowed on WITHOUT ROWID tables or on any table column other than INTEGER PRIMARY KEY.


1 Answers

Example 1 (for all rows):

UPDATE product SET price = price + 50 

Example 2 (for a specific row):

UPDATE product SET price = price + 50 WHERE id = 1 

Example 3 (for specific rows):

UPDATE product SET price = price + 50 WHERE id IN [1, 2, 3] 

Example 4 (generic):

UPDATE {table} SET {column} = {column} + {value} WHERE {condition} 

Where:

  • {table} - table name
  • {column} - column name
  • {value} - a number by which column's value should be increased or decreased
  • {condition} - some condition if any
like image 54
Konstantin Tarkus Avatar answered Oct 16 '22 09:10

Konstantin Tarkus