SQL unique : manual check vs catch exception -
SQL unique : manual check vs catch exception -
i'm working on big database , i'm seeking can speed database. question : when have unique index on somes fields, faster between create select request check if it's ok, or seek anyway , grab exception if entry exists ?
i made researchs nil conclusive. thanks.
a manual check won't think does. (see below.)
if check first, every insert requires 2 round-trips database. might require serializable transactions.
and have trap errors anyway. duplicate value one thing can go wrong on insert; there lot of other things can go wrong.
i insert, , trap errors.
the point of select before insert determine whether value exists in database. can't rely on work. here's why.
open 2 terminal sessions (for example), , connect both database. table exists. it's empty.
create table test ( test_id serial primary key, test_email varchar(15) not null unique );
a: begin transaction; a: select test_email test test_email = 'a@b.com'; (0 rows) b: begin transaction; a: insert test (test_email) values ('a@b.com'); insert 0 1 b: select test_email test test_email = 'a@b.com'; (0 rows) b: insert test (test_email) values ('a@b.com'); (waiting lock) a: commit; b: error: duplicate key value violates unique constraint... sql unique
Comments
Post a Comment