SHIFTRIGHT
Function
Performs an arithmetic right bit-shift operation on an integer value. Arithmetic right shift preserves the sign bit, so negative numbers remain negative after the shift. Shifting right by n bits is equivalent to integer division by 2n (floor). Supports int and bigint types.
Parameters
value: int or bigint type, the value to shiftn: int type, the number of bit positions to shift; must be greater than or equal to 0
Return Value
- The same type as
value(int or bigint) - Returns the result after the right shift
- Returns NULL if
valueornis NULL
Examples
Notes
shiftrightis an arithmetic right shift that preserves the sign bit- For positive numbers: shiftright(x, n) = floor(x / 2n)
- For negative numbers, arithmetic right shift preserves the sign bit; the result remains negative
- Right shift is equivalent to integer division (floor)
- Difference from
shiftrightunsigned:shiftrightis arithmetic right shift, preserving the sign bitshiftrightunsignedis logical right shift, filling the most significant bit with 0
- Example: for -4 (binary representation: 11111111111111111111111111111100)
- shiftright(-4, 2) = -1 (sign bit preserved)
- shiftrightunsigned(-4, 2) = 1073741823 (most significant bit filled with 0)
- Bit-shift operations are faster than division
- Common use cases:
- Fast division by powers of 2
- Bit flag and bit mask operations
- Data encoding and decoding
- Related functions:
shiftleft— left shiftshiftrightunsigned— logical right shift (does not preserve sign bit)
