Here is a simple table definition:
CREATE TABLE UserNotificationTokens (
UserID INT NOT NULL,
Token CHAR(36) NOT NULL,
DeviceId VARCHAR(50) NOT NULL,
CONSTRAINT UC_DeviceId UNIQUE (DeviceId)
)
Here, DeviceId column represents a physical device (smartphones). For each device, a user has a token (just a string, no big deal). As you can see, there is a unique key on DeviceId column. I want to insert a new token for a device if this device (DeviceId) does not exist already. I can check this existence in a few ways. But, the point is SQL Server already checks if DeviceId is unique because of the Unique Key. That means, there is double work for the same task. Is it a good practice to just ignore my own checking and leave it to SQL Server? If the insert will cause an error with code 2601 (Violation of Unique Key constraint), that means DeviceId is already there. Catch this specific error and do nothing. Otherwise, the row was inserted successfully.