Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ampersand (&) operator in a SQL Server WHERE Clause

Sorry for the very basic question. What does the & operator do in this SQL

WHERE (sc.Attributes & 1) = 0  

sc is an alias for a table which contains a column attributes.

I'm trying to understand some SQL in a report and that line is making it return 0 entries. If I comment it out it works. I have limited SQL knowledge and I'm not sure what the & 1 is doing.

like image 699
Jimmymcnulty Avatar asked Mar 21 '09 23:03

Jimmymcnulty


People also ask

Why is it called the ampersand?

Etymology. The term ampersand is a corruption of and (&) per se and, which literally means "(the character) & by itself (is the word) and." The symbol & is derived from the ligature of ET or et, which is the Latin word for "and."

What is an ampersand?

ampersand • \am-pər-sand\ • noun. : a character & that is used for the word and. Examples: The company coming out of this merger will have a name that combines elements of each of the original companies' names with an ampersand. "

What is this symbol called &?

What is an &? & is called an ampersand symbol (pronounced “AM- per-sand”). Essentially, it means “and”. It is used both (a) in the body of the paper as part of a citation and (b) at the end of the paper as part of a reference.

Is ampersand grammatically correct?

An ampersand (&) is a typographical symbol that is rarely used in formal writing. It is read aloud as the word and and is used as a substitute for that word in informal writing and in the names of products or businesses.


2 Answers

& is the bitwise logical and operator - It performs the operation on 2 integer values.

WHERE (sc.Attributes & 1) = 0  

The above code checks to see if sc.Attributes is an even number. Which is the same as saying that the first bit is not set.

Because of the name of the column though: "Attributes", then the "1" value is probably just some flag that has some external meaning.

It is common to use 1 binary digit for each flag stored in a number for attributes. So to test for the first bit you use sc.Attributes&1, to test for the second you use sc.Attributes&2, to test for the third you use sc.Attributes&4, to test for the fourth you use sc.Attributes&8, ...

The = 0 part is testing to see if the first bit is NOT set.

Some binary examples: (== to show the result of the operation)

//Check if the first bit is set, same as sc.Attributes&1 11111111 & 00000001 == 1 11111110 & 00000001 == 0 00000001 & 00000001 == 1   //Check if the third bit is set, same as sc.Attributes&4 11111111 & 00000100 == 1 11111011 & 00000100 == 0 00000100 & 00000100 == 1 
like image 182
Brian R. Bondy Avatar answered Sep 29 '22 08:09

Brian R. Bondy


It's a bitwise and.

like image 28
MarkusQ Avatar answered Sep 29 '22 06:09

MarkusQ