All Products
Search
Document Center

PolarDB:RIGHT_SHIFT

Last Updated:Mar 28, 2026

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:

  1. Perform a signed right shift on the shard key value: shardKey >> n

  2. Divide 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 1

The 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

ParameterTypeDescription
shardKeyColumn referenceThe shard key column. Must be an integer type.
nIntegerNumber of bits to shift right. Must not exceed the bit width of the shard key type (for example, 32 for INT).

Usage notes

  • RIGHT_SHIFT produces 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:

PlaceholderDescriptionExample
idShard key column — must be an integer typeuser_id, order_id
8Bits to shift right — adjust to match the number of fixed low-order bits in your key values4, 8, 16
4Number of table shards per database shard4, 8