Suppose I create a table of tasks.
CREATE TABLE todos (
id UUID DEFAULT gen_random_uuid PRIMARY KEY,
text STRING(1000)
)
An end-user creates some new todos (which don't yet have an id/UUID) and updates others, and we'd like to be able to update or insert those tasks (update if they have an id, insert otherwise). We could create or update one by one, using the right query.
-- $1 is "some task"
INSERT INTO todos (text)
VALUES ($1)
RETURNING id
-- $1 is a UUID, $2 is "some task"
UPDATE todos
SET text = $2
WHERE id = $1
Can "update or insert" be performed in one query? Or better, in a single query that works with a batch of todos?
UPSERT
and INSERT INTO ... ON CONFLICT
don't seem to be the right approach, because they try to create first, whereas I'd like to try to update first otherwise insert (to generate id).
I'm using CockroachDB, Go, and the pgx
driver.
How would you typically handle this situation?