There's an interesting design decision I've been thinking about lately. Let's say I'm adding usernames to a table, and I want to make sure there are no duplicates. The username column is NOT NULL UNIQUE
. I could either:
- Query the database before inserting to make sure there are no duplicate names, or
- Just
INSERT
, and catch any exceptions that come from the database engine.
Assuming the DB I'm using is capable of enforcing constraints, I was wondering what situations each of these choices is appropriate in.
Can you cache the username list and check it on the application side without going to the database? You should still have the unique constraint on the database to ensure no bad data gets in (always protect the data at the database level first and foremost) but if you can do the check from a cache, you could save a whole round trip to the database when someone selects the same username as an existing user. Now this may depend o nthe size of the data you would need to cache and how often the cache would have to be updated. Not knowing your system, I can't say if it is practical, but I would at least look into doing it.