Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining the UNIQUE and CHECK constraints

I have a table with columns a b and c, and if c is false then I only want to allow insertions if columns a and b are unique, but if c is true then a and b do not need to be unique.

Example: There can only be one (foo, bar, false) in the table, but no limit on how many (foo, bar, true) there can be.

I tried something like CONSTRAINT blah UNIQUE (a,b) AND CHECK (C is TRUE) but I can't figure out the correct syntax.

like image 902
Bobby Avatar asked Apr 06 '10 18:04

Bobby


People also ask

Can you have multiple check constraints in a table?

You can apply multiple CHECK constraints to a single column. You can also apply a single CHECK constraint to multiple columns by creating it at the table level.

Can we have multiple check constraints in SQL?

You can have multiple check constraint for a single column. If data being inserted or updated violates a check constraint the database engine will not allow the INSERT or UPDATE operation to occur. A check constraint consists of a logical expression to identify what is a valid expression.

Can unique constraints be multiple?

A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

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);


1 Answers

  1. Create an indexed view returning a and b with a filter WHERE C = false, then create a unique index on the view. This is a general approach

  2. If you have SQL Server 2008, then create a unique filtered index instead

  3. Stored procedure

  4. Trigger (before or after)

like image 142
gbn Avatar answered Sep 30 '22 07:09

gbn