Sqlite - Update row if exists or create new row and then update?
Archived 4 months ago
D
dialoguechicken
Verified
I'm essentially trying to use conditional logic here but it doesn't exist in Sqlite it seems.
What I want is effectively this:
```sql
IF EXISTS (SELECT 1 from names WHERE name = $1) THEN
UPDATE names
SET {thing} = {thing} + 1, other_thing = other_thing + 1
WHERE name = $1;
ELSE
INSERT INTO names (name, thing, other_thing, others) VALUES ($1, 0, 0, 0);
UPDATE names
SET {thing} = {thing} + 1, other_thing = other_thing + 1
WHERE name = $1;
END IF;
```
But that doesn't seem to work in SQL. CASE statements don't seem much better. I think an upsert is the closest to this, but I'm not sure if I can actually do all of my changes in an upsert here?
What's my best/most idiomatic solution here? Thanks.
