Snowflake SQL Tutorial 84 - BITAND, BITOR, BITXOR, BITNOT, Shifts - Bitwise Functions

Snowflake SQL · Episode 84

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

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.

Sample data
-- 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.

Query
SELECT ORDER_ID, CUSTOMER_ID, ORDER_DATE, AMOUNT, STATUS
FROM ORDERS ORDER BY ORDER_ID LIMIT 10;
Result10 rows · 5 columns
ORDER_IDCUSTOMER_IDORDER_DATEAMOUNTSTATUS
10011012023-01-124200.00SHIPPED
10021022023-01-28890.50SHIPPED
10031012023-02-146150.00SHIPPED
10041032023-02-271500.00CANCELLED
10051042023-03-092310.75SHIPPED
10061012023-03-225020.00SHIPPED
10071052023-04-057890.00SHIPPED
10081022023-04-191120.00SHIPPED
10091032023-05-023340.25SHIPPED
10101062023-05-21640.00PENDING

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.

Query
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_;
Result1 row · 6 columns · scroll →
ABAND_OR_XOR_NOT_
12108146-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.

Query
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;
Result4 rows · 5 columns
ABAND_OR_XOR_
00000
01011
10011
11110

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.

Query
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;
Result16 rows · 7 columns · scroll →
NAS_BINARY_TYPEPADDED_DECIMALBIT_0BIT_1BIT_2BIT_3
0bytearray(b'0') 0000000
1bytearray(b'1') 0001000
2bytearray(b'2') 0000200
3bytearray(b'3') 0001200
4bytearray(b'4') 0000040
5bytearray(b'5') 0001040
6bytearray(b'6') 0000240
7bytearray(b'7') 0001240
8bytearray(b'8') 0000008
9bytearray(b'9') 0001008
10bytearray(b'10') 0010208
11bytearray(b'11') 0011208
12bytearray(b'12') 0010048
13bytearray(b'13') 0011048
14bytearray(b'14') 0010248
15bytearray(b'15') 0011248

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 columns in that grid are not what they look like

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.

Query
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;
Result1 row · 5 columns
AND_NULLOR_NULLXOR_NULLNOT_NULLBOTH_NULL
NULLNULLNULLNULLNULL

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.

Query
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;
Result1 row · 5 columns
ORIGINALXORED_WITH_7XORED_TWICEBACK_TO_THE_ORIGINALXOR_WITH_ITSELF
121112TRUE0

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.

Query
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;
Result1 row · 3 columns
ROWS_TOTALROUND_TRIPPEDXOR_WITH_SELF_IS_ZERO
414141

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.

Query
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;
Result1 row · 6 columns · scroll →
ORIGINALLEFT_1LEFT_2RIGHT_1RIGHT_2RIGHT_1_OF_AN_ODD_NUMBER
122448636

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.

Query
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;
Result1 row · 5 columns
SHIFTED_LEFT_3TIMES_8SHIFTED_RIGHT_1FLOOR_DIVIDETRUNC_DIVIDE
9696.0666

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.

Query
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;
Result1 row · 6 columns · scroll →
ORIGINALRIGHT_1RIGHT_2LEFT_1FLOOR_DIVIDE_FOR_COMPARISONTRUNC_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.

Query
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;
Result1 row · 4 columns
MATCHES_ARITHMETIC_SHIFTBECAME_POSITIVE_LOGICAL_SHIFTMINUS_ONE_SHIFTEDMINUS_ONE_SHIFTED_FAR
TRUEFALSE-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.

Query
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;
Result1 row · 5 columns
LEFT_30LEFT_62LEFT_63RIGHT_64RIGHT_1
10737418244611686018427387904922337203685477580800

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.

Query
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;
Result1 row · 5 columns
LEFT_63TWO_TO_THE_63THEY_MATCHSIGNED_INT64_MAXPAST_THE_INT64_MAX
92233720368547758089223372036854775808TRUE9223372036854775807TRUE

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.

Query
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;
Result1 row · 5 columns
LEFT_64LEFT_100LEFT_200RIGHT_200LEFT_63_FOR_COMPARISON
184467440737095516161267650600228229401496703205376009223372036854775808

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.

Query
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;
Result1 row · 5 columns
SHIFT_40_AND_BACKSHIFT_64_AND_BACKSHIFT_100_AND_BACKFORTY_SURVIVEDHUNDRED_SURVIVED
111TRUETRUE

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.

Query
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;
Result1 row · 4 columns
LEFT_BY_ZERORIGHT_BY_ZEROLEFT_ZERO_IS_IDENTITYRIGHT_ZERO_IS_IDENTITY
88TRUETRUE

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.

The query that fails
SELECT BITSHIFTLEFT(8, -1) AS SHOULD_NOT_GET_THIS_FAR;
Query failed — Snowflake returned an error
100050 (22023): Invalid parameter value: -1. Reason: shift parameter must be greater or equal to zero

And the same thing the other way round.

The query that fails
SELECT BITSHIFTRIGHT(8, -1) AS SHOULD_NOT_GET_THIS_FAR;
Query failed — Snowflake returned an error
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.

Query
SELECT BITSHIFTLEFT(1, 200)  AS TWO_HUNDRED_IS_FINE,
       BITSHIFTRIGHT(1, 200) AS SO_IS_THIS,
       BITSHIFTLEFT(1, 0)    AS ZERO_IS_FINE;
Result1 row · 3 columns
TWO_HUNDRED_IS_FINESO_IS_THISZERO_IS_FINE
001

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.

Query
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;
Result10 rows · 5 columns
ORDER_IDSTATUSAMOUNTORDER_DATEFLAGS
1001SHIPPED4200.002023-01-122
1002SHIPPED890.502023-01-284
1003SHIPPED6150.002023-02-142
1004CANCELLED1500.002023-02-272
1005SHIPPED2310.752023-03-092
1006SHIPPED5020.002023-03-222
1007SHIPPED7890.002023-04-052
1008SHIPPED1120.002023-04-192
1009SHIPPED3340.252023-05-022
1010PENDING640.002023-05-214

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.

Query
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;
Result10 rows · 5 columns
ORDER_IDFLAGSIS_SHIPPEDIS_HIGH_VALUEIS_WEEKEND
10012FALSETRUEFALSE
10024FALSEFALSETRUE
10032FALSETRUEFALSE
10042FALSETRUEFALSE
10052FALSETRUEFALSE
10062FALSETRUEFALSE
10072FALSETRUEFALSE
10082FALSETRUEFALSE
10092FALSETRUEFALSE
10104FALSEFALSETRUE

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.

Query
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;
Result1 row · 4 columns
ROWS_TOTALSHIPPED_AGREESHIGH_VALUE_AGREESWEEKEND_AGREES
41414041

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.

What that 41 does and does not tell you

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.

Query
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;
Result1 row · 5 columns
FLAGS_SHIPPED_AND_WEEKENDSET_HIGH_VALUECLEAR_SHIPPEDCLEAR_A_FLAG_THAT_WAS_NOT_SETTOGGLE_SHIPPED
57454

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.

Query
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;
Result4 rows · 5 columns
FLAGSNSHIPPEDHIGH_VALUEWEEKEND
227FALSETRUEFALSE
69FALSETRUETRUE
43FALSEFALSETRUE
02FALSEFALSEFALSE

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.

Query
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;
Result1 row · 4 columns
ROWS_TOTALIN_RANGEDISTINCT_COMBINATIONSHIGHEST_SEEN
414146

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.

Query
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;
Result1 row · 6 columns · scroll →
DECIMAL_FIRST_ARGINTEGER_FOR_COMPARISONROUNDS_DOWN_OR_TRUNCATESAND_THIS_ONEROUND_SAYSTRUNC_SAYS
88881312

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.

Query
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;
Result1 row · 4 columns
MATCHES_TRUNCMATCHES_ROUNDMATCHES_TRUNC_ROUNDING_DOWNMATCHES_ROUND_ROUNDING_DOWN
TRUETRUETRUETRUE

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.

Worth sitting with for a second

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.

Query
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;
Result1 row · 5 columns
DECIMAL_12_4BOTH_RULES_GIVE_12DECIMAL_12_6TWELVE_POINT_SIX_MATCHES_TRUNCTWELVE_POINT_SIX_MATCHES_ROUND
001FALSETRUE

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.

Query
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;
Result1 row · 5 columns
SEVEN_POINT_FIVESEVENEIGHTMATCHES_TRUNCMATCHES_ROUND
010FALSETRUE

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?

Query
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;
Result1 row · 4 columns
BITOR_DECIMALBITXOR_DECIMALSHIFT_DECIMALBITNOT_DECIMAL
15726-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.

Query
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;
Result5 rows · 7 columns · scroll →
ORDER_IDLOW_THREE_BITSWITH_BIT_3_SETINVERTED_LOW_BYTEDOUBLEDHALVEDROUND_TRIPPED
1001110017902002500TRUE
1002210027892004501TRUE
1003310037882006501TRUE
1004410047872008502TRUE
1005510057862010502TRUE

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, BITXOR and BITNOT work on the bits of an integer. BITAND against a single bit returns that bit's value, not a 1.
  • Any NULL argument makes the whole result NULL.
  • BITXOR is its own inverse. Apply it twice and you are back, and a number against itself gives 0.
  • BITSHIFTLEFT doubles per step. BITSHIFTRIGHT halves 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, because NUMBER carries it.
  • Pack flags with addition or BITOR, read them with BITAND, set with BITOR, clear with BITAND plus BITNOT, toggle with BITXOR.
  • 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_IF silently drops a row whose condition evaluates to NULL, which is why one count read 40 where the others read 41.
  • BITAND rounds a decimal rather than truncating it, and so do the rest of the family. Same rule as casting to INT.
Next in this series

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.