129

I have a field that stores product codes. The codes are unique, but some products simply doesn't have a code. I can't invent codes because those are providers codes.

Is this kind of constraint possible in MySQL?

I'm a noob with stored procedures and triggers, so if the solution involves one of these, please be patient.

Update: The column is NOT Null. That's why I was unable to do this.

The Disintegrator
  • 4,089
  • 9
  • 34
  • 42
  • Possible duplicate of [Does MySQL ignore null values on unique constraints?](http://stackoverflow.com/questions/3712222/does-mysql-ignore-null-values-on-unique-constraints) – Amir Ali Akbari Nov 07 '16 at 08:11

3 Answers3

188

Yes, you can do this. See the MySQL reference (version 5.5).

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index allows multiple NULL values for columns that can contain NULL.

EricC
  • 1,215
  • 1
  • 19
  • 33
13

Yes, if you make the product code column nullable (not declared with NOT NULL), the unique key will allow multiple rows with NULL product codes.

chaos
  • 119,149
  • 33
  • 300
  • 308
8

MySQL still allows for multiple rows to have a value of NULL in a unique column.

cg.
  • 3,598
  • 2
  • 25
  • 28