Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraint for only one record marked as default

Tags:

sql

sql-server

How could I set a constraint on a table so that only one of the records has its isDefault bit field set to 1?

The constraint is not table scope, but one default per set of rows, specified by a FormID.

like image 824
ProfK Avatar asked Mar 12 '09 09:03

ProfK


People also ask

Which constraint is applied only once in a table?

Constraints can be assigned on a column or table level. Column level constraints apply only to one column, while table level constraints can apply to multiple columns or the whole table.

Which constraint can be used to provide a default value?

The DEFAULT constraint is used to set a default value for a column. The default value will be added to all new records, if no other value is specified.

Which type of constraint allows only unique values?

A primary key constraint uniquely identifies each row/record in a database table. Primary keys must contain unique values. A primary key column cannot have NULL values.


1 Answers

Use a unique filtered index

On SQL Server 2008 or higher you can simply use a unique filtered index

CREATE UNIQUE INDEX IX_TableName_FormID_isDefault     ON TableName(FormID)     WHERE isDefault = 1 

Where the table is

CREATE TABLE TableName(     FormID INT NOT NULL,     isDefault BIT NOT NULL ) 

For example if you try to insert many rows with the same FormID and isDefault set to 1 you will have this error:

Cannot insert duplicate key row in object 'dbo.TableName' with unique index 'IX_TableName_FormID_isDefault'. The duplicate key value is (1).

Source: http://technet.microsoft.com/en-us/library/cc280372.aspx

like image 161
Yves M. Avatar answered Oct 11 '22 10:10

Yves M.