Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce unique constraint in MySQL?

I have a MySQL table defined:

File -------------------------- ID int(11) PK name varchar(100) customerId int(11) FK isPrimaryImage tinyint(1) .... 


I've read here that MySQL doesn't support a UNIQUE CONSTRAINT with a WHERE condition. For each customerId we'd have only one primaryImage = 1.

So what else can I do to enforce this constraint?

like image 744
kasdega Avatar asked Jul 13 '11 12:07

kasdega


People also ask

How do I create a unique constraint in MySQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.

Does PRIMARY KEY enforce unique?

A primary key should be unique, but a unique key cannot necessarily be the primary key. Primary key implements entity integrity, whereas the unique key enforces unique data.

Which is the correct way to add unique constraint?

The syntax for creating a unique constraint using an ALTER TABLE statement in SQL Server is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.


1 Answers

MySQL perfectly supports unique constraints.

It does not support partial constraints/indexes, though, so you would need to mark non-primary images with a NULL instead of 0.

ALTER TABLE file ADD CONSTRAINT ux_file_customer_primary  UNIQUE (customerId, isPrimaryImage) 

You can insert arbitrary number of NULL values into isPrimaryImage but only one non-null value per customer.

like image 98
Quassnoi Avatar answered Sep 27 '22 21:09

Quassnoi