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 SQL create unique INDEX constraint based on status column and other 4 column

I need UNIQUE INDEX CONSTRAINT for below example:

 CREATE TABLE DEMO(
    
    COL_1 number,
    COL_2 number,
    COL_3 number,
    COL_4 number,
    STATUS number)
    ;
    
    Insert into DEMO(COL_1,COL_2,COL_3,COL_4,STATUS) values (1,2,3,4,0); --Allow insert
    Insert into DEMO(COL_1,COL_2,COL_3,COL_4,STATUS) values (1,2,3,4,1); --Allow insert
    Insert into DEMO(COL_1,COL_2,COL_3,COL_4,STATUS) values (1,2,3,4,0); --Allow insert
    Insert into DEMO(COL_1,COL_2,COL_3,COL_4,STATUS) values (1,2,3,4,1); --Not allow insert status 1 already exits!

>Solution :

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

This is the 12th pseudo constraint (based on constraint types) that you can impose on a database model, that doesn’t require the use of the clause CONSTRAINT to define it.

You can create a partial unique index to enforce it. For example:

create unique index ix1 on demo (
  case when status = 1 then col_1 end,
  case when status = 1 then col_2 end, 
  case when status = 1 then col_3 end,
  case when status = 1 then col_4 end,
  case when status = 1 then status end
);

See running example at db<>fiddle.

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