The HASH function distributes rows across database shards or table shards by computing the modulo of each shard key value against the total shard count. Use it when shard key values are integers or strings (such as user IDs or order IDs) and are evenly distributed.
How it works
HASH routing depends on whether the database shard key and the table shard key are the same column or different columns.
Different shard keys for database sharding and table sharding
The shard key value is divided by the number of database shards to determine which database shard receives the row:
Integer key:
HASH(8)is equivalent to8 % D, whereDis the number of database shards.String key:
HASH("ABC")is equivalent tohashcode("ABC").abs() % D. The string is first converted to a hash value, then used for routing.
Same shard key for database sharding and table sharding
The shard key value is divided by the total number of table shards across all database shards.
Example: Two database shards, four table shards each (eight total table shards).
Database shard 0 stores table shards 0 to 3.
Database shard 1 stores table shards 4 to 7.
Key value
15:15 % (2 × 4) = 7routes the row to table shard 7 in database shard 1.
Supported data types
| Data type | Behavior |
|---|---|
| INTEGER | Key value used directly in modulo calculation |
| STRING | Key value converted to a hash value before modulo calculation; case-sensitive |
Shard keys must be INTEGER or STRING type. STRING type shard keys are case-sensitive during data routing.
Use cases
Database sharding based on user IDs or order IDs.
Shard key values are strings.
HASH produces even data distribution only when the values in the shard key column are themselves evenly distributed.
Example
The following DDL statement creates a table that uses HASH sharding on the id column for database sharding only:
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 HASH(ID);