Reputation: 63835
I am designing a User
table in my database. I have about 30 or so options for each user that can be either "allow" or "disallow".
My question is should I store these as 30 bit
columns or should I use a single int
column to store them and parse out each bit in my application?
Also, our database is SQL Server 2008 and 2005 (depending on environment)
Upvotes: 9
Views: 2160
Reputation: 453308
I just tried creating two tables, one with a single int column and one with 30 bit columns then added a row to each and looked at them with SQL Server Internals Viewer
CREATE TABLE T_INT(X INT DEFAULT 1073741823);
CREATE TABLE T_BIT(
X1 BIT DEFAULT 1,
/*Other columns omitted for brevity*/
X30 BIT DEFAULT 1
);
INSERT INTO T_INT DEFAULT VALUES;
INSERT INTO T_BIT DEFAULT VALUES;
Single row for table with 30 Bit Columns
Single row for table with one int Column
From a storage point of view SQL Server combines the bit columns and the data is stored in exactly the same amount of space (yellow). You do end up losing 3 bytes a row for the NULL bitmap (purple) though as the length of this is directly proportional to the number of columns (irrespective of whether they allow nulls)
Key for fields (for the int version, colour coding is the same for the bit version)
Upvotes: 10
Reputation: 3690
I agree your design should be properly normalized, three tables User and User setting, and a bridge table:
User:
Userid int
UserName varchar(X)
UserSetting:
Settingid int
SettingName varchar(X)
UserUserSetting:
Userid int
SettingId int
IsSet bit
There would be FK's between the bridge table UserUserSetting and the UserSetting and User table and a unique contr constraint of t UserId, SettingId in UserUserSetting
Upvotes: 1
Reputation: 8926
If you combine into a bitflag field, it's going to be difficult to see what is set if you're looking at the raw data. I'd go with individual columns for each value, or store the options in their own table.
Upvotes: 4
Reputation: 2534
Neither -- unless you have a major space issue or compatibility requirement with some other system, think about how this will prevent you from optimizing your queries and clearly understanding what each bit represents.
You can have more than a thousand columns in a table, or you can have a child table for user settings. Why limit yourself to 30 bits that you need to parse in your app? Imagine what kind of changes you'll need to make to the app if several of these settings are deprecated or a couple of new ones introduced.
Upvotes: 5
Reputation: 65157
I think it would be easier to allow for future expansion if you have columns for each value. If you add another option in the future (which is likely for most applications like this), then it may affect all your other code since you would need to reparse your int column to account for the new bits.
Upvotes: 4