Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Oracle – Unique constraint while allowing null values

I’m a bit new to PL-SQL coming from T-SQL.

I have a requirement that only one phone number is allowed per user ID, but the phone number column can be null as many times as required.

So table is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

User ID Phone Number
1 NULL
1 9735152122
1 NULL
2 NULL
3 NULL
1 2124821212

It’s that last one I need to block, although the first three are fine. In this case I’m talking about the sample table I’ve posted, not the actual table order. I just need to allow the NULLs through but block if there are duplicate phone numbers per a given User ID.

I’ve read about functional indexes but not sure exactly how to apply them here.

>Solution :

CREATE UNIQUE INDEX my_index ON my_table (
  CASE WHEN phone_number IS NULL THEN NULL ELSE user_id END,
  phone_number
)

With this logic, if phone_number is NULL, then both values in the index will be NULL, so that row will be excluded from the index. If phone_number is not NULL, then the row will be included in the index with the actual values for user_id and phone_number, and uniqueness will be enforced.

P.S. This is not "PL/SQL", it is Oracle SQL. PL/SQL is the procedural language used to write such things as triggers, functions, etc.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading