Can I conditionally enforce a uniqueness constraint?

user2692862 picture user2692862 · Aug 17, 2013 · Viewed 7.5k times · Source

My database contains a table of users. Every active user has a unique username. I'd like to be able to deactivate a user and free up the username they're using, but keep them in the same table.

Is there a way to only conditionally enforce the uniqueness constraint?

Answer

Gordon Linoff picture Gordon Linoff · Aug 18, 2013

Add another column called something like isactive. The create a unique constraint on (username, isactive).

Then you can have both an active and inactive user name at the same time. You will not be able to have two active user names.

If you want multiple inactive names, use NULL for the value of isactive. NULL values can be repeated in a unique index.