Overview of the RIGHT_SHIFT() Function in SQL Server

In SQL Server, RIGHT_SHIFT() is a bit manipulation function that returns the first argument bit-shifted right by the number of bits specified in the second argument.

The RIGHT_SHIFT() function was introduced in SQL Server 2022.

Syntax

The syntax goes like this:

RIGHT_SHIFT ( expression_value, shift_amount )

There’s also a << operator that does the same thing. The syntax for this operator goes like this:

expression_value >> shift_amount

In both cases, expression_value can be any integer or binary expression that isn’t a large object (LOB).

The shift_amount argument must be an integer type.

Example

Here’s an example to demonstrate:

SELECT RIGHT_SHIFT(12345, 1);

Result:

6172

In order to understand the result, we need to see what happened to the binary representation of the specified number.

The following table contains the above integer values and their equivalent binary values:

IntegerBinary
123450011 0000 0011 1001
61720001 1000 0001 1100

If we look at the two binary values, we can see that the second one is almost the same as the first one, except that the bits have been shifted to the right by 1. A zero has been added to the left, and this has pushed all other bits to the right.

This effect can be easier to see if we remove the spaces:

0011000000111001
0001100000011100

The effect can be even easier to see if we do the following:

0011000000111001
 0011000000111001

We’ve effectively just moved the whole bottom value to the right. The RIGHT_SHIFT() function does the same thing, but removes the rightmost digit and adds a zero to the left.

The resulting binary value is the equivalent of 6172, and so that’s what is returned by the RIGHT_SHIFT() function.

Let’s shift the same value by two:

SELECT RIGHT_SHIFT(12345, 2);

Result:

3086

The integer result is quite different again.

Let’s look at the binary representation of the two values:

IntegerBinary
123450011 0000 0011 1001
30860000 1100 0000 1110

This time the second binary value has had its bits shifted to the right by two.

Negative Shift Amounts

It’s possible to pass a negative value to the RIGHT_SHIFT() function in order to shift the bits to the left, instead of to the right:

SELECT RIGHT_SHIFT(12345, -1);

Result:

24690

Here’s the binary representation of the two values:

IntegerBinary
123450011 0000 0011 1001
246900110 0000 0111 0010

So we can see that the bottom value is almost the same as the top value, except that its bits have been shifted to the left by one digit.

This is the same outcome that we’d get if we’d used the LEFT_SHIFT() function with a shift value of 1.

The Right Shift Operator (>>)

There’s also a right shift operator (>>) that does the same thing as the RIGHT_SHIFT() function:

SELECT 12345 >> 2;

Result:

3086

Here they are together:

SELECT
  RIGHT_SHIFT(12345, 2) AS "RIGHT_SHIFT",
  12345 >> 2 AS ">>";

Result:

RIGHT_SHIFT >>         
----------- -----------
       3086        3086