NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RASTERIZEDDB SERVER / PARTITIONING

Partitioning

A hash-partitioned table is one logical table whose rows are spread over many partitions, each with its own files, locks, indexes and vacuum state. A row's partition is chosen by a hash of its partition key, usually a tenant or customer id. A statement that fixes the key touches only the partition that can hold its rows; any other statement reads every partition under one snapshot.

Use it for multi-tenant tables, so that one tenant's heavy DELETE or UPDATE does not block the others, and so a large table can be split across disks. Applications see an ordinary table: the partitions are never named in SQL.

Create a partitioned table

sql
CREATE TABLE assets (
    tenant_id      BIGINT NOT NULL,
    asset_group_id BIGINT NOT NULL,
    asset_id       UUID   NOT NULL,
    body           TEXT,
    PRIMARY KEY (tenant_id, asset_group_id, asset_id)
) PARTITION BY HASH (tenant_id, asset_group_id);

The full form is:

sql
CREATE TABLE [IF NOT EXISTS] name (columns and constraints)
    PARTITION BY HASH (c1 [, c2 [, c3]])
    [PARTITIONS n];
PartRule
Key columnsOne to three column names, outermost first. No expressions, operator classes or COLLATE.
PARTITIONS nHow many partitions the table starts with. Default 64. A database holds at most 1,048,576 declared partitions across all its tables.
Key column typesInteger types (SMALLINT, INT, BIGINT and the other integer widths up to 128-bit signed and 64-bit unsigned), UUID, TEXT and VARCHAR.
Key column nullabilityEvery key column must be NOT NULL, and cannot be a generated column.
Unique keysEvery PRIMARY KEY and UNIQUE constraint or index must contain every partition key column.

Refused key types, each with its reason in the error: floating point, NUMERIC, JSON/JSONB, BOOLEAN, CHAR(n)/CHARACTER(n), CITEXT, NAME, BYTEA, arrays, bit strings, intervals, TIMETZ, geometric and range types, and (not yet supported) DATE, TIME, TIMESTAMP, INET and MAC addresses. INT and BIGINT values hash alike, so INT 42 and BIGINT 42 land in the same place.

A table with no rows in some partitions costs nothing for those: a partition gets its files when its first row is written.

Choosing the key

Put the column every query fixes first, typically the tenant. A partition holds the whole of each tenant it owns: all rows with one value of the first key column are in one partition, until you split that tenant (below).

A second key column costs nothing until it is used: it lets you later split one big tenant across several partitions with SPLIT KEY, by that second column. A one-column key can isolate a tenant into its own partition but never split it. If you might need to split, declare (tenant_id, <natural sub-key>) from the start.

The unique-key rule follows from the key: with PARTITION BY HASH (tenant_id, asset_group_id), a PRIMARY KEY (tenant_id, asset_id) is refused because it lacks asset_group_id. Either add the column to the key, or partition by (tenant_id) alone.

Which statements touch one partition

The WHERE fixes by equalityPartitions read
Every key column (tenant_id = 42 AND asset_group_id = 7)one
A leading prefix of the key (tenant_id = 42)normally one: that tenant's partition, or its pieces if it was split
Only a later key column (asset_group_id = 7)all
A range, !=, a function or a cast on a key columnall, for that column
Contradictory values (tenant_id = 1 AND tenant_id = 2)none
No WHEREall

IN lists route too: tenant_id IN (1, 2) AND asset_group_id IN (7, 8, 9) reads at most six partitions. Past 256 combinations the router drops the last key column and routes by the leading ones instead, which only ever reads more partitions, never fewer. A row-value IN such as (tenant_id, asset_group_id) IN ((1, 7), (2, 9)) reads all partitions.

In a join, a constant on one side is carried to the other across an equality: in SELECT … FROM assets a JOIN tenants t ON a.tenant_id = t.id WHERE t.id = 42, assets is read in one partition. This happens across INNER joins and from the preserved side of a LEFT join, for integer and quoted-string literals.

Every row is still checked against the whole WHERE, so routing never changes an answer, only how much is read.

See what a statement touched

sql
SET partition_trace = on;
SELECT count(*) FROM assets WHERE tenant_id = 42;
text
NOTICE:  partition_trace: "assets": read 1 of 64 partitions (routed by (tenant_id, asset_group_id))

Each read or write plan on a partitioned table raises one NOTICE, saying how many partitions it reached and why: routed by …, the WHERE clause does not pin …, no WHERE clause, no row can match the WHERE clause, or routed by the bound value of … for a prepared statement. An INSERT reports once per table how many partitions its rows went to. partition_trace is a session setting; RESET partition_trace turns it off.

Using a partitioned table

A partitioned table answers like the same table unpartitioned. That includes:

  • INSERT in every form, COPY, INSERT … SELECT, ON CONFLICT DO NOTHING and DO UPDATE, and RETURNING.
  • SELECT with joins, aggregates, GROUP BY, DISTINCT, window functions, UNION, CTEs and subqueries; SELECT … FOR UPDATE/FOR SHARE with SKIP LOCKED and NOWAIT.
  • UPDATE and DELETE, routed or across all partitions, all or nothing across partitions; UPDATE … FROM and DELETE … USING.
  • Prepared statements, transactions, LOCK TABLE, VACUUM and VACUUM FULL, DROP TABLE.
  • CREATE [UNIQUE] INDEX (B-tree, hash, GIN, JSON path) and DROP INDEX.
  • ALTER TABLE: RENAME TO, RENAME COLUMN (key columns too), ADD COLUMN (on a populated table too, which rewrites every row), DROP COLUMN, SET/DROP DEFAULT, SET/DROP NOT NULL, ADD/DROP CONSTRAINT (CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY).
  • Foreign keys in both directions: from a partitioned table to a plain or partitioned one, and onto a partitioned table, with every ON DELETE/ON UPDATE action. A foreign key onto a partitioned table must reference a unique key, which always contains every partition key column.

Changing a key value moves the row

An UPDATE that changes a partition key column moves each affected row to its new partition, in the same statement and transaction:

sql
UPDATE assets SET tenant_id = 43 WHERE tenant_id = 42 AND asset_group_id = 7;

Uniqueness is checked once all moved rows have landed, so a shift such as SET asset_group_id = asset_group_id + 1 over consecutive values succeeds. A concurrent writer that touches a row another transaction moved gets a serialization failure (40001) and should retry.

Two forms still refuse a move, with 0A000: an ON CONFLICT … DO UPDATE whose update would move the row (as in PostgreSQL), and an UPDATE … FROM that changes the target's key.

Convert an existing table

An existing plain table can be converted in place:

sql
ALTER TABLE orders PARTITION BY HASH (tenant_id) PARTITIONS 64;

PostgreSQL-style tooling can use the equivalent spelling:

sql
CREATE INDEX orders_by_tenant ON orders USING partition (tenant_id) WITH (partitions = 64);

PARTITIONS defaults to 64. The index name is accepted and then names nothing: no index is listed and none can be dropped. The table must meet the same rules as CREATE … PARTITION BY (key types, NOT NULL, unique keys).

The conversion rewrites every row into new files while holding an exclusive lock: all reads and writes of the table wait until it finishes. A crash at any point leaves either the old table or the new one, whole. It cannot run inside a transaction block (25001). With replication on, it is replicated like other DDL.

A table placed on another storage location, a key/value store or in memory cannot be converted; move it back to the database directory first.

Inspect partitions

sql
SHOW PARTITIONS assets;
ColumnMeaning
pidPartition id. Ids are never reused; a reshape creates new ones.
lo, hiThe partition's range of the 64-bit hash space, as hexadecimal text.
locationThe directory or store holding its files.
statematerialized (it has files) or unmaterialized (no row written yet).
row_slotsRow-pointer records, including dead versions not yet vacuumed.
total_bytesBytes on disk.

Rows are listed in hash-range order.

Reshape partitions

These statements change how a table's rows are divided. Each copies the rows of the affected partitions into new partitions, keeping every row version exactly as it was, then retires the old ones.

sql
-- Split the partition holding tenant 42 at its midpoint.
ALTER TABLE assets SPLIT PARTITION FOR (tenant_id = 42);

-- Merge two adjacent partitions into one.
ALTER TABLE assets MERGE PARTITIONS FOR (tenant_id = 42), FOR (tenant_id = 77);

-- Give tenant 42 a partition of its own, optionally on another disk.
ALTER TABLE assets ISOLATE KEY (tenant_id = 42);
ALTER TABLE assets ISOLATE KEY (tenant_id = 42) TO '/mnt/nvme2/rasterizeddb';

-- Spread tenant 42 over 8 partitions, by asset_group_id.
ALTER TABLE assets SPLIT KEY (tenant_id = 42) INTO 8;

FOR (…) and KEY (…) take column = value pairs, separated by commas or AND, fixing a leading prefix of the key. They are routed exactly as a WHERE clause is.

StatementRules
SPLIT PARTITION FOR (…)Refused for a partition that holds a single hash point.
MERGE PARTITIONS FOR (…), FOR (…)The two partitions must be adjacent in hash order (see SHOW PARTITIONS).
ISOLATE KEY (…) [TO '<location>']Refused when the key already has a partition to itself and no TO is given. With TO, the isolated partition goes to that location.
SPLIT KEY (…) INTO nNeeds a key of two or three columns, and a prefix that leaves at least one column unfixed. n is a power of two from 2 to 1024.

ISOLATE KEY and SPLIT KEY are refused when the key's rows already span more than one partition; merge first. One reshape makes at most 1,026 new partitions.

While a reshape runs, every statement on that table waits: it holds an exclusive lock on the table for the whole copy. Plan reshapes for quiet periods. Other tables are unaffected.

A crash during a reshape rolls it back (or, after its commit point, forward) at the next start, and leftover files are deleted automatically.

Reshapes cannot run inside a transaction block (25001), and they are not replicated: each node keeps its own partition layout, which does not affect which rows a query returns.

Partitions across disks

When the database has a storage pool with several primary locations, each partition is placed when it gets its first row, by the pool's policy, counting every partitioned table's partitions together:

Pool policyA new partition goes to
primarythe first enabled primary location
round-robinthe location holding the fewest tables plus partitions
free-spacethe location furthest below its share, shares being free space × weight

Locations below the pool's minimum free space are skipped. The table's own small metadata files always stay in the database directory. Where a partition was placed is recorded and never recomputed.

Move one partition

sql
STORAGE MOVE PARTITION assets FOR (tenant_id = 42) TO '/mnt/nvme2/rasterizeddb';

The target must be a primary location of this database, or a defined key/value store ('kv:<store>'). The move is a reshape: it holds the table's exclusive lock while it copies.

STORAGE MOVE TABLE and STORAGE PLACE TABLE are refused for a partitioned table; move its partitions instead.

Balance partitions across disks

sql
STORAGE REBALANCE PARTITIONS DRY RUN;
STORAGE REBALANCE PARTITIONS;

The plan first moves every partition off a location that is disabled or no longer a primary, to the roomiest location that takes tables. Under the round-robin policy it then moves partitions, smallest first, from the location holding the most to the one holding the fewest, until no two differ by more than one. No move takes a location below the minimum free space. DRY RUN prints the plan without moving anything.

Moves run one at a time, each holding only its own table's lock. The first failure stops the run, keeping the moves already made; running the statement again plans from there. Partitions on a key/value store are left where they are.

To retire a disk: STORAGE DISABLE LOCATION '<path>', then STORAGE REBALANCE PARTITIONS (and STORAGE REBALANCE for plain tables), then STORAGE DROP LOCATION '<path>'. A location that still holds a partition cannot be dropped or made a backup location.

Partitions on a key/value store

Place the table on a store before creating it, and its partitions' data goes there:

sql
STORAGE PLACE TABLE access_logs AT 'kv:logs';
CREATE TABLE access_logs (
    domain TEXT   NOT NULL,
    id     BIGINT NOT NULL,
    path   TEXT,
    PRIMARY KEY (domain, id)
) PARTITION BY HASH (domain);

See Key/value storage for defining the store, its costs, and what backups cover.

Settings

Partitions are opened when first used, not at start-up, and closed again when idle, so a database can hold far more partitions than it has file descriptors for. These settings control that:

SettingDefaultChange it withWhat it does
partition.open_budget0SET CONFIG partition.open_budget = 2000Partitions open at once in this process, across tables. Past it, opening one closes idle ones first. 0 derives it from the open-file limit.
partition.idle_close_secs300SET CONFIG partition.idle_close_secs = 600Seconds a partition goes untouched before it is closed. 0 turns idle closing off.
partition.max_open4096--partition-max-open N or RDB_PARTITION_MAX_OPEN (read at start)The most partitions a derived budget allows. At start the server raises its soft open-file limit to fit, ten descriptors per partition over a reserve of 2,048, within the hard limit.
partition.resident_budget0SET CONFIG partition.resident_budget = 4294967296Estimated bytes of memory open partitions may hold, across tables; past it, idle partitions are closed first. 0 limits them by count alone.

SET CONFIG needs a superuser. The partition.* settings above take effect at once and are saved, so they hold after a restart; a start-up flag given for the same setting wins over the saved value. SET CONFIG partition.max_open = N is saved for the next start. SHOW CONFIG lists the current values. See Configuration.

Automatic compaction (VACUUM FULL of a partition whose row slots are mostly dead) runs per partition and is tuned with the auto_compact.* settings; see Maintenance.

Limits

  • Only PARTITION BY HASH. PARTITION BY RANGE and LIST, DEFAULT partitions, PARTITION OF … FOR VALUES WITH (MODULUS …, REMAINDER …), ATTACH PARTITION and DETACH PARTITION are refused. The hash is not PostgreSQL's: a PostgreSQL hash partition with the same modulus would hold different rows.
  • Individual partitions cannot be named or queried directly.
  • At most three key columns. Key columns cannot be dropped, retyped or made nullable. RENAME COLUMN on a key column is fine.
  • UNIQUE and PRIMARY KEY must contain every key column, so uniqueness is per partition key, not global on a subset.
  • Partitioned tables cannot be temporary or unlogged, cannot be created in an in-memory database or in a storage pool that has a backup (mirror) location, and cannot have JSON columns stored as shadow tables (--json-shadow-tables); native JSONB columns are fine.
  • COLOCATE WITH is not supported.
  • Queries that do not fix the key read every partition, at most eight at a time. ORDER BY across partitions is correct but costs more than on a plain table.
  • Reshapes and conversions are offline for the table they change: its readers and writers wait for the copy.
✓ page rendered in 304 µs axum + tera + htmx · no other javascript