I want to update the column of a row if the row already exists, but if it doesn't exist yet then I want to insert a new row.
Related questions
This type of question is popular for SQL in general
- UPDATE if exists else INSERT in SQL Server 2008
- Solutions for INSERT OR UPDATE on SQL Server
- Insert into a MySQL table or update if exists
and SQLite in particular
- INSERT IF NOT EXISTS ELSE UPDATE?
- SQLite - UPSERT *not* INSERT or REPLACE
- SQLite UPSERT / UPDATE OR INSERT
- SQL: How to update or insert if doesn't exist?
Looking for SQLite.swift implementation
I'm trying to save development time by using the SQLite.swift wrapper for iOS development. I chose this framework because it was recommended on raywenderlich.com. I think it would be useful to have an example of the syntax for an update or insert.
Strategy
In this answer, Sam Saffron says:
If you are generally doing updates I would ..
- Begin a transaction
- Do the update
- Check the rowcount
- If it is 0 do the insert
- Commit
If you are generally doing inserts I would
- Begin a transaction
- Try an insert
- Check for primary key violation error
- if we got an error do the update
- Commit
This way you avoid the select and you are transactionally sound on Sqlite.
That makes sense to me, so in my answer below I am providing an example of the "generally doing updates".