MySQL Forums
Forum List  »  Oracle

Using NULL values in unique keys
Posted by: Alex
Date: October 04, 2006 08:18AM

Hello, all!

I have the following table in Oracle:

SQL> create table mytable( name varchar2(10) not null, ref number(9,0), constraint uk unique( name, ref ) );
Table created.

If I try to add two rows to the table with the same 'name' and ref=NULL, the unique constraint is violated (which is exactly what I want):

SQL> insert into mytable(name) values('Alex');
1 row created.
SQL> insert into mytable(name) values('Alex');
insert into mytable(name) values('Alex')
*
ERROR at line 1:
ORA-00001: unique constraint (MYDB.UK) violated

MySQL and Postgres behave differently in that they don't consider the NULL values equal (I read somewhere that it's what the standard said). I can, however, do a little trick in postgres to get what I want:

mydb=> create unique index mytable_unique_idx on mytable( name, (coalesce(ref, -1)) );
CREATE INDEX
mydb=> insert into mytable(name) values('Alex');
INSERT 409755 1
mydb=> insert into mytable(name) values('Alex');
ERROR: duplicate key violates unique constraint "mytable_unique_idx"

My question is how do I do it in MySQL. I tried using coalesce but got a syntax error.

Thanks,
Alex.

Options: ReplyQuote


Subject
Views
Written By
Posted
Using NULL values in unique keys
5493
October 04, 2006 08:18AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.