Search code examples
sqlitesql-updatemultiplication

Sqlite: convert semicolon separated positive values to negative values


I have a SQLite table that look like this:

name value
Julia 43
Julia 12;54
Julia 10;7;32
Julia NULL
Julia 11;42

So my aim is to multiply all values in the column value by -1. When I run something like this:

UPDATE table
SET value = value * -1
WHERE name = 'Julia' 
  AND value IS NOT NULL;

this leads to this table:

name value
Julia -43
Julia -12
Julia -10
Julia NULL
Julia -11

The second and third semicolon separated values are lost. But the output table should look like this one:

name value
Julia -43
Julia -12;-54
Julia -10;-7;-32
Julia NULL
Julia -11;-42

Solution

  • For this sample data you can replace all occurrences of ';' with ';-' and concatenate a '-' at the beginning of value:

    UPDATE tablename
    SET value = '-' || REPLACE(value, ';', ';-')
    WHERE name = 'Julia' AND value IS NOT NULL;
    

    See the demo.