I'm inserting values into my table (from python code) as follows:
cur.execute("insert into t(a, b, c) values (?, ?, ?)", (a, b, c))
There is a unique constraint
on column c. What is a common way of insert
if I want to cover the case when we're inserting duplicate value for c column?
I have some ideas
- select everything from t to list and test before inserting if the value is already present
- try-catch block
- some more sophisticated sqlite statement
How would you test it?
thank you
Depends :)
If there is only one inserter the 1 might be the most efficient.
If there are several inserters you have to use 2 as under 1 you could test and seem OK but another inserter adds the C value you have so it fails
You could use INSERT OR REPLACE to update rows with a unique constraint, or INSERT OR IGNORE to ignore inserts which conflict with a unique constraint:
These sqlite commands are probably faster than writing Python code to do the same thing, though to test this you could use Python's
timeit
module to test the speed of various implementations. For example, you could runversus
versus