RIGHT_SHIFT is a sharding function for PolarDB-X 1.0 that routes rows by shifting the shard key value right by a fixed number of bits before applying a modulo operation. Use it when the low-order bits of your shard key are flags or padding that carry no distribution signal — shifting them out before the modulo produces a more even spread across shards.
How it works
RIGHT_SHIFT(shardKey, n) routes a row in two steps:
Perform a signed right shift on the shard key value:
shardKey >> nDivide the result by the number of database or table shards and take the remainder:
(shardKey >> n) % shardCount
The remainder determines which shard the row goes to.
Example: With four database shards and the key 0x0100:
RIGHT_SHIFT(0x0100, 8) = 0x01 = 1
1 % 4 = 1 -> shard 1The same logic maps 0x0200, 0x0300, and 0x0400 to shards 2, 3, and 0 respectively — distributing the four values across four shards.
When to use RIGHT_SHIFT
Use RIGHT_SHIFT when the high-order bits of your shard key vary across rows but the low-order bits are fixed — for example, when the rightmost bits encode status flags, version numbers, or type identifiers.
With plain modulo sharding, those fixed low-order bits dominate the remainder calculation, and many rows land on the same shard. Shifting the fixed bits out restores distribution signal from the higher-order bits.
Parameters
| Parameter | Type | Description |
|---|---|---|
shardKey | Column reference | The shard key column. Must be an integer type. |
n | Integer | Number of bits to shift right. Must not exceed the bit width of the shard key type (for example, 32 for INT). |
Usage notes
RIGHT_SHIFTproduces an even distribution only when the high-order bits — the bits that remain after shifting — vary sufficiently across shard key values. If those remaining bits are also clustered or sequential, distribution may still be uneven.Specify the bit-shift count in your DDL statement.
The shift is a signed (arithmetic) right shift: the sign bit is preserved.
Limitations
The shard key must be an integer column.
PolarDB-X 1.0 instance version 5.1.28-1320920 or later is required.
Partition a table with RIGHT_SHIFT
The following example partitions test_hash_tb by the id column, shifting 8 bits right. The table is split into 4 table shards per database shard.
CREATE TABLE test_hash_tb (
id INT,
name VARCHAR(30) DEFAULT NULL,
create_time DATETIME DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8
dbpartition BY RIGHT_SHIFT(id, 8)
tbpartition BY RIGHT_SHIFT(id, 8) tbpartitions 4;Replace the placeholder values:
| Placeholder | Description | Example |
|---|---|---|
id | Shard key column — must be an integer type | user_id, order_id |
8 | Bits to shift right — adjust to match the number of fixed low-order bits in your key values | 4, 8, 16 |
4 | Number of table shards per database shard | 4, 8 |