

# CREATE SCALEOUT ROUTING FUNCTION

Use `CREATE SCALEOUT ROUTING FUNCTION` to define how a routing key places rows in the collocations of a database cluster group for Aurora.

## Description and syntax
<a name="databaseclustergroups-sql-create-scaleout-routing-function-syntax"></a>

Creates a routing function: the rule that maps a routing key value to a collocation, and so to the member cluster that holds that collocation. A scaleout table names a routing function to place its rows. Because the function maps each key to a collocation and not to a member cluster, you can move a collocation to another member cluster without changing the function. Tables whose rows stay together share one function. For the concepts, see [Scaleout tables and routing functions](databaseclustergroups-scaleout-tables.md). To choose a function, see [Choosing a routing key and routing function](databaseclustergroups-routing-key.md).

```sql
CREATE SCALEOUT ROUTING FUNCTION {{function_name}}({{param}} {{type}} [, {{param}} {{type}} ...])
  AS PARTITION BY {{method}}({{arguments}})
  IN TARGET COLLOCATION (
    {{collocation_group}} { VALUES IN ({{value}} [, ...]) | VALUES IN RANGE ({{low}}, { {{high}} | MAXVALUE }) } [, ...]
  );

{{method}}({{arguments}}) ::=
    MOD({{param}}, {{divisor}})
  | HASH('{{algorithm}}', {{param}} [, {{param}} ...])
  | PREFIX({{param}}, '{{delimiter}}', {{depth}})
  | COLUMN({{param}})
```

Aurora provides the `MOD`, `HASH`, `PREFIX`, and `COLUMN` functions, and the routing layer refuses any other method. User-defined routing functions aren't supported. For a placement scheme that doesn't map to one of these functions, map each database with a data mapping, or connect with session pinning.

The following rules apply to `CREATE SCALEOUT ROUTING FUNCTION`:
+ Each declared key parameter appears exactly once in `PARTITION BY`. The divisor, algorithm, delimiter, and depth must be literals.
+ All collocations in one function use `VALUES IN`, or all use `VALUES IN RANGE`. You can't mix the two forms.
+ `VALUES IN RANGE ({{low}}, {{high}})` includes both bounds. Ranges can't overlap. Only the last range can use `MAXVALUE`, and only as its upper bound.
+ A value can't appear in two collocations. Each value or bound must fit the key's type and length, and the routing layer doesn't clamp or truncate it.
+ `PREFIX`: use a non-empty delimiter and a depth of 1 or more. With an empty delimiter, the routing layer rejects every statement on the table.
+ `COLUMN` on a `TIMESTAMP` key: the routing layer reads the bounds in your session's time zone, and [SHOW CREATE SCALEOUT ROUTING FUNCTION](databaseclustergroups-sql-show-create-scaleout-routing-function.md) shows them in your session's time zone.
+ Every collocation name must already exist on a data mapping. Collocation names are case-sensitive.
+ `MOD`: give the divisor as an integer literal of 1 or more. A collocation can take a list of remainders with `VALUES IN` or a range of remainders with `VALUES IN RANGE`.
+ `HASH`: the algorithm is one of the six algorithm names. Ranges cover 0 to 9223372036854775807, and the last range can end at `MAXVALUE`. The routing layer hashes key columns in signature order.
+ `DROP SCALEOUT ROUTING FUNCTION` on a function that a scaleout table uses returns error 64042, `Cannot drop routing function '<name>' referenced by scaleout tables`.

## Parameters and options
<a name="databaseclustergroups-sql-create-scaleout-routing-function-parameters"></a>

The statement takes the following parameters and options.

{{function\_name}}  
The routing function name, unique in the group.

{{param}} {{type}}  
A key parameter with the name and type of the routing key column of each table that uses the function, for example `tenant_rf(tenant_id BIGINT)`. `HASH` takes one or more parameters. `MOD`, `PREFIX`, and `COLUMN` take one. Use every parameter in the method arguments exactly once.  
The arguments, key data types, and collocation values depend on the function:  


<table>
<thead>
  <tr><th>Function</th><th>Arguments</th><th>Key data types (Aurora MySQL)</th><th>Collocation values</th></tr>
</thead>
<tbody>
  <tr><td><code>MOD</code></td><td>Key, integer divisor</td><td><code>TINYINT</code>, <code>SMALLINT</code>, <code>MEDIUMINT</code>, <code>INT</code>, <code>BIGINT</code></td><td><code>VALUES IN</code> remainders, or <code>VALUES IN RANGE</code> of remainders</td></tr>
  <tr><td><code>HASH</code></td><td>Algorithm string, one or more keys</td><td>Integer types, <code>CHAR</code>, <code>VARCHAR</code>, <code>TEXT</code>, <code>DATE</code>, <code>DATETIME</code>, <code>TIMESTAMP</code></td><td><code>VALUES IN RANGE</code> over 0 to 9223372036854775807</td></tr>
  <tr><td><code>PREFIX</code></td><td>Key, delimiter string, integer depth</td><td><code>CHAR</code>, <code>VARCHAR</code>, <code>TEXT</code></td><td><code>VALUES IN</code> prefixes, or <code>VALUES IN RANGE</code> of prefixes</td></tr>
  <tr><td><code>COLUMN</code></td><td>Key only</td><td>Integer types, <code>CHAR</code>, <code>VARCHAR</code>, <code>DATE</code>, <code>DATETIME</code>, <code>TIMESTAMP</code></td><td><code>VALUES IN</code> values, or <code>VALUES IN RANGE</code></td></tr>
</tbody>
</table>


MOD({{param}}, {{divisor}})  
The remainder of the key, `key % n`, which keeps the sign of the key, from `-(n-1)` to `n-1`, as the engine `MOD()` function does. A negative key gives a negative remainder: under `MOD(k, 6)`, -7 and -1 are both in bucket -1. Give the divisor as an integer literal of 1 or more. List the negative remainders in a collocation if your keys can be negative. Map the buckets with `VALUES IN` lists.

HASH('{{algorithm}}', {{param}} [, {{param}} ...])  
A hash of the key, as an integer from 0 to 9223372036854775807. Each collocation takes one range of that interval, so the ranges divide hash values, not key values. Several parameters give a composite key; keep the `ROUTE BY KEY` column order of each table the same as the parameter order. Map the ranges with `VALUES IN RANGE` from 0 to `MAXVALUE`.  
The {{algorithm}} is a quoted string, the first argument, written in lowercase. It is one of the following:  
+ `cityhash`, `xxhash`, or `md5` – Hashes a character key under the collation of the routing key, so two values that the collation compares as equal get the same hash.
+ `cityhash_normalized`, `xxhash_normalized`, or `md5_normalized` – Ignores the collation of the routing key. Lowercases a character key, removes all whitespace, and removes accents that Unicode can separate from the base letter, then hashes the result. Doesn't turn `ß` into `ss`, `ø` into `o`, or full-width letters into ASCII letters. Two values that the key's collation compares as equal can go to different member clusters. For a character key, use these algorithms only when the key has a binary collation, such as `utf8mb4_bin`.
Both forms of an algorithm hash integer and date and time keys the same way. The routing layer computes the hash itself; no statement returns the hash or the collocation of a key value.

PREFIX({{param}}, '{{delimiter}}', {{depth}})  
The key up to the end of its {{depth}}-th segment, cut at {{delimiter}}. `PREFIX` keeps the key up to that point and matches the result against the collocations. Under `PREFIX(k, '/', 1)`, `'us/nyc'` routes by `'us'`, and under `PREFIX(k, '/', 2)`, `'us/east/nyc'` routes by `'us/east'`. A leading delimiter stays in the result: at depth 1, `'/us/nyc'` routes by `'/us'`. `PREFIX` takes one key parameter. Map the prefixes with `VALUES IN` lists, or map one inclusive range of prefixes with `VALUES IN RANGE`.  
Give a non-empty {{delimiter}} and a {{depth}} of 1 or more. The routing layer matches the delimiter as plain text, compares the result under the routing key's collation, and rejects a key that has fewer segments than the depth or a prefix that no collocation lists. `PREFIX` isn't supported on a routing key with a Japanese collation.

COLUMN({{param}})  
The key value itself. `COLUMN` takes one key parameter. Map exact values with `VALUES IN` lists, or map one inclusive range with `VALUES IN RANGE`. One function uses lists or ranges, not both, and ranges can't overlap. The last range can end at `MAXVALUE`.  
`COLUMN` is the only routing function that routes a range predicate, and only with `VALUES IN RANGE` collocations on an integer, `DATE`, `DATETIME`, or `TIMESTAMP` key. On a `TIMESTAMP` key, the routing layer reads the bounds in your session's time zone.

{{collocation\_group}}  
A collocation that a data mapping already declares in `router_collocation_group`. Each name appears once in the map.

VALUES IN ({{value}} [, ...])  
The values of the collocation: `MOD` buckets, such as `(0, 3)`, `PREFIX` prefixes, such as `('us', 'ca')`, or `COLUMN` key values. A value belongs to one collocation only.

VALUES IN RANGE ({{low}}, { {{high}} \| MAXVALUE })  
A range of `HASH` values, `MOD` remainders, `PREFIX` prefixes, or `COLUMN` key values, both bounds included: `(0, 99)` holds 0 and 99. `MAXVALUE` leaves the top open. All entries in one map use the same form. Ranges can't share a bound, so start each integer range at the previous high value plus 1. For how to write adjacent date, time, and string ranges, see [COLUMN](databaseclustergroups-scaleout-tables.md#databaseclustergroups-routing-functions-column).

## Where it runs and required privileges
<a name="databaseclustergroups-sql-create-scaleout-routing-function-privileges"></a>

Run the statement at the routing endpoint, in a session that isn't pinned, outside a transaction. A pinned session passes the statement through to the member cluster unchanged. On Aurora MySQL, inside a transaction the routing layer refuses the statement with error 1179. For the details, see [Where these statements run](databaseclustergroups-sql-reference.md#databaseclustergroups-sql-where-statements-run).

The router user needs `dbclustergroup_metadata_admin` or `dbclustergroup_super_admin`. For all privileges for database cluster groups for Aurora, see [Privileges](databaseclustergroups-sql-reference.md#databaseclustergroups-sql-privileges).

## Usage notes
<a name="databaseclustergroups-sql-create-scaleout-routing-function-usage"></a>

Keep the following in mind when you use the statement.
+ Map the member tables first. Each collocation that the function targets must already exist in a data mapping.
+ The routing layer doesn't check that every key has a route. Under `MOD`, put every bucket from 0 to divisor - 1, and from -1 to -(divisor - 1) if keys can be negative, in exactly one collocation. Under `HASH`, start the ranges at 0, end them at `MAXVALUE`, and leave no gap. Under `PREFIX` and `COLUMN`, list every prefix or key value that your rows use, or cover the keys with ranges. The routing layer refuses a statement whose key maps to no collocation.
+ A scaleout table spreads across at most as many member clusters as its function has collocations. Create more collocations than you have member clusters today; two or more collocations can be on one member cluster.
+ Under `MOD`, `PREFIX`, and `COLUMN`, your application can compute the collocation of a key, for example to load each member table with its own rows. Under `MOD`, use the engine `MOD()` function, which keeps the sign of the key. Under `HASH`, no statement returns the hash, so load the rows through routed `INSERT` statements that carry the routing key. See [Loading data into member clusters](databaseclustergroups-loading-data.md).
+ A routing function has no `ALTER` statement. To change one, create a new function and switch the table to it. Change the routing function only of an empty scaleout table. The change moves no rows, so you can't read a row by its routing key if the new function sends that key to another collocation. See [Changing a routing function](databaseclustergroups-changing-routing-function.md).
+ Keep your own record of the statement. You read a definition back only with [SHOW CREATE SCALEOUT ROUTING FUNCTION](databaseclustergroups-sql-show-create-scaleout-routing-function.md).
+ For `COLUMN`, `PREFIX`, and `HASH` with `cityhash`, `xxhash`, or `md5`, the routing layer compares string routing keys under the collation of the scaleout table. For more information, see [Collations and string routing keys](databaseclustergroups-character-sets.md#databaseclustergroups-character-sets-routing-keys).

## Examples
<a name="databaseclustergroups-sql-create-scaleout-routing-function-examples"></a>

The following example creates a `MOD` function with twelve buckets of `tenant_id`, one collocation for each bucket.

```sql
CREATE SCALEOUT ROUTING FUNCTION tenant_rf(tenant_id BIGINT)
  AS PARTITION BY MOD(tenant_id, 12)
  IN TARGET COLLOCATION (
    cg_00 VALUES IN (0),  cg_01 VALUES IN (1),  cg_02 VALUES IN (2),  cg_03 VALUES IN (3),
    cg_04 VALUES IN (4),  cg_05 VALUES IN (5),  cg_06 VALUES IN (6),  cg_07 VALUES IN (7),
    cg_08 VALUES IN (8),  cg_09 VALUES IN (9),  cg_10 VALUES IN (10), cg_11 VALUES IN (11)
  );
```

The following example creates two `HASH` functions with two equal ranges: one on a string key, and one on a composite key.

```sql
CREATE SCALEOUT ROUTING FUNCTION device_rf(device_id VARCHAR(64))
  AS PARTITION BY HASH('cityhash', device_id)
  IN TARGET COLLOCATION (
    cg_h0 VALUES IN RANGE (0, 4611686018427387903),
    cg_h1 VALUES IN RANGE (4611686018427387904, MAXVALUE)
  );

CREATE SCALEOUT ROUTING FUNCTION region_id_rf(region INT, id BIGINT)
  AS PARTITION BY HASH('cityhash', region, id)
  IN TARGET COLLOCATION (
    cg_r0 VALUES IN RANGE (0, 4611686018427387903),
    cg_r1 VALUES IN RANGE (4611686018427387904, MAXVALUE)
  );
```

The following example creates a `PREFIX` function that places rows by the first segment of a tenant path, cut at a slash. This example assumes that data mappings already created the collocations `C1` and `C2`.

```sql
CREATE SCALEOUT ROUTING FUNCTION tenant_path_fn(tenant_path VARCHAR(128))
  AS PARTITION BY PREFIX(tenant_path, '/', 1)
  IN TARGET COLLOCATION (
    C1 VALUES IN ('/us', '/ca'),
    C2 VALUES IN ('/eu')
  );
```

With this function, `'/us/acme/42'` and `'/ca/beta/7'` go to `C1`, `'/eu/gamma/1'` goes to `C2`, and `'/jp/x'` is rejected.

The following example creates a `COLUMN` function that places rows by inclusive ranges of `order_id`. This example assumes that data mappings already created the collocations `C1`, `C2`, and `C3`.

```sql
CREATE SCALEOUT ROUTING FUNCTION orders_range_fn(order_id BIGINT)
  AS PARTITION BY COLUMN(order_id)
  IN TARGET COLLOCATION (
    C1 VALUES IN RANGE (1, 999999),
    C2 VALUES IN RANGE (1000000, 1999999),
    C3 VALUES IN RANGE (2000000, MAXVALUE)
  );
```

## Errors
<a name="databaseclustergroups-sql-create-scaleout-routing-function-errors"></a>

A refused statement creates nothing. For all errors from the routing layer, see [Error codes for database cluster groups for Aurora](databaseclustergroups-error-reference.md).


| Aurora MySQL | Meaning | 
| --- | --- | 
| [64005](databaseclustergroups-errors-scaleout.md#databaseclustergroups-data-mapping-and-scaleout-ddl-errors) TARGET COLLOCATION '<group>' not found: no data mapping declares such a router\_collocation\_group (names are case-sensitive) (42000) | No data mapping declares the collocation. The message lists every missing name. | 
| [64022](databaseclustergroups-errors-scaleout.md#databaseclustergroups-data-mapping-and-scaleout-ddl-errors) Routing function '<function\_name>' already exists (42000) | The name is in use. | 
| 1305 FUNCTION <name> does not exist. Use MOD, PREFIX, COLUMN or HASH. | The statement names a function other than MOD, HASH, PREFIX, or COLUMN. | 
| 1582 Incorrect parameter count in the call to routing function '<function>' | A missing divisor, algorithm, delimiter, or depth, or more than one parameter in COLUMN. | 
| [1064](databaseclustergroups-errors-routing.md#databaseclustergroups-routing-and-statement-errors) You have an error in your SQL syntax; hash algorithm '<name>' is not supported | The HASH algorithm isn't one of the six names, or it isn't in lowercase. | 
| 1235 HASH algorithm name must be a string literal, found '<value>' | The algorithm isn't a quoted string, or it isn't the first argument. | 
| 1491 The routing function MOD returns the wrong type for parameter '<param>', 1502 for a BLOB, TEXT, or JSON key, or [1235](databaseclustergroups-errors-scaleout.md#databaseclustergroups-data-mapping-and-scaleout-ddl-errors) Parameter data type is incompatible with the routing function type (42000) | The function doesn't accept the key type. | 
| 1235 Parameter '<param>' is declared but not used as a routing key | A parameter is missing from the method arguments. | 
| [1495](databaseclustergroups-errors-scaleout.md#databaseclustergroups-data-mapping-and-scaleout-ddl-errors) Multiple definition of same value <N> in TARGET COLLOCATION mappings | A value is in two collocations. | 
| [1517](databaseclustergroups-errors-scaleout.md#databaseclustergroups-data-mapping-and-scaleout-ddl-errors) Duplicate TARGET COLLOCATION name <collocation> | A collocation is listed twice. | 
| 1480 All TARGET COLLOCATION entries must use the same mapping type | The map mixes VALUES IN and VALUES IN RANGE. | 
| 1493 TARGET COLLOCATION '<a>' and '<b>' have overlapping VALUES IN RANGE bounds | Ranges overlap or share a bound. | 
| 1493 TARGET COLLOCATION '<group>' has an inverted VALUES IN RANGE; … | The low bound is above the high bound. | 
| 1654 for COLUMN or PREFIX, 1697 for MOD or HASH: TARGET COLLOCATION '<group>' has an invalid VALUES IN RANGE bound; each bound must have the type this routing function returns | A bound of the wrong type, or a HASH bound above the interval. | 
| 1235 MOD divisor must be an integer literal, found '<n>' | A negative or non-literal divisor. | 
| [1064](databaseclustergroups-errors-routing.md#databaseclustergroups-routing-and-statement-errors) | Syntax error: a form outside the grammar, such as IF NOT EXISTS, an empty parameter list, or MAXVALUE in a VALUES IN list. | 
| 1235 (42000) This operation is not supported in query routing mode. Use the cluster endpoint directly or pin the session to a member cluster. | CREATE OR REPLACE SCALEOUT ROUTING FUNCTION. | 
| 1179 CREATE SCALEOUT ROUTING FUNCTION is not allowed inside a transaction … | The statement ran inside a transaction. | 
| [1227](databaseclustergroups-errors-connection.md) Access denied; you need the '<PRIVILEGE>' privilege for this operation | The router user lacks the privilege for database cluster groups for Aurora. | 

## Related statements
<a name="databaseclustergroups-sql-create-scaleout-routing-function-related"></a>

For more information, see the following:
+ [DROP SCALEOUT ROUTING FUNCTION](databaseclustergroups-sql-drop-scaleout-routing-function.md)
+ [SHOW CREATE SCALEOUT ROUTING FUNCTION](databaseclustergroups-sql-show-create-scaleout-routing-function.md)
+ [SHOW SCALEOUT ROUTING FUNCTIONS](databaseclustergroups-sql-show-scaleout-routing-functions.md)
+ [CREATE SCALEOUT TABLE](databaseclustergroups-sql-create-scaleout-table.md)
+ [INSERT INTO dbclustergroup\_sys.data\_mappings](databaseclustergroups-sql-insert-data-mappings.md)