how can i delete if row exists (where eq(xxx)), otherwise insert, in one query?

would i have to use raw sql & an if/else statement?
15 Replies
Luxaritas
Luxaritas•13mo ago
I don't think this is something any SQL dialect supports doing in one query. Could you explain your use case?
paaradiso
paaradisoOP•13mo ago
i have a table of collections (music singles, eps, albums) that you can like. i also have a liked_collections table that just has user_id and collection_id columns. when a collection is liked/unliked, i want to either remove a row if it's already liked, or insert a row if it's not already liked
Luxaritas
Luxaritas•13mo ago
Ah, I see
Luxaritas
Luxaritas•13mo ago
I would actually recommend not doing this "toggling" on the DB level This seems likely to introduce synchronization issues
paaradiso
paaradisoOP•13mo ago
ooh okay how should i do it?
Luxaritas
Luxaritas•13mo ago
Imagine that your user loads the app on their phone and PC Both show the song as liked They unlike on their PC, but their phone is offline You then unlike on their phone When the phone comes back online and you trigger the toggle It is back to being liked, which was not the user's intent!
paaradiso
paaradisoOP•13mo ago
i see hmm
Luxaritas
Luxaritas•13mo ago
Have the client request specifically to like or unlike
paaradiso
paaradisoOP•13mo ago
yeah true
Luxaritas
Luxaritas•13mo ago
If the delete fails because the record doesn't exist? A-ok. If the insert fails because the row already exists? Also fine!
paaradiso
paaradisoOP•13mo ago
that's much smarter, thanks :)
Luxaritas
Luxaritas•13mo ago
yw 🙂
paaradiso
paaradisoOP•13mo ago
easier to implement as well
Luxaritas
Luxaritas•13mo ago
The best solutions to hard problems is to make your problem easier 😄
Want results from more Discord servers?
Add your server