views:

1028

answers:

2

MySQL has something like this:

INSERT INTO visits (ip, hits)
VALUES ('127.0.0.1', 1)
ON DUPLICATE KEY UPDATE hits = hits + 1;

As far as I'm know this feature doesn't exist in SQLite, what I want to know is if there is any way to archive the same effect without having to execute two queries. Also, if this is not possible, what do you prefer:

  1. SELECT + (INSERT or UPDATE) or
  2. UPDATE (+ INSERT if UPDATE fails)
+1  A: 

I'd prefer UPDATE (+ INSERT if UPDATE fails). Less code = fewer bugs.

codeholic
Thanks! @Sam (http://stackoverflow.com/questions/418898/sqlite-upsert-not-insert-or-replace/418988#418988) seems to agree with you. I also prefer this approach.
Alix Axel
+4  A: 
INSERT OR IGNORE INTO visits VALUES ($ip, 0);
UPDATE visits SET hits = hits + 1 WHERE ip LIKE $ip;

This requires the "ip" column to have a UNIQUE (or PRIMARY KEY) constraint.

dan04
Brilliant, I totally forgot about the `OR IGNORE` clause. Nice one!
Alix Axel