Skip to content
Advertisement

SQlite Insert or replace conditional on each column value being bigger than it’s current value

I’m in a situation where I can have the same record appear several times.

The trouble is that some of the fields may be missing, this is denoted by a value of -1 in that field. The value of the field will either by the correct value or -1. The correct value will always be positive. The problem is I don’t know in advance which fields will be missing and the set of missing fields can be different for each record. My goal is to have a final entry in the database, which pools all the correct values.

What I want to be able to do is to insert and replace those columns whose value has increased. Given that the only possible values are -1 and the correct value which is positive this should ensure that I end up with as many of the correct rows as possible (it may be of course that some columns are omitted from all the records.)

The code above is my attempt (I’m still new to sql) obviously this is wrong, it updates both columns regardless of their current values,but it should only update Val1 because Val1 has increased, while Val2 should remain unchanged because it decreased.

The question below seems to be asking for something similar but in that case, you have a complete data set to compare to, you don’t know which (if any) of the recs are complete in my case. So I’ve not been able to generalise this solution to my problem.

How to conditionally INSERT OR REPLACE a row in SQLite?

This one I really could not understand the answer at all but perhaps it will help you when trying to solve my problem.

SQLite conditional insert or replace

Advertisement

Answer

I believe the following is along the lines of what you want to do.

If you have version 3.24.0 or greater of SQlite then you can use an UPSERT (update or insert)

e.g. :-

Result :-

  • Note the next example includes more explanatory notes, many of which apply.

If the SQlite version is below 3.24.0 then consider :-

This initially adds the row (value for owner is null), using 3 supplied values ([owner], val1 and val1) null,-1 and 5 as per :-

enter image description here

The second use amends the row using values ([owner], val1 and val1) 1, 7 and -1

  • Val2 is not updated according to my interpretation of :-

    • What I want to be able to do is to insert and replace those columns whose value has increased. Given that the only possible values are -1 and the correct value which is positive this should ensure that I end up with as many of the correct rows as possible (it may be of course that some columns are omitted from all the records.)

As per :-

enter image description here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement