Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flags in a database rows, best practices

I am asking this out of a curiosity. Basically my question is when you have a database which needs a row entry to have things which act like flags, what is the best practice? A good example of this would be the badges on stack overflow, or the operating system field in bugzilla. Any subset of the flags may be set for a given entry.

Usually, I do c and c++ work, so my gut reaction is to use an unsigned integer field as a set of bits which can be flipped... But i know that isn't a good solution for several reasons. The most obvious of which is scale-ability, there will be a hard upper limit on how many flags I can have.

I can also think of a couple of other solutions which scale better but would have performance issues because they would require multiple selects to get all the information.

So, what is the "right" way to do this?

like image 778
Evan Teran Avatar asked Sep 24 '08 01:09

Evan Teran


People also ask

What are flags in database?

It's mainly used to mean any Boolean variable, that is, a variable that can only hold the values "true" or "false" (or also "null", in case of SQL). Normally it represents the answer to whether a certain attribute is set.

What is the use of flag in SQL?

You use database flags for many operations, including adjusting SQL Server parameters, adjusting options, and configuring and tuning an instance. When you set, remove, or modify a flag for a database instance, the database might be restarted. The flag value is then persisted for the instance until you remove it.

What is the data type for flag in SQL?

In data warehousing we have an Is Current Flag column in SCD type 2 dimension table. This flag indicates whether the row is the current version or not. Some DW data modellers believe that in SQL Server platform this column should be created as bit rather than int or Y/N.

What does each row represent in database?

In relational databases, a row is a data record within a table. Each row, which represents a complete record of specific item data, holds different data within the same structure. A row is occasionally referred to as a tuple.


1 Answers

Generally speaking, I avoid bitmask fields. They're difficult to read in the future and they require a much more in-depth knowledge of the data to understanding.

The relational solution has been proposed previously. Given the example you outlined, I would create something like this (in SQL Server):

 CREATE TABLE Users (   UserId INT IDENTITY(1, 1) PRIMARY KEY,   FirstName VARCHAR(50),   LastName VARCHAR(50),   EmailAddress VARCHAR(255) );  CREATE TABLE Badges (   BadgeId INT IDENTITY(1, 1) PRIMARY KEY,   [Name] VARCHAR(50),   [Description] VARCHAR(255) );  CREATE TABLE UserBadges (   UserId INT REFERENCES Users(UserId),   BadgeId INT REFERENCES Badges(BadgeId) ); 
like image 178
Jeremiah Peschka Avatar answered Sep 23 '22 10:09

Jeremiah Peschka