In this post we are going to cover the bitwise functions in Snowflake: BITAND, BITOR, BITXOR, BITNOT, BITSHIFTLEFT and BITSHIFTRIGHT.
These work on the individual bits inside an integer. Every whole number is a row of ones and zeros underneath, and these six functions let you read and change those bits directly instead of doing arithmetic on the number as a whole.
We will start with the four operators on two small numbers and build it up step by step. Then we will do the thing bitwise is actually for in a database, which is packing several yes-or-no answers into one column.
Two of the grids on this page are more useful than the rest. One is a reconciliation check that reports every single row agreeing, on data that is wrong. The other is a test I wrote that could not have failed, so it told me nothing. Both stay exactly as they came out of the database.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 84 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's start with the four operators
- Now let's look at the bits one at a time
- What do they do with a NULL?
- Now the one property of XOR that matters
- Let's shift the bits along
- Now let's shift a negative number
- How far can we shift?
- What happens when the shift count is negative?
- Now the real reason to use any of this: packing flags
- Let's read the flags back out
- So let's check the pack against the conditions
- Now let's set, clear and toggle a flag
- Which flag combinations actually occur?
- What happens if we give BITAND a decimal?
- Let's design a test that can fail
- One last thing: all of it on one grid
Let's create some sample data
Most of this post is arithmetic on literals, so it needs no table at all. The flag-packing section later on works on the ORDERS table, the same one the rest of the course uses.
-- ORDERS comes from the setup script this course uses throughout.
-- Run it once; every episode works on the same tables.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;Here are the first few orders.
SELECT ORDER_ID, CUSTOMER_ID, ORDER_DATE, AMOUNT, STATUS
FROM ORDERS ORDER BY ORDER_ID LIMIT 10;| ORDER_ID | CUSTOMER_ID | ORDER_DATE | AMOUNT | STATUS |
|---|---|---|---|---|
| 1001 | 101 | 2023-01-12 | 4200.00 | SHIPPED |
| 1002 | 102 | 2023-01-28 | 890.50 | SHIPPED |
| 1003 | 101 | 2023-02-14 | 6150.00 | SHIPPED |
| 1004 | 103 | 2023-02-27 | 1500.00 | CANCELLED |
| 1005 | 104 | 2023-03-09 | 2310.75 | SHIPPED |
| 1006 | 101 | 2023-03-22 | 5020.00 | SHIPPED |
| 1007 | 105 | 2023-04-05 | 7890.00 | SHIPPED |
| 1008 | 102 | 2023-04-19 | 1120.00 | SHIPPED |
| 1009 | 103 | 2023-05-02 | 3340.25 | SHIPPED |
| 1010 | 106 | 2023-05-21 | 640.00 | PENDING |
That is a LIMIT 10 off the front of the table. There are 41 orders altogether, and the counts later on this page cover all of them.
Have a look at the STATUS column. The values are stored in capitals — SHIPPED, CANCELLED, PENDING. Keep that in mind. It is going to matter more than it looks.
Let's start with the four operators
BITAND, BITOR and BITXOR each take two numbers and compare them bit by bit. BITNOT takes one and flips every bit in it.
Let's run all four on 12 and 10.
SELECT 12 AS A, 10 AS B,
BITAND(12, 10) AS AND_,
BITOR(12, 10) AS OR_,
BITXOR(12, 10) AS XOR_,
BITNOT(12) AS NOT_;| A | B | AND_ | OR_ | XOR_ | NOT_ |
|---|---|---|---|---|---|
| 12 | 10 | 8 | 14 | 6 | -13 |
BITAND gave 8, BITOR gave 14 and BITXOR gave 6. And BITNOT of 12 gave -13, which surprises people. We will come back to that one.
Those three numbers make more sense one bit at a time, so let's do all four combinations of a single bit.
SELECT P.A, P.B,
BITAND(P.A, P.B) AS AND_,
BITOR(P.A, P.B) AS OR_,
BITXOR(P.A, P.B) AS XOR_
FROM (SELECT 0 AS A, 0 AS B UNION ALL SELECT 0, 1
UNION ALL SELECT 1, 0 UNION ALL SELECT 1, 1) P
ORDER BY P.A, P.B;| A | B | AND_ | OR_ | XOR_ |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
BITAND gives 1 only when both bits are 1. BITOR gives 1 when either of them is. BITXOR gives 1 when exactly one of them is, which is why both bits being 1 gives 0. That is what the exclusive in exclusive-or means.
Now let's look at the bits one at a time
Here is a way to see which bits are set in a number without doing any binary conversion. BITAND the number against 1, 2, 4 and 8 in turn, and each one tells you about one bit.
SELECT V.N,
TO_BINARY(TO_CHAR(V.N), 'UTF-8') AS AS_BINARY_TYPE,
LPAD(TO_CHAR(V.N, '0000'), 4, '0') AS PADDED_DECIMAL,
BITAND(V.N, 1) AS BIT_0,
BITAND(V.N, 2) AS BIT_1,
BITAND(V.N, 4) AS BIT_2,
BITAND(V.N, 8) AS BIT_3
FROM (SELECT SEQ4() AS N FROM TABLE(GENERATOR(ROWCOUNT => 16))) V
ORDER BY V.N;| N | AS_BINARY_TYPE | PADDED_DECIMAL | BIT_0 | BIT_1 | BIT_2 | BIT_3 |
|---|---|---|---|---|---|---|
| 0 | bytearray(b'0') | 000 | 0 | 0 | 0 | 0 |
| 1 | bytearray(b'1') | 000 | 1 | 0 | 0 | 0 |
| 2 | bytearray(b'2') | 000 | 0 | 2 | 0 | 0 |
| 3 | bytearray(b'3') | 000 | 1 | 2 | 0 | 0 |
| 4 | bytearray(b'4') | 000 | 0 | 0 | 4 | 0 |
| 5 | bytearray(b'5') | 000 | 1 | 0 | 4 | 0 |
| 6 | bytearray(b'6') | 000 | 0 | 2 | 4 | 0 |
| 7 | bytearray(b'7') | 000 | 1 | 2 | 4 | 0 |
| 8 | bytearray(b'8') | 000 | 0 | 0 | 0 | 8 |
| 9 | bytearray(b'9') | 000 | 1 | 0 | 0 | 8 |
| 10 | bytearray(b'10') | 001 | 0 | 2 | 0 | 8 |
| 11 | bytearray(b'11') | 001 | 1 | 2 | 0 | 8 |
| 12 | bytearray(b'12') | 001 | 0 | 0 | 4 | 8 |
| 13 | bytearray(b'13') | 001 | 1 | 0 | 4 | 8 |
| 14 | bytearray(b'14') | 001 | 0 | 2 | 4 | 8 |
| 15 | bytearray(b'15') | 001 | 1 | 2 | 4 | 8 |
Read the four BIT_ columns across any row and you have that number in binary. For 12 it is 0, 0, 4, 8 — bits two and three are set, and 4 plus 8 is 12.
Notice that a BITAND against a single bit returns the value of that bit, not a one or a zero. That is why BIT_2 reads 4 and not 1. It is either the bit's value or zero, which is all you need for a > 0 test.
Two of the other columns in that grid do not show what their names suggest, and they are worth reading properly rather than skipping.PADDED_DECIMAL was meant to be the number zero-padded to four places. It reads 000 on the first ten rows and 001 on the rest. TO_CHAR(n, '0000') gives back a five-character string with a leading space for the sign, and LPAD(..., 4, '0') on a string that is already longer than four characters does not pad it — it truncates it, and the last character is the one that falls off.AS_BINARY_TYPE is TO_BINARY(TO_CHAR(n), 'UTF-8'), which is the bytes of the digits of the number, not the number's bits. That is why the row for 10 holds two bytes and the row for 9 holds one.
What do they do with a NULL?
Short section. Let's hand each of them a NULL.
SELECT BITAND(12, NULL) AS AND_NULL,
BITOR(12, NULL) AS OR_NULL,
BITXOR(12, NULL) AS XOR_NULL,
BITNOT(NULL) AS NOT_NULL,
BITAND(NULL, NULL) AS BOTH_NULL;| AND_NULL | OR_NULL | XOR_NULL | NOT_NULL | BOTH_NULL |
|---|---|---|---|---|
| NULL | NULL | NULL | NULL | NULL |
Every column came back NULL. One NULL argument is enough.
So these behave like ordinary arithmetic, and not like the HASH function from Episode 83, which gave a number back for HASH(NULL).
Now the one property of XOR that matters
BITXOR undoes itself. Apply it twice with the same second argument and you are back where you started. Let's watch that.
SELECT 12 AS ORIGINAL,
BITXOR(12, 7) AS XORED_WITH_7,
BITXOR(BITXOR(12, 7), 7) AS XORED_TWICE,
BITXOR(BITXOR(12, 7), 7) = 12 AS BACK_TO_THE_ORIGINAL,
BITXOR(12, 12) AS XOR_WITH_ITSELF;| ORIGINAL | XORED_WITH_7 | XORED_TWICE | BACK_TO_THE_ORIGINAL | XOR_WITH_ITSELF |
|---|---|---|---|---|
| 12 | 11 | 12 | TRUE | 0 |
12 exclusive-or 7 gave 11. Exclusive-or that with 7 again and we have 12 back, and the comparison column confirms it. The last column shows the other half of the same property: exclusive-or a number with itself and you get 0.
One literal is not a test. Let's do it on every order id in the table.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT_IF(BITXOR(BITXOR(ORDER_ID, 255), 255) = ORDER_ID) AS ROUND_TRIPPED,
COUNT_IF(BITXOR(ORDER_ID, ORDER_ID) = 0) AS XOR_WITH_SELF_IS_ZERO
FROM ORDERS;| ROWS_TOTAL | ROUND_TRIPPED | XOR_WITH_SELF_IS_ZERO |
|---|---|---|
| 41 | 41 | 41 |
All 41 order ids survived the round trip, and all 41 gave 0 against themselves.
That is why exclusive-or turns up in toggles, in simple masking and in checksums. One operation, used twice, is its own undo.
Let's shift the bits along
The two shift functions move every bit a given number of places left or right. Moving them left makes the number bigger and moving them right makes it smaller.
SELECT 12 AS ORIGINAL,
BITSHIFTLEFT(12, 1) AS LEFT_1,
BITSHIFTLEFT(12, 2) AS LEFT_2,
BITSHIFTRIGHT(12, 1) AS RIGHT_1,
BITSHIFTRIGHT(12, 2) AS RIGHT_2,
BITSHIFTRIGHT(13, 1) AS RIGHT_1_OF_AN_ODD_NUMBER;| ORIGINAL | LEFT_1 | LEFT_2 | RIGHT_1 | RIGHT_2 | RIGHT_1_OF_AN_ODD_NUMBER |
|---|---|---|---|---|---|
| 12 | 24 | 48 | 6 | 3 | 6 |
12 shifted left one place is 24, and left two places is 48. Each step to the left doubles it. Each step to the right halves it, so 12 goes to 6 and then to 3.
The last column is the interesting one. 13 shifted right one place is 6, not 6.5. The bit that fell off the end is gone, so this is a division that rounds down.
Let's put that next to the arithmetic it is supposed to match.
SELECT BITSHIFTLEFT(12, 3) AS SHIFTED_LEFT_3,
12 * POWER(2, 3) AS TIMES_8,
BITSHIFTRIGHT(13, 1) AS SHIFTED_RIGHT_1,
FLOOR(13 / 2) AS FLOOR_DIVIDE,
TRUNC(13 / 2) AS TRUNC_DIVIDE;| SHIFTED_LEFT_3 | TIMES_8 | SHIFTED_RIGHT_1 | FLOOR_DIVIDE | TRUNC_DIVIDE |
|---|---|---|---|---|
| 96 | 96.0 | 6 | 6 | 6 |
12 shifted left three places is 96, and 12 times 2 cubed is also 96. On the right-hand side, the shift, FLOOR and TRUNC all give 6, so this grid cannot tell us which rounding rule a shift uses. For that we need a negative number.
Now let's shift a negative number
This is where the two rounding rules part company. FLOOR rounds towards minus infinity and TRUNC rounds towards zero, and on a negative number those are different answers.
SELECT -8 AS ORIGINAL,
BITSHIFTRIGHT(-8, 1) AS RIGHT_1,
BITSHIFTRIGHT(-8, 2) AS RIGHT_2,
BITSHIFTLEFT(-8, 1) AS LEFT_1,
FLOOR(-8 / 2) AS FLOOR_DIVIDE_FOR_COMPARISON,
TRUNC(-8 / 2) AS TRUNC_DIVIDE_FOR_COMPARISON;| ORIGINAL | RIGHT_1 | RIGHT_2 | LEFT_1 | FLOOR_DIVIDE_FOR_COMPARISON | TRUNC_DIVIDE_FOR_COMPARISON |
|---|---|---|---|---|---|
| -8 | -4 | -2 | -16 | -4 | -4 |
-8 shifted right one place is -4 and right two places is -2, so it stayed negative the whole way. Shifted left one place it is -16.
And the two comparison columns both say -4 as well, so -8 still does not separate the rules. It divides exactly. But the sign is the thing we were after here, and the sign survived.
That tells us something specific. There are two kinds of right shift in computing. An arithmetic shift copies the sign bit along as it goes. A logical shift feeds in zeros, which turns a negative number into a large positive one. Let's find out which one this is.
SELECT BITSHIFTRIGHT(-8, 1) = FLOOR(-8 / 2) AS MATCHES_ARITHMETIC_SHIFT,
BITSHIFTRIGHT(-8, 1) > 0 AS BECAME_POSITIVE_LOGICAL_SHIFT,
BITSHIFTRIGHT(-1, 1) AS MINUS_ONE_SHIFTED,
BITSHIFTRIGHT(-1, 63) AS MINUS_ONE_SHIFTED_FAR;| MATCHES_ARITHMETIC_SHIFT | BECAME_POSITIVE_LOGICAL_SHIFT | MINUS_ONE_SHIFTED | MINUS_ONE_SHIFTED_FAR |
|---|---|---|---|
| TRUE | FALSE | -1 | -1 |
It matches the arithmetic shift, and it did not become positive. The proof is the last column: -1 shifted right 63 places is still -1.
Every bit in -1 is a one. Shift it as far as you like and the sign keeps being copied in behind it, so it can never become anything else. That is what an arithmetic shift means.
How far can we shift?
Bitwise operations are usually described as 64-bit, so you would expect shifting past 64 places to wrap around or overflow. Let's find out.
SELECT BITSHIFTLEFT(1, 30) AS LEFT_30,
BITSHIFTLEFT(1, 62) AS LEFT_62,
BITSHIFTLEFT(1, 63) AS LEFT_63,
BITSHIFTRIGHT(1, 64) AS RIGHT_64,
BITSHIFTRIGHT(1, 1) AS RIGHT_1;| LEFT_30 | LEFT_62 | LEFT_63 | RIGHT_64 | RIGHT_1 |
|---|---|---|---|---|
| 1073741824 | 4611686018427387904 | 9223372036854775808 | 0 | 0 |
1 shifted left 63 places came back as a very large number rather than an error. Let's check whether it is the number it should be, and where it sits against the signed 64-bit limit.
SELECT BITSHIFTLEFT(1, 63) AS LEFT_63,
POWER(2, 63)::NUMBER(38,0) AS TWO_TO_THE_63,
BITSHIFTLEFT(1, 63) = POWER(2, 63)::NUMBER(38,0) AS THEY_MATCH,
9223372036854775807 AS SIGNED_INT64_MAX,
BITSHIFTLEFT(1, 63) > 9223372036854775807 AS PAST_THE_INT64_MAX;| LEFT_63 | TWO_TO_THE_63 | THEY_MATCH | SIGNED_INT64_MAX | PAST_THE_INT64_MAX |
|---|---|---|---|---|
| 9223372036854775808 | 9223372036854775808 | TRUE | 9223372036854775807 | TRUE |
It equals 2 to the power 63 exactly, and it is greater than the largest signed 64-bit integer. So it did not wrap. Snowflake's NUMBER type simply carried it.
Let's push it further than that.
SELECT BITSHIFTLEFT(1, 64) AS LEFT_64,
BITSHIFTLEFT(1, 100) AS LEFT_100,
BITSHIFTLEFT(1, 200) AS LEFT_200,
BITSHIFTRIGHT(1, 200) AS RIGHT_200,
BITSHIFTLEFT(1, 63) AS LEFT_63_FOR_COMPARISON;| LEFT_64 | LEFT_100 | LEFT_200 | RIGHT_200 | LEFT_63_FOR_COMPARISON |
|---|---|---|---|---|
| 18446744073709551616 | 1267650600228229401496703205376 | 0 | 0 | 9223372036854775808 |
64 places and 100 places both gave honest large numbers. 200 places gave 0, and so did shifting right 200 places, with no error either time.
Now the question that actually tells us something. If a shift of 100 is a real shift rather than a truncation, it should reverse.
SELECT BITSHIFTRIGHT(BITSHIFTLEFT(1, 40), 40) AS SHIFT_40_AND_BACK,
BITSHIFTRIGHT(BITSHIFTLEFT(1, 64), 64) AS SHIFT_64_AND_BACK,
BITSHIFTRIGHT(BITSHIFTLEFT(1, 100), 100) AS SHIFT_100_AND_BACK,
BITSHIFTRIGHT(BITSHIFTLEFT(1, 40), 40) = 1 AS FORTY_SURVIVED,
BITSHIFTRIGHT(BITSHIFTLEFT(1, 100), 100) = 1 AS HUNDRED_SURVIVED;| SHIFT_40_AND_BACK | SHIFT_64_AND_BACK | SHIFT_100_AND_BACK | FORTY_SURVIVED | HUNDRED_SURVIVED |
|---|---|---|---|---|
| 1 | 1 | 1 | TRUE | TRUE |
Out 40 places and back again gives 1. Out 100 places and back again also gives 1. So these are not 64-bit operations with a wraparound. They are arithmetic on a much wider number.
And for completeness, a shift of zero.
SELECT BITSHIFTLEFT(8, 0) AS LEFT_BY_ZERO,
BITSHIFTRIGHT(8, 0) AS RIGHT_BY_ZERO,
BITSHIFTLEFT(8, 0) = 8 AS LEFT_ZERO_IS_IDENTITY,
BITSHIFTRIGHT(8, 0) = 8 AS RIGHT_ZERO_IS_IDENTITY;| LEFT_BY_ZERO | RIGHT_BY_ZERO | LEFT_ZERO_IS_IDENTITY | RIGHT_ZERO_IS_IDENTITY |
|---|---|---|---|
| 8 | 8 | TRUE | TRUE |
Both directions leave the number alone, as you would hope.
What happens when the shift count is negative?
Shifting left by -1 would be the same as shifting right by 1, so you might expect it to work. It does not.
SELECT BITSHIFTLEFT(8, -1) AS SHOULD_NOT_GET_THIS_FAR;100050 (22023): Invalid parameter value: -1. Reason: shift parameter must be greater or equal to zero
And the same thing the other way round.
SELECT BITSHIFTRIGHT(8, -1) AS SHOULD_NOT_GET_THIS_FAR;100050 (22023): Invalid parameter value: -1. Reason: shift parameter must be greater or equal to zero
Both refused, with the same message: the shift parameter must be greater than or equal to zero.
So the rule is not symmetric. Too far is fine and gives you 0. Backwards is an error.
SELECT BITSHIFTLEFT(1, 200) AS TWO_HUNDRED_IS_FINE,
BITSHIFTRIGHT(1, 200) AS SO_IS_THIS,
BITSHIFTLEFT(1, 0) AS ZERO_IS_FINE;| TWO_HUNDRED_IS_FINE | SO_IS_THIS | ZERO_IS_FINE |
|---|---|---|
| 0 | 0 | 1 |
200 places in either direction returns 0 without complaint, and a shift of nothing returns the number. All three of those ran. Only the negative count stopped the query.
Now the real reason to use any of this: packing flags
Here is what bitwise is for in a database. You have several yes-or-no facts about a row and you want them in one column instead of several.
Give each fact a bit. Bit 0 is worth 1, bit 1 is worth 2, bit 2 is worth 4. Add up the ones that are true and the total is a single number that holds all three answers.
Let's do it with three conditions about an order: is it shipped, is it a high-value order, did it fall on a weekend.
SELECT ORDER_ID, STATUS, AMOUNT, ORDER_DATE,
IFF(STATUS = 'Shipped', 1, 0)
+ IFF(AMOUNT >= 1000, 2, 0)
+ IFF(DATE_PART('dayofweek', ORDER_DATE) IN (0, 6), 4, 0) AS FLAGS
FROM ORDERS
ORDER BY ORDER_ID
LIMIT 10;| ORDER_ID | STATUS | AMOUNT | ORDER_DATE | FLAGS |
|---|---|---|---|---|
| 1001 | SHIPPED | 4200.00 | 2023-01-12 | 2 |
| 1002 | SHIPPED | 890.50 | 2023-01-28 | 4 |
| 1003 | SHIPPED | 6150.00 | 2023-02-14 | 2 |
| 1004 | CANCELLED | 1500.00 | 2023-02-27 | 2 |
| 1005 | SHIPPED | 2310.75 | 2023-03-09 | 2 |
| 1006 | SHIPPED | 5020.00 | 2023-03-22 | 2 |
| 1007 | SHIPPED | 7890.00 | 2023-04-05 | 2 |
| 1008 | SHIPPED | 1120.00 | 2023-04-19 | 2 |
| 1009 | SHIPPED | 3340.25 | 2023-05-02 | 2 |
| 1010 | PENDING | 640.00 | 2023-05-21 | 4 |
One FLAGS column holding three answers. A 2 means high value only. A 4 means weekend only. A 6 would mean both.
Let's read the flags back out
Packing is only half of it. To get an answer back out you BITAND the flags against the bit you want and test whether anything survived.
SELECT F.ORDER_ID, F.FLAGS,
BITAND(F.FLAGS, 1) > 0 AS IS_SHIPPED,
BITAND(F.FLAGS, 2) > 0 AS IS_HIGH_VALUE,
BITAND(F.FLAGS, 4) > 0 AS IS_WEEKEND
FROM (SELECT ORDER_ID, STATUS, AMOUNT, ORDER_DATE,
IFF(STATUS = 'Shipped', 1, 0)
+ IFF(AMOUNT >= 1000, 2, 0)
+ IFF(DATE_PART('dayofweek', ORDER_DATE) IN (0, 6), 4, 0) AS FLAGS
FROM ORDERS) F
ORDER BY F.ORDER_ID
LIMIT 10;| ORDER_ID | FLAGS | IS_SHIPPED | IS_HIGH_VALUE | IS_WEEKEND |
|---|---|---|---|---|
| 1001 | 2 | FALSE | TRUE | FALSE |
| 1002 | 4 | FALSE | FALSE | TRUE |
| 1003 | 2 | FALSE | TRUE | FALSE |
| 1004 | 2 | FALSE | TRUE | FALSE |
| 1005 | 2 | FALSE | TRUE | FALSE |
| 1006 | 2 | FALSE | TRUE | FALSE |
| 1007 | 2 | FALSE | TRUE | FALSE |
| 1008 | 2 | FALSE | TRUE | FALSE |
| 1009 | 2 | FALSE | TRUE | FALSE |
| 1010 | 4 | FALSE | FALSE | TRUE |
That reads cleanly. Now look down the IS_SHIPPED column.
It is FALSE on every one of those ten rows. And eight of the ten orders we just looked at are marked SHIPPED.
It is the comparison. The pack used IFF(STATUS = 'Shipped', 1, 0), and the table stores SHIPPED in capitals. The condition is false for every row in the table, so bit 0 is never set, and the only flag values that can ever occur are 0, 2, 4 and 6.
So let's check the pack against the conditions
This is the part I most want you to see. Let's write the reconciliation you would write in a real job: unpack each flag and compare it back against the condition it was built from.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT_IF((BITAND(F.FLAGS, 1) > 0) = (F.STATUS = 'Shipped')) AS SHIPPED_AGREES,
COUNT_IF((BITAND(F.FLAGS, 2) > 0) = (F.AMOUNT >= 1000)) AS HIGH_VALUE_AGREES,
COUNT_IF((BITAND(F.FLAGS, 4) > 0)
= (DATE_PART('dayofweek', F.ORDER_DATE) IN (0, 6))) AS WEEKEND_AGREES
FROM (SELECT ORDER_ID, STATUS, AMOUNT, ORDER_DATE,
IFF(STATUS = 'Shipped', 1, 0)
+ IFF(AMOUNT >= 1000, 2, 0)
+ IFF(DATE_PART('dayofweek', ORDER_DATE) IN (0, 6), 4, 0) AS FLAGS
FROM ORDERS) F;| ROWS_TOTAL | SHIPPED_AGREES | HIGH_VALUE_AGREES | WEEKEND_AGREES |
|---|---|---|---|
| 41 | 41 | 40 | 41 |
Shipped agrees on 41 rows out of 41.
The check passes. The check is also correct. And the data is wrong.
Both sides of that comparison use the same broken condition. The pack asked STATUS = 'Shipped' and got false. The check asked STATUS = 'Shipped' and got false. False equals false, on all 41 rows, so it agrees with itself perfectly.
A round-trip check proves that your pack and your unpack are consistent with each other. It cannot prove that the condition was right in the first place. Those are two different questions, and this grid answers the easy one while looking like it answered the hard one.
The thing that would have caught it is sitting in the grid two sections up: the STATUS column itself, in capitals.
And the other column is wrong in a different way
HIGH_VALUE_AGREES is 40, not 41. That is a second failure in the same grid, and it has nothing to do with the first.
COUNT_IF counts the rows where its condition is TRUE. For one order the comparison came out NULL rather than true or false, so it was neither counted nor reported as a disagreement.
That happens when the amount is NULL. AMOUNT >= 1000 on a NULL is NULL, and FALSE = NULL is NULL too. So the row vanished from the count instead of failing it.
Two different problems, side by side in one grid, and neither of them raised an error.
Now let's set, clear and toggle a flag
Once a value is packed you still want to change individual bits in it. There are three operations and each one uses a different function.
Let's start from 5, which is bit 0 and bit 2 together.
SELECT 5 AS FLAGS_SHIPPED_AND_WEEKEND,
BITOR(5, 2) AS SET_HIGH_VALUE,
BITAND(5, BITNOT(1)) AS CLEAR_SHIPPED,
BITAND(5, BITNOT(2)) AS CLEAR_A_FLAG_THAT_WAS_NOT_SET,
BITXOR(5, 1) AS TOGGLE_SHIPPED;| FLAGS_SHIPPED_AND_WEEKEND | SET_HIGH_VALUE | CLEAR_SHIPPED | CLEAR_A_FLAG_THAT_WAS_NOT_SET | TOGGLE_SHIPPED |
|---|---|---|---|---|
| 5 | 7 | 4 | 5 | 4 |
To set a bit, BITOR it in. 5 or 2 gives 7, which is all three bits on.
To clear a bit, BITAND with BITNOT of that bit. 5 with bit 0 cleared gives 4.
And clearing a bit that was not set gives 5 back, unchanged. That is what you want. You can run it twice and nothing happens the second time.
To toggle, use BITXOR. 5 exclusive-or 1 gives 4, and doing it again brings 5 back.
That is also where BITNOT of 12 being -13 comes from, by the way. BITNOT flips every bit, including the sign bit, which is why you almost always use it inside a BITAND as a mask rather than on its own.
Which flag combinations actually occur?
Let's group the whole table by its packed value and see what is really in there.
SELECT F.FLAGS, COUNT(*) AS N,
BITAND(F.FLAGS, 1) > 0 AS SHIPPED,
BITAND(F.FLAGS, 2) > 0 AS HIGH_VALUE,
BITAND(F.FLAGS, 4) > 0 AS WEEKEND
FROM (SELECT IFF(STATUS = 'Shipped', 1, 0)
+ IFF(AMOUNT >= 1000, 2, 0)
+ IFF(DATE_PART('dayofweek', ORDER_DATE) IN (0, 6), 4, 0) AS FLAGS
FROM ORDERS) F
GROUP BY F.FLAGS
ORDER BY N DESC;| FLAGS | N | SHIPPED | HIGH_VALUE | WEEKEND |
|---|---|---|---|---|
| 2 | 27 | FALSE | TRUE | FALSE |
| 6 | 9 | FALSE | TRUE | TRUE |
| 4 | 3 | FALSE | FALSE | TRUE |
| 0 | 2 | FALSE | FALSE | FALSE |
Four combinations. Flags 2 on 27 orders, flags 6 on 9, flags 4 on 3 and flags 0 on 2. Those add up to the 41 orders in the table.
SHIPPED is FALSE on all four rows, which is the same bug again, now visible as the shape of the whole result rather than one column of one row.
And a sanity check on the range.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT_IF(F.FLAGS BETWEEN 0 AND 7) AS IN_RANGE,
COUNT(DISTINCT F.FLAGS) AS DISTINCT_COMBINATIONS,
MAX(F.FLAGS) AS HIGHEST_SEEN
FROM (SELECT IFF(STATUS = 'Shipped', 1, 0)
+ IFF(AMOUNT >= 1000, 2, 0)
+ IFF(DATE_PART('dayofweek', ORDER_DATE) IN (0, 6), 4, 0) AS FLAGS
FROM ORDERS) F;| ROWS_TOTAL | IN_RANGE | DISTINCT_COMBINATIONS | HIGHEST_SEEN |
|---|---|---|---|
| 41 | 41 | 4 | 6 |
All 41 rows are inside 0 to 7, which is the range three bits can hold. 4 distinct combinations, and the highest value seen is 6.
6 rather than 7, because bit 0 never fires. That check tells you about the bug too, if you read it rather than just noting that it passed.
What happens if we give BITAND a decimal?
Bits only exist in whole numbers, so a decimal has to be converted first. The question is which way it converts: does 12.5 become 12, or 13?
Let's find out.
SELECT BITAND(12.5, 10) AS DECIMAL_FIRST_ARG,
BITAND(12, 10) AS INTEGER_FOR_COMPARISON,
BITAND(12.4, 10) AS ROUNDS_DOWN_OR_TRUNCATES,
BITAND(12.6, 10) AS AND_THIS_ONE,
ROUND(12.5) AS ROUND_SAYS,
TRUNC(12.5) AS TRUNC_SAYS;| DECIMAL_FIRST_ARG | INTEGER_FOR_COMPARISON | ROUNDS_DOWN_OR_TRUNCATES | AND_THIS_ONE | ROUND_SAYS | TRUNC_SAYS |
|---|---|---|---|---|---|
| 8 | 8 | 8 | 8 | 13 | 12 |
Every BITAND column came back 8, whether the input was 12, 12.4, 12.5 or 12.6. The last two columns show what the two candidate rules would do: ROUND(12.5) is 13 and TRUNC(12.5) is 12.
So both rules lead to the same answer here, which means this grid cannot tell them apart. Let's write the comparison out explicitly and see it say so.
SELECT BITAND(12.6, 10) = BITAND(TRUNC(12.6), 10) AS MATCHES_TRUNC,
BITAND(12.6, 10) = BITAND(ROUND(12.6), 10) AS MATCHES_ROUND,
BITAND(12.4, 10) = BITAND(TRUNC(12.4), 10) AS MATCHES_TRUNC_ROUNDING_DOWN,
BITAND(12.4, 10) = BITAND(ROUND(12.4), 10) AS MATCHES_ROUND_ROUNDING_DOWN;| MATCHES_TRUNC | MATCHES_ROUND | MATCHES_TRUNC_ROUNDING_DOWN | MATCHES_ROUND_ROUNDING_DOWN |
|---|---|---|---|
| TRUE | TRUE | TRUE | TRUE |
All four columns say TRUE. It matches truncate and it matches round, at the same time, both ways.
I have learned nothing, and it is my own fault. I masked with 10. In binary 10 is 1010, and 12 and 13 differ only in their last bit — the one bit that 10 does not look at.
A test that cannot fail is not a test. It still runs, it still produces a grid, and every column in that grid says TRUE. Nothing about the output tells you the question went unanswered.
Let's design a test that can fail
Mask with 1 instead. Then the only bit being looked at is the one where 12 and 13 disagree, so the two rules have to give different answers.
SELECT BITAND(12.4, 1) AS DECIMAL_12_4,
BITAND(12, 1) AS BOTH_RULES_GIVE_12,
BITAND(12.6, 1) AS DECIMAL_12_6,
BITAND(12.6, 1) = BITAND(12, 1) AS TWELVE_POINT_SIX_MATCHES_TRUNC,
BITAND(12.6, 1) = BITAND(13, 1) AS TWELVE_POINT_SIX_MATCHES_ROUND;| DECIMAL_12_4 | BOTH_RULES_GIVE_12 | DECIMAL_12_6 | TWELVE_POINT_SIX_MATCHES_TRUNC | TWELVE_POINT_SIX_MATCHES_ROUND |
|---|---|---|---|---|
| 0 | 0 | 1 | FALSE | TRUE |
Now it separates. BITAND(12.6, 1) is 1, while BITAND(12, 1) is 0. So 12.6 did not become 12. It became 13, and the last two columns say exactly that: it does not match truncate, and it does match round.
12.4 is in the same grid, and it gives 0 just like 12 does. That one settles nothing either, because rounding 12.4 and truncating 12.4 both give 12. It is in there as the control.
One decisive value is thin. Let's do it again on a different number, one where rounding crosses to an even number instead of an odd one.
SELECT BITAND(7.5, 1) AS SEVEN_POINT_FIVE,
BITAND(7, 1) AS SEVEN,
BITAND(8, 1) AS EIGHT,
BITAND(7.5, 1) = BITAND(7, 1) AS MATCHES_TRUNC,
BITAND(7.5, 1) = BITAND(8, 1) AS MATCHES_ROUND;| SEVEN_POINT_FIVE | SEVEN | EIGHT | MATCHES_TRUNC | MATCHES_ROUND |
|---|---|---|---|---|
| 0 | 1 | 0 | FALSE | TRUE |
BITAND(7.5, 1) is 0. 7 would give 1 and 8 gives 0, so 7.5 became 8. It does not match truncate and it does match round, which is the same verdict as before.
So BITAND rounds a decimal. It does not truncate it. That agrees with what casting a decimal to INT did back in Episode 77, which is reassuring — one rule, not a special case.
And the other operators?
SELECT BITOR(12.5, 10) AS BITOR_DECIMAL,
BITXOR(12.5, 10) AS BITXOR_DECIMAL,
BITSHIFTLEFT(12.5, 1) AS SHIFT_DECIMAL,
BITNOT(12.5) AS BITNOT_DECIMAL;| BITOR_DECIMAL | BITXOR_DECIMAL | SHIFT_DECIMAL | BITNOT_DECIMAL |
|---|---|---|---|
| 15 | 7 | 26 | -14 |
BITOR, BITXOR, the shifts and BITNOT all accept the decimal and all behave like they were handed 13 rather than 12. One rule across the whole family.
One last thing: all of it on one grid
One query, one order per row, every operator from this post side by side.
SELECT ORDER_ID,
BITAND(ORDER_ID, 7) AS LOW_THREE_BITS,
BITOR(ORDER_ID, 8) AS WITH_BIT_3_SET,
BITXOR(ORDER_ID, 255) AS INVERTED_LOW_BYTE,
BITSHIFTLEFT(ORDER_ID, 1) AS DOUBLED,
BITSHIFTRIGHT(ORDER_ID, 1) AS HALVED,
BITXOR(BITXOR(ORDER_ID, 255), 255) = ORDER_ID AS ROUND_TRIPPED
FROM ORDERS
ORDER BY ORDER_ID
LIMIT 5;| ORDER_ID | LOW_THREE_BITS | WITH_BIT_3_SET | INVERTED_LOW_BYTE | DOUBLED | HALVED | ROUND_TRIPPED |
|---|---|---|---|---|---|---|
| 1001 | 1 | 1001 | 790 | 2002 | 500 | TRUE |
| 1002 | 2 | 1002 | 789 | 2004 | 501 | TRUE |
| 1003 | 3 | 1003 | 788 | 2006 | 501 | TRUE |
| 1004 | 4 | 1004 | 787 | 2008 | 502 | TRUE |
| 1005 | 5 | 1005 | 786 | 2010 | 502 | TRUE |
The low three bits of the id, the id with bit 3 forced on, the id with its low byte inverted, the id doubled, the id halved, and the check that the inversion reverses.
Have a look at the halved column against the ids. 1002 and 1003 both halve to 501, because the shift threw away the odd bit. Two different ids, one result. That is the rounding we established earlier, and it is the reason a right shift is not a safe stand-in for division when you need to get the original back.
Key points
BITAND,BITOR,BITXORandBITNOTwork on the bits of an integer.BITANDagainst a single bit returns that bit's value, not a 1.- Any
NULLargument makes the whole resultNULL. BITXORis its own inverse. Apply it twice and you are back, and a number against itself gives 0.BITSHIFTLEFTdoubles per step.BITSHIFTRIGHThalves per step and rounds down, so it loses the odd bit.- The shifts are arithmetic, not logical: a negative number stays negative, and -1 shifted right 63 places is still -1.
- Shifting too far returns 0 with no error. Shifting by a negative count is an error.
BITSHIFTLEFT(1, 63)goes one past the signed 64-bit maximum without wrapping, and a shift of 100 places reverses cleanly, becauseNUMBERcarries it.- Pack flags with addition or
BITOR, read them withBITAND, set withBITOR, clear withBITANDplusBITNOT, toggle withBITXOR. - A round-trip check only proves your pack and your unpack agree. It cannot tell you the condition was right. The check here reported 41 of 41 on a column that was never set.
COUNT_IFsilently drops a row whose condition evaluates toNULL, which is why one count read 40 where the others read 41.BITANDrounds a decimal rather than truncating it, and so do the rest of the family. Same rule as casting toINT.
Episode 85 — GENERATOR and the sequence functions, and the last post in Level 7. Making rows out of nothing, a date spine, and a daily sales report that looks finished while leaving most of the calendar out without saying so.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode. The ORDERS data is invented demo data created by that script. The flag-packing bug and the two tests that proved nothing are left exactly as they came out of the database. Nothing here is timed and no performance claims are made anywhere in this series. Function behaviour follows the Snowflake bitwise expression documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.