QamoosTech
DatabasesData modelingBeginnerSQLDjango

Unique Constraint

Pronunciationyoo-NEEK kun-STRAYNT

Definition

A unique constraint makes the database reject a row if another row already has the same value, or the same combination of values, in the constrained columns.

Where you hear it

In table design, migrations, and errors such as "duplicate key value violates unique constraint".

Examples

  • A unique constraint on member and week stops a double payment.
  • Emails must be unique, so the database refuses a second account.
  • The unique constraint on the username makes a second signup fail with an error.

Common mistake

Checking for duplicates only in code. Two requests at once can both pass the check; the constraint is what really prevents it.

Don't confuse with

A primary key, which is also unique but identifies the row and cannot be empty. A table can have many unique constraints.

Say it at work

  • In a meeting or chatAdd a unique constraint instead of checking in code.
  • In an email or ticketThe migration fails because the existing data has duplicates.