title: How to update or insert with SQLite.swift
body: <p>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.</p>
  <h1>Related questions</h1>
  <p>This type of question is popular for SQL in general</p>
  <ul>
  <li><a href="https://stackoverflow.com/questions/21208719/update-if-exists-else-insert-in-sql-server-2008">UPDATE if exists else INSERT in SQL Server 2008</a></li>
  <li><a href="https://stackoverflow.com/questions/108403/solutions-for-insert-or-update-on-sql-server">Solutions for INSERT OR UPDATE on SQL Server</a></li>
  <li><a href="https://stackoverflow.com/questions/4205181/insert-into-a-mysql-table-or-update-if-exists">Insert into a MySQL table or update if exists</a></li>
  </ul>
  <p>and SQLite in particular</p>
  <ul>
  <li><a href="https://stackoverflow.com/questions/3634984/insert-if-not-exists-else-update">INSERT IF NOT EXISTS ELSE UPDATE?</a></li>
  <li><a href="https://stackoverflow.com/questions/418898/sqlite-upsert-not-insert-or-replace">SQLite - UPSERT *not* INSERT or REPLACE</a></li>
  <li><a href="https://stackoverflow.com/questions/15277373/sqlite-upsert-update-or-insert">SQLite UPSERT / UPDATE OR INSERT</a></li>
  <li><a href="https://stackoverflow.com/questions/14807472/sql-how-to-update-or-insert-if-doesnt-exist">SQL: How to update or insert if doesn&#39;t exist?</a></li>
  </ul>
  <h1>Looking for SQLite.swift implementation</h1>
  <p>I'm trying to save development time by using the <a href="https://github.com/stephencelis/SQLite.swift" rel="nofollow noreferrer">SQLite.swift</a> wrapper for iOS development. I chose this framework because it was <a href="https://www.raywenderlich.com/123579/sqlite-tutorial-swift" rel="nofollow noreferrer">recommended on raywenderlich.com</a>. I think it would be useful to have an example of the syntax for an update or insert.</p>
  <h1>Strategy</h1>
  <p>In <a href="https://stackoverflow.com/a/418988/3681880">this answer</a>, Sam Saffron says:</p>
  <blockquote>
  <p>If you are generally doing updates I would ..</p>
  <ol>
  <li>Begin a transaction</li>
  <li>Do the update</li>
  <li>Check the rowcount</li>
  <li>If it is 0 do the insert</li>
  <li>Commit</li>
  </ol>
  <p>If you are generally doing inserts I would</p>
  <ol>
  <li>Begin a transaction</li>
  <li>Try an insert</li>
  <li>Check for primary key violation error</li>
  <li>if we got an error do the update</li>
  <li>Commit</li>
  </ol>
  <p>This way you avoid the select and you are transactionally sound on
  Sqlite.</p>
  </blockquote>
  <p>That makes sense to me, so in my answer below I am providing an example of the &quot;generally doing updates&quot;.</p>