Peter Larsson Blog

Patron Saint of Lost Yaks

Save some time and key-typing

Sometimes you have a denormalized table with several BIT columns used as flags.

Say you want to select every row that has at least one flag set. That's easy.

SELECT * FROM Table1 WHERE Flag1 = 1 OR Flag2 = 1 OR Flag3 = 1...

But how to easy select all records where all flags are not set?

SELECT * FROM Table1 WHERE Flag1 = 0 AND Flag2 = 0 AND Flag3 = 0...

That can be the way you normally write, and it can get very long!

But if you write like this instead to get all records where at least one flag is set

SELECT * FROM Table1
WHERE 1 IN (Flag1, Flag2, Flag3...)

The code is somewhat smaller. It can be hard the first times to understand what is happening but you will get it eventually.

But how to select all records where all flags are set? You can't write

SELECT * FROM Table1
WHERE 0 IN (Flag1, Flag2, Flag3...)

because that will only get you all records where at least one flag is not set.
Here is the perfect opportunity to introduce the NOT operator. This is the way you can get the records where all flags are set.

SELECT * FROM Table1
WHERE NOT 0 IN (Flag1, Flag2, Flag3...)

And this will get you all records where all flags are not set

SELECT * FROM Table1
WHERE NOT 1 IN (Flag1, Flag2, Flag3...)

Legacy Comments


Suresh Beniwal
2007-10-05
re: Save some time and key-typing
Good article. Thanks, this will definitely help sometime.
--Suresh

dineshrajan
2010-08-09
re: Save some time and key-typing
Nice Article. Thanks