Which DB construct is faster: a unique index and INSERT IGNORE, or using SELECT to find existing records?
I have a table with one column: userid.
When a user visits a specific page, their user ID is inserted into the table. Users are unique, so there should not be two identical user IDs in this table.
I am considering two projects:
- Create a unique column and use commands
INSERT
every time the user accesses this page. - Checking that the user is already recorded in the table by
SELECT
ing from the table, thenINSERT
ing if no record is found.
Which one is faster?
source to share
Definitely create an index UNIQUE
, or better, make this column a PRIMARY KEY
.
You need an index to keep your checks fast.
Why not make this index UNIQUE
so that you have a different fallback option (if you forgot to check with for some reason SELECT
)?
If yours is a table InnoDB
, it will anyway PRIMARY KEY
, since all tables are InnoDB
organized by design index.
If you have not declared PRIMARY KEY
in your table, InnoDB
will create a hidden column that will become the primary key, which will make your table twiz so big and you will not have a pointer to your column.
Creating PRIMARY KEY
in your column is a win-win.
You can specify
INSERT
IGNORE
INTO mytable
VALUES (userid)
and check how many records were affected.
If 0
, there was a key violation, but not an exception.
source to share
You must make it unique in all cases.
Wether to check SELECT first depends on which scenario is the most common. If you have new users all the time and only existing users, it might be generally faster if the system would just insert and catch the exception on rare occasions it does, but the exception is slower than checking first and then inserting, so if the normal scenario is an existing user, you should always check it first.
source to share