how can i set up a uniqueness constraint in mysql for columns that can be null?

Posted by user299689 on Stack Overflow See other posts from Stack Overflow or by user299689
Published on 2010-03-23T07:53:30Z Indexed on 2010/03/23 8:03 UTC
Read the original article Hit count: 228

I know that in MySQL, UNIQUE constraits don't treat NULL values as equal. So if I have a unique constraint on ColumnX, then two separate rows can have values of NULL for ColumnX and this wouldn't violate the constraint. How can I work around this? I can't just set the value to an arbitrary constant that I can flag, because ColumnX in my case is actually a foreign key to another table. What are my options here?

Please note that this table also has an "id" column that is its primary key. Since I'm using Ruby on Rails, it's important to keep this id column as the primary key.

Note 2: In reality, my unique key encompasses many columns, and some of them have to be null, because they are foreign keys, and only one of them should be non-null. What I'm actually trying to do is to "simulate" a polymorphic relationship in a way that keep referential integrity in the db, but using the technique outlined in the first part of the question asked here: http://stackoverflow.com/questions/922184/why-can-you-not-have-a-foreign-key-in-a-polymorphic-association

© Stack Overflow or respective owner

Related posts about mysql

Related posts about foreign-keys