Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server bit column constraint, 1 row = 1, all others 0

Tags:

I have a bit IsDefault column. Only one row of data within the table may have this bit column set to 1, all the others must be 0.

How can I enforce this?

like image 447
Mike Avatar asked Jan 26 '11 22:01

Mike


People also ask

What is bit 0 in SQL Server?

If there are from 9 up to 16 bit columns, the columns are stored as 2 bytes, and so on. The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0. Converting to bit promotes any nonzero value to 1.

How to define bit data type in SQL?

SQL Server bit data type is an integer data type that can take only one of these values: 0, 1, NULL. With regard to the storage, if there are less than 9 columns of the bit data in the table, they are stored as 1 byte. If there are 9 to 16 such columns, they consume 2 bytes and so on.

What is bit value in SQL?

SQL Server BIT data type is an integer data type that can take a value of 0, 1, or NULL . The following illustrates the syntax of the BIT data type: BIT. SQL Server optimizes storage of BIT columns. If a table has 8 or fewer bit columns, SQL Server stores them as 1 byte.

How do I get all rows in one column in SQL?

In this case, we use GROUP_CONCAT function to concatenate multiple rows into one column. GROUP_CONCAT concatenates all non-null values in a group and returns them as a single string. If you want to avoid duplicates, you can also add DISTINCT in your query.


1 Answers

All versions:

  • Trigger
  • Indexed view
  • Stored proc (eg test on write)

SQL Server 2008: a filtered index

CREATE UNIQUE INDEX IX_foo ON bar (MyBitCol) WHERE MyBitCol = 1 
like image 78
gbn Avatar answered Oct 15 '22 05:10

gbn