views:

26

answers:

2

The questions says it all really.

I have a table and I want to insert a row if it doesn't already exist. or should I just do an insert and if the key constraint is violated then ignore it?

A: 

Use a trigger that fires before INSERTs and discards the duplicate row, something along the lines of...

CREATE TRIGGER trigger_name
BEFORE INSERT on your_table
FOR EACH ROW WHEN EXISTS (SELECT * FROM your_table WHERE id = NEW.id)
BEGIN
  SELECT RAISE(IGNORE);
END;
Blrfl
I think this would be exceedingly slow and inefficient, but thanks for the suggestion. It seems insert or ignore does what I require.
Matt H
Try "marginally faster." Just for laughs, I benchmarked it both ways. `INSERT OR IGNORE` took, on average, 5% longer than the trigger. I have a theory why that is but would have to dig through the SQLite source to confirm it.
Blrfl
+2  A: 

Use INSERT OR IGNORE: http://www.sqlite.org/lang_insert.html

Robie Basak