Question

I'm developing an iOS app that will enable users to receive push notifications. Therefore, I have to store for each user their APN device token. I have decided to piggy back the APN device token on each API request and store it in the database if it doesn't yet exist.

The table design is very simple, only one column 'device_token':

mysql> desc apn_devices;
+--------------+-------------+------+-----+---------+-------+
| Field        | Type        | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| device_token | varchar(64) | NO   | PRI | NULL    |       |
+--------------+-------------+------+-----+---------+-------+

Now I'm wondering, what would be more expensive to ensure all tokens are unique? I see two options:

  1. Put a unique constraint on 'device_token', just insert the token and ignore any exception that might occur
  2. First, perform a query to check if the token already exists and if not, insert it.

The first seems to be a more 'clean' solution, in a sense that it takes less code, which is easier to maintain. The second solution will only add an additional query when the token does not yet exist, preventing the inevitable constraint violation of the first. Logically thinking, the latter should be less expensive, but takes more code to accomplish.

What is best practice here? Is it expensive for MySQL to throw exceptions?

Was it helpful?

Solution

Or, you can simply do an INSERT IGNORE ... (no need for a unique constraint as it's the primary key, and hence by construction must be unique)

From MySQL Reference Manual:

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row still is not inserted, but no error occurs. Ignored errors may generate warnings instead, although duplicate-key errors do not.

Note that if you had other columns in your table you'd want to update each time (e.g. a "last used" timestamp), you could also use INSERT ... ON DUPLICATE KEY UPDATE ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top