Upsert with 2 conditions
I have a tool that keeps stats, every day for an organisation it keeps a set of data. However using the following query, it overwrites the row, even when the date changes:
14 Replies
Hi :vmathi: Could the following code solves your issues?
That doesn't seem to entirely work, however i think i have found a workaround. I thought i was doing something wrong with upsert. However i can check if the row exists, and update it, otherwise insert.
I don't have a unique constraint on the
org_id
and date
column since multiple points should be able to be saved for an org, and multiple orgs should be able to save on the same date.
Thanks for getting me started though!! :crumbLove:you should have an onConflict
create a unique index on what you determine to be the best way to identify a unique entry
in this case it's a comma delimited string of field names. the field names are in a unique index on the table
Oh, didn't know you could do it that way, thank you very much!
just remember to create the unique index in the database
Yeah i'm probably going to make a unique computed column that combines org id and date. And go from there.
you don't need a computed column
i can't set a unique constraint on the org_id or the date though
just do it on org_id
you want the ones existing to be updated, right?
Only if the date is still the same
every day there are about 6 pushes to the service, only the latest for said date should be kept, but other days need to create new rows
example
so instead of tenant_id , id you would just do org_id, date
for an upsert it will only update if that org_id, date exists. otherwise it will be an insert
that is what an upsert is supposed to do
yeah that's what i expected upsert to do, though onConflict requires a unique column
no, you can have multiple columns
your unique index needs to match your onconflict
Oh i see