SQL course · Module 11: Production SQL · Lesson 37 of 40
Quick answer: PostgreSQL table partitioning splits one large table into smaller tables called partitions. You create the parent with PARTITION BY RANGE, LIST or HASH, then add partitions with CREATE TABLE ... PARTITION OF. Each row goes to the partition that matches its partition key, and a query that filters on the key skips the other partitions (partition pruning). Old data can be removed by detaching or dropping a whole partition. Partition only very large tables.
In this lesson you will learn:
- RANGE, LIST and HASH partitioning
- the DEFAULT partition
- how to see partition pruning in
EXPLAINoutput - how indexes and primary keys work on partitioned tables
DETACHandATTACH PARTITION, and when not to partition
Before you start: Lesson 36, Preventing SQL Injection: Parameterized Queries, Roles and GRANT. You also need the practice tables from Lesson 31 and plan reading from Lesson 32.
We ran every example on PostgreSQL 16.15 with the shop database from Lesson 3 and checked the current PostgreSQL 18 manual; everything works on newer versions too. The plans hide costs and timings, so on PostgreSQL 16 your output should match ours. PostgreSQL 18 also prints Buffers lines and decimal row counts in EXPLAIN ANALYZE (release notes).
Table of Contents
Setup: the practice tables
We use the practice tables from Lesson 31: big_customers (20,000 rows) and big_orders (200,000 rows). Run the script again so your data matches ours; setseed makes the “random” data repeatable when the whole script runs in one session (we checked this on PostgreSQL 16).
DROP TABLE IF EXISTS big_orders, big_customers;
CREATE TABLE big_customers (
id integer PRIMARY KEY,
email text NOT NULL,
country text NOT NULL,
signup_date date NOT NULL
);
CREATE TABLE big_orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES big_customers (id),
order_date date NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL
);
SELECT setseed(0.31); -- fixed seed: everyone gets the same "random" data
INSERT INTO big_customers
SELECT i,
CASE WHEN i % 3 = 0 THEN 'Customer' || i || '@Example.com'
ELSE 'customer' || i || '@example.com' END,
(ARRAY['Pakistan','India','UK','USA','Canada','Germany','France','Italy'])[1 + floor(random() * 8)::int],
DATE '2023-01-01' + floor(random() * 1000)::int
FROM generate_series(1, 20000) AS i;
INSERT INTO big_orders
SELECT i,
1 + floor(random() * 20000)::int,
DATE '2024-01-01' + floor(random() * 1035)::int,
CASE WHEN r < 0.80 THEN 'delivered'
WHEN r < 0.90 THEN 'shipped'
WHEN r < 0.95 THEN 'cancelled'
ELSE 'pending' END,
round((5 + random() * 495)::numeric, 2)
FROM (SELECT i, random() AS r FROM generate_series(1, 200000) AS i) AS s;
VACUUM ANALYZE big_customers, big_orders;
DROP TABLE
CREATE TABLE
CREATE TABLE
setseed
---------
(1 row)
INSERT 0 20000
INSERT 0 200000
VACUUM
The first time, two NOTICE lines also say the tables do not exist yet. The orders run from 2024-01-01 to 2026-10-31.
What is table partitioning?
The PostgreSQL manual defines partitioning as “splitting what is logically one large table into smaller physical pieces” (PostgreSQL docs: Table Partitioning). You query one table, the parent, but it is “a ‘virtual’ table having no storage of its own”; the rows live in the partitions, “otherwise-ordinary tables”.
The column that decides where a row goes is the partition key. There are three methods:
| Method | How rows are split | Typical key |
|---|---|---|
| RANGE | ranges of values that do not overlap | dates, timestamps, ids |
| LIST | an explicit list of values per partition | country, region, status |
| HASH | a hash of the key, with a modulus and a remainder | customer id, when there is no natural range |
RANGE partitioning by date
We create a partitioned copy of big_orders with one partition per year:
CREATE TABLE orders_part (
id integer NOT NULL,
customer_id integer NOT NULL,
order_date date NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL
) PARTITION BY RANGE (order_date);
CREATE TABLE orders_2024 PARTITION OF orders_part
FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');
CREATE TABLE orders_2025 PARTITION OF orders_part
FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
CREATE TABLE orders_2026 PARTITION OF orders_part
FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');
INSERT INTO orders_part SELECT * FROM big_orders;
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 200000
FROM is included and TO is not (PostgreSQL docs: CREATE TABLE), so 2025-01-01 belongs to orders_2025. We inserted into the parent only. The hidden column tableoid, shown as tableoid::regclass, names the table that stores each row:
SELECT tableoid::regclass AS partition, COUNT(*) AS orders,
MIN(order_date) AS first_day, MAX(order_date) AS last_day
FROM orders_part
GROUP BY 1
ORDER BY 1;
partition | orders | first_day | last_day
-------------+--------+------------+------------
orders_2024 | 70500 | 2024-01-01 | 2024-12-31
orders_2025 | 70440 | 2025-01-01 | 2025-12-31
orders_2026 | 59060 | 2026-01-01 | 2026-10-31
(3 rows)
The parent itself stores nothing:
SELECT pg_size_pretty(pg_relation_size('orders_part')) AS parent_size,
pg_size_pretty(pg_relation_size('orders_2024')) AS orders_2024_size;
parent_size | orders_2024_size
-------------+------------------
0 bytes | 4152 kB
(1 row)
The DEFAULT partition
No partition accepts an order dated 2027:
INSERT INTO orders_part VALUES (200001, 4242, '2027-01-05', 'pending', 50.00);
ERROR: no partition of relation "orders_part" found for row
DETAIL: Partition key of the failing row contains (order_date) = (2027-01-05).
A DEFAULT partition takes every row that fits no other partition:
CREATE TABLE orders_default PARTITION OF orders_part DEFAULT;
INSERT INTO orders_part VALUES (200001, 4242, '2027-01-05', 'pending', 50.00);
SELECT tableoid::regclass AS partition, id, order_date
FROM orders_part
WHERE id = 200001;
CREATE TABLE
INSERT 0 1
partition | id | order_date
----------------+--------+------------
orders_default | 200001 | 2027-01-05
(1 row)
But now try to add a 2027 partition:
CREATE TABLE orders_2027 PARTITION OF orders_part
FOR VALUES FROM ('2027-01-01') TO ('2028-01-01');
ERROR: updated partition constraint for default partition "orders_default" would be violated by some row
The 2027 row already sits in the default partition. Even without such a row, each new partition means the default partition “must be scanned”, which “may be slow” if it is big (PostgreSQL docs: CREATE TABLE). Keep it small or empty. We fix 2027 later.
Partition pruning with EXPLAIN
Partition pruning means the planner proves that a partition “could not contain any rows meeting the query’s WHERE clause” and leaves it out (PostgreSQL docs: Partition Pruning). Autovacuum “does not process partitioned tables”, so run ANALYZE on the parent yourself now and then (PostgreSQL docs: ANALYZE); PostgreSQL 18 added ANALYZE ONLY to skip the partitions (release notes).
ANALYZE orders_part;
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM orders_part
WHERE order_date >= '2026-03-01' AND order_date < '2026-04-01';
ANALYZE
QUERY PLAN
--------------------------------------------------------------------------------------------
Aggregate
-> Seq Scan on orders_2026 orders_part
Filter: ((order_date >= '2026-03-01'::date) AND (order_date < '2026-04-01'::date))
(3 rows)
Only orders_2026 is in the plan. EXPLAIN ANALYZE (timings off) shows the rows read:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT COUNT(*) FROM orders_part
WHERE order_date >= '2026-03-01' AND order_date < '2026-04-01';
QUERY PLAN
--------------------------------------------------------------------------------------------
Aggregate (actual rows=1 loops=1)
-> Seq Scan on orders_2026 orders_part (actual rows=5956 loops=1)
Filter: ((order_date >= '2026-03-01'::date) AND (order_date < '2026-04-01'::date))
Rows Removed by Filter: 53104
(4 rows)
PostgreSQL read the 59,060 rows of orders_2026 and kept 5,956; the 140,941 rows in the other partitions were never touched.

Compare with pruning turned off:
SET enable_partition_pruning = off;
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM orders_part
WHERE order_date >= '2026-03-01' AND order_date < '2026-04-01';
RESET enable_partition_pruning;
SET
QUERY PLAN
--------------------------------------------------------------------------------------------------------------
Finalize Aggregate
-> Gather
Workers Planned: 2
-> Partial Aggregate
-> Parallel Append
-> Parallel Seq Scan on orders_2024 orders_part_1
Filter: ((order_date >= '2026-03-01'::date) AND (order_date < '2026-04-01'::date))
-> Parallel Seq Scan on orders_2025 orders_part_2
Filter: ((order_date >= '2026-03-01'::date) AND (order_date < '2026-04-01'::date))
-> Parallel Seq Scan on orders_2026 orders_part_3
Filter: ((order_date >= '2026-03-01'::date) AND (order_date < '2026-04-01'::date))
-> Parallel Seq Scan on orders_default orders_part_4
Filter: ((order_date >= '2026-03-01'::date) AND (order_date < '2026-04-01'::date))
(13 rows)
RESET
Now all four partitions are read. Pruning needs a WHERE condition on the partition key, so a filter on customer_id reads every partition:
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM orders_part WHERE customer_id = 4242;
QUERY PLAN
------------------------------------------------------
Aggregate
-> Append
-> Seq Scan on orders_2024 orders_part_1
Filter: (customer_id = 4242)
-> Seq Scan on orders_2025 orders_part_2
Filter: (customer_id = 4242)
-> Seq Scan on orders_2026 orders_part_3
Filter: (customer_id = 4242)
-> Seq Scan on orders_default orders_part_4
Filter: (customer_id = 4242)
(10 rows)
So does a function around the key, like the non-sargable filters in Lesson 33:
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM orders_part WHERE extract(year FROM order_date) = 2026;
QUERY PLAN
-------------------------------------------------------------------------------------
Finalize Aggregate
-> Gather
Workers Planned: 2
-> Partial Aggregate
-> Parallel Append
-> Parallel Seq Scan on orders_2024 orders_part_1
Filter: (EXTRACT(year FROM order_date) = '2026'::numeric)
-> Parallel Seq Scan on orders_2025 orders_part_2
Filter: (EXTRACT(year FROM order_date) = '2026'::numeric)
-> Parallel Seq Scan on orders_2026 orders_part_3
Filter: (EXTRACT(year FROM order_date) = '2026'::numeric)
-> Parallel Seq Scan on orders_default orders_part_4
Filter: (EXTRACT(year FROM order_date) = '2026'::numeric)
(13 rows)
Write order_date >= '2026-01-01' AND order_date < '2027-01-01' instead.
Pruning at execution time
Pruning can also happen “during its execution”, when the value is unknown at planning time, as in a prepared statement (Lesson 36) with a generic plan, one that does “not rely on the parameter values” (PostgreSQL docs: Query Planning):
PREPARE orders_since (date) AS
SELECT COUNT(*) FROM orders_part WHERE order_date >= $1;
SET plan_cache_mode = force_generic_plan;
EXPLAIN (COSTS OFF) EXECUTE orders_since('2026-06-01');
RESET plan_cache_mode;
DEALLOCATE orders_since;
PREPARE
SET
QUERY PLAN
---------------------------------------------------------------------------
Finalize Aggregate
-> Gather
Workers Planned: 2
-> Partial Aggregate
-> Parallel Append
Subplans Removed: 2
-> Parallel Seq Scan on orders_2026 orders_part_1
Filter: (order_date >= $1)
-> Parallel Seq Scan on orders_default orders_part_2
Filter: (order_date >= $1)
(10 rows)
RESET
DEALLOCATE
Subplans Removed: 2 means 2024 and 2025 were skipped when the query started. The default partition stays, because it could hold later dates.
Indexes and primary keys on partitioned tables
An index on the parent “automatically creates a matching index on each partition”, including later ones (PostgreSQL docs: Table Partitioning):
CREATE INDEX orders_part_customer_idx ON orders_part (customer_id);
SELECT tablename, indexname
FROM pg_indexes
WHERE tablename IN ('orders_part', 'orders_2024', 'orders_2025', 'orders_2026', 'orders_default')
ORDER BY tablename, indexname;
CREATE INDEX
tablename | indexname
----------------+--------------------------------
orders_2024 | orders_2024_customer_id_idx
orders_2025 | orders_2025_customer_id_idx
orders_2026 | orders_2026_customer_id_idx
orders_default | orders_default_customer_id_idx
orders_part | orders_part_customer_idx
(5 rows)
Now a primary key:
ALTER TABLE orders_part ADD PRIMARY KEY (id);
ERROR: unique constraint on partitioned table must include all partitioning columns
DETAIL: PRIMARY KEY constraint on table "orders_part" lacks column "order_date" which is part of the partition key.
Each partition’s index checks uniqueness only inside its partition, so “the constraint’s columns must include all of the partition key columns”. Add the key column:
ALTER TABLE orders_part ADD PRIMARY KEY (id, order_date);
ALTER TABLE
Now id alone is not guaranteed unique across years; an identity column (Lesson 16) or your app must ensure that.
LIST partitioning
LIST partitioning names the values of each partition. We split customers by region:
CREATE TABLE customers_by_region (
id integer NOT NULL,
email text NOT NULL,
country text NOT NULL,
signup_date date NOT NULL
) PARTITION BY LIST (country);
CREATE TABLE customers_asia PARTITION OF customers_by_region
FOR VALUES IN ('Pakistan', 'India');
CREATE TABLE customers_europe PARTITION OF customers_by_region
FOR VALUES IN ('UK', 'Germany', 'France', 'Italy');
CREATE TABLE customers_america PARTITION OF customers_by_region
FOR VALUES IN ('USA', 'Canada');
INSERT INTO customers_by_region SELECT * FROM big_customers;
SELECT tableoid::regclass AS partition, COUNT(*) AS customers
FROM customers_by_region
GROUP BY 1
ORDER BY 1;
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM customers_by_region WHERE country = 'Italy';
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 20000
partition | customers
-------------------+-----------
customers_asia | 5045
customers_europe | 9921
customers_america | 5034
(3 rows)
QUERY PLAN
--------------------------------------------------------
Aggregate
-> Seq Scan on customers_europe customers_by_region
Filter: (country = 'Italy'::text)
(3 rows)
Sorting by tableoid sorts by the tables’ internal ids, which here follow creation order. Italy reads only the Europe partition. A country in no list fails:
INSERT INTO customers_by_region VALUES (20001, 'new@example.com', 'Brazil', '2026-11-01');
ERROR: no partition of relation "customers_by_region" found for row
DETAIL: Partition key of the failing row contains (country) = (Brazil).
HASH partitioning
HASH partitioning spreads rows evenly when the key has no natural ranges. Usually the modulus equals the number of partitions:
CREATE TABLE orders_by_customer (
id integer NOT NULL,
customer_id integer NOT NULL,
order_date date NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL
) PARTITION BY HASH (customer_id);
CREATE TABLE orders_h0 PARTITION OF orders_by_customer FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE orders_h1 PARTITION OF orders_by_customer FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE orders_h2 PARTITION OF orders_by_customer FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE orders_h3 PARTITION OF orders_by_customer FOR VALUES WITH (MODULUS 4, REMAINDER 3);
INSERT INTO orders_by_customer SELECT * FROM big_orders;
SELECT tableoid::regclass AS partition, COUNT(*) AS orders,
COUNT(DISTINCT customer_id) AS customers
FROM orders_by_customer
GROUP BY 1
ORDER BY 1;
EXPLAIN (COSTS OFF)
SELECT * FROM orders_by_customer WHERE customer_id = 4242;
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 200000
partition | orders | customers
-----------+--------+-----------
orders_h0 | 49803 | 4971
orders_h1 | 50606 | 5048
orders_h2 | 50421 | 5051
orders_h3 | 49170 | 4929
(4 rows)
QUERY PLAN
------------------------------------------
Seq Scan on orders_h0 orders_by_customer
Filter: (customer_id = 4242)
(2 rows)
Each partition got about a quarter of the rows, and one customer’s orders share a partition, so = reads one partition. A range such as customer_id < 100 reads all four, because the ids are mixed.
Attach and detach partitions to archive old data
The manual says dropping or detaching a partition “is far faster than a bulk operation” and avoids “the VACUUM overhead caused by a bulk DELETE” (PostgreSQL docs: Table Partitioning). Let’s archive 2024. With CONCURRENTLY, the parent gets only a SHARE UPDATE EXCLUSIVE lock, so other sessions can keep reading and writing it:
ALTER TABLE orders_part DETACH PARTITION orders_2024 CONCURRENTLY;
ERROR: cannot detach partitions concurrently when a default partition exists
CONCURRENTLY “cannot be run in a transaction block and is not allowed if the partitioned table contains a default partition” (PostgreSQL docs: ALTER TABLE). So we use a plain DETACH, which takes ACCESS EXCLUSIVE, the default ALTER TABLE lock; other queries on the table wait:
ALTER TABLE orders_part DETACH PARTITION orders_2024;
ALTER TABLE orders_2024 RENAME TO orders_2024_archive;
SELECT COUNT(*) AS orders_before_2025 FROM orders_part WHERE order_date < '2025-01-01';
SELECT COUNT(*) AS archived_orders FROM orders_2024_archive;
ALTER TABLE
ALTER TABLE
orders_before_2025
--------------------
0
(1 row)
archived_orders
-----------------
70500
(1 row)
Nothing was deleted or copied: the partition became a standalone table that you can back up, move or drop.
For 2027, build a normal table, then attach it. Attaching locks the parent only with SHARE UPDATE EXCLUSIVE. It scans the table to check its rows; a matching CHECK constraint lets PostgreSQL skip that scan:
CREATE TABLE orders_2027 (LIKE orders_part INCLUDING ALL);
ALTER TABLE orders_2027 ADD CONSTRAINT orders_2027_check
CHECK (order_date >= '2027-01-01' AND order_date < '2028-01-01');
ALTER TABLE orders_part ATTACH PARTITION orders_2027
FOR VALUES FROM ('2027-01-01') TO ('2028-01-01');
CREATE TABLE
ALTER TABLE
ERROR: updated partition constraint for default partition "orders_default" would be violated by some row
Move the 2027 row with a data-modifying CTE (Lesson 21) using RETURNING (Lesson 17), attach, then drop the extra CHECK, as the manual recommends:
WITH moved AS (
DELETE FROM orders_default
WHERE order_date >= '2027-01-01' AND order_date < '2028-01-01'
RETURNING *
)
INSERT INTO orders_2027 SELECT * FROM moved;
ALTER TABLE orders_part ATTACH PARTITION orders_2027
FOR VALUES FROM ('2027-01-01') TO ('2028-01-01');
ALTER TABLE orders_2027 DROP CONSTRAINT orders_2027_check;
\d+ orders_part
INSERT 0 1
ALTER TABLE
ALTER TABLE
Partitioned table "public.orders_part"
Column | Type | Collation | Nullable | Default | Storage | Compression | Stats target | Description
-------------+---------------+-----------+----------+---------+----------+-------------+--------------+-------------
id | integer | | not null | | plain | | |
customer_id | integer | | not null | | plain | | |
order_date | date | | not null | | plain | | |
status | text | | not null | | extended | | |
total | numeric(10,2) | | not null | | main | | |
Partition key: RANGE (order_date)
Indexes:
"orders_part_pkey" PRIMARY KEY, btree (id, order_date)
"orders_part_customer_idx" btree (customer_id)
Partitions: orders_2025 FOR VALUES FROM ('2025-01-01') TO ('2026-01-01'),
orders_2026 FOR VALUES FROM ('2026-01-01') TO ('2027-01-01'),
orders_2027 FOR VALUES FROM ('2027-01-01') TO ('2028-01-01'),
orders_default DEFAULT
2024 is gone and 2027 is in. In real projects, create next year’s partition before the year starts.
When not to partition
The manual says the benefits are “normally worthwhile only when a table would otherwise be very large”; its rule of thumb is a table bigger than the server’s memory. Our practice table:
SELECT pg_size_pretty(pg_table_size('big_orders')) AS table_size,
pg_size_pretty(pg_total_relation_size('big_orders')) AS with_indexes;
table_size | with_indexes
------------+--------------
12 MB | 16 MB
(1 row)
At 12 MB it is far too small to partition in real life; we did it only to learn. Do not partition when:
- the table is not huge; an index (Lesson 31) is simpler
- most queries do not filter on the partition key, so they read every partition
- you need a unique key without the partition column
- you would need very many partitions; the manual warns: “Never just assume that more partitions are better than fewer partitions, nor vice-versa.”
Try it yourself
Keep the tables from this lesson for the exercises.
Exercise 1: Orders around New Year
Which partitions are read for orders from 2025-12-15 up to (not including) 2026-01-15? Check with EXPLAIN and count the orders per partition.
Exercise 2: LIST partitions by status
Create orders_by_status, a copy of big_orders LIST-partitioned by status into orders_open (pending, shipped) and orders_closed (delivered, cancelled). Count rows per partition and status, and check that a query for pending orders reads one partition.
Exercise 3: Detach concurrently
Check that the default partition is empty, drop it, then detach orders_2025 with CONCURRENTLY. Show that the 2025 orders left orders_part but are still in orders_2025.
Solutions
Solution 1
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM orders_part
WHERE order_date >= '2025-12-15' AND order_date < '2026-01-15';
SELECT tableoid::regclass AS partition, COUNT(*) AS orders
FROM orders_part
WHERE order_date >= '2025-12-15' AND order_date < '2026-01-15'
GROUP BY 1
ORDER BY 1;
QUERY PLAN
--------------------------------------------------------------------------------------------------
Aggregate
-> Append
-> Seq Scan on orders_2025 orders_part_1
Filter: ((order_date >= '2025-12-15'::date) AND (order_date < '2026-01-15'::date))
-> Seq Scan on orders_2026 orders_part_2
Filter: ((order_date >= '2025-12-15'::date) AND (order_date < '2026-01-15'::date))
(6 rows)
partition | orders
-------------+--------
orders_2025 | 3253
orders_2026 | 2735
(2 rows)
The range crosses New Year, so two partitions are read.
Solution 2
CREATE TABLE orders_by_status (
id integer NOT NULL,
customer_id integer NOT NULL,
order_date date NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL
) PARTITION BY LIST (status);
CREATE TABLE orders_open PARTITION OF orders_by_status
FOR VALUES IN ('pending', 'shipped');
CREATE TABLE orders_closed PARTITION OF orders_by_status
FOR VALUES IN ('delivered', 'cancelled');
INSERT INTO orders_by_status SELECT * FROM big_orders;
SELECT tableoid::regclass AS partition, status, COUNT(*) AS orders
FROM orders_by_status
GROUP BY 1, 2
ORDER BY 1, 2;
EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM orders_by_status WHERE status = 'pending';
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 200000
partition | status | orders
---------------+-----------+--------
orders_open | pending | 9948
orders_open | shipped | 19866
orders_closed | cancelled | 9888
orders_closed | delivered | 160298
(4 rows)
QUERY PLAN
------------------------------------------------
Aggregate
-> Seq Scan on orders_open orders_by_status
Filter: (status = 'pending'::text)
(3 rows)
Only orders_open is read.
Solution 3
SELECT COUNT(*) AS rows_in_default FROM orders_default;
DROP TABLE orders_default;
ALTER TABLE orders_part DETACH PARTITION orders_2025 CONCURRENTLY;
SELECT COUNT(*) AS orders_in_2025 FROM orders_part
WHERE order_date >= '2025-01-01' AND order_date < '2026-01-01';
SELECT COUNT(*) AS rows_in_orders_2025 FROM orders_2025;
rows_in_default
-----------------
0
(1 row)
DROP TABLE
ALTER TABLE
orders_in_2025
----------------
0
(1 row)
rows_in_orders_2025
---------------------
70440
(1 row)
Without a default partition, CONCURRENTLY works. Finally, drop everything (dropping a partitioned table drops its partitions):
DROP TABLE orders_part, orders_2024_archive, orders_2025,
customers_by_region, orders_by_customer, orders_by_status;
DROP TABLE big_orders, big_customers;
DROP TABLE
DROP TABLE
Common mistakes
- No partition for new data. The insert fails with
no partition of relation "orders_part" found for row. Create partitions ahead of time. - A primary key without the partition key.
ADD PRIMARY KEY (id)fails withunique constraint on partitioned table must include all partitioning columns. - A function on the partition key.
extract(year FROM order_date) = 2026read all partitions; use a date range. - Overlapping ranges. A partition for June 2026 next to the 2026 partition fails with
partition "orders_2026_06" would overlap partition "orders_2026". - DETACH CONCURRENTLY in a transaction. Inside
BEGIN(Lesson 19) it fails withALTER TABLE ... DETACH CONCURRENTLY cannot run inside a transaction block.
Frequently asked questions
When should I partition a table in PostgreSQL?
When the table is very large (bigger than the server’s memory, by the manual’s rule of thumb), most queries filter on one column such as a date, and you remove old data in big blocks. Otherwise, try indexes and better queries first.
How many partitions should a table have?
Enough to keep each partition a manageable size, and no more. The manual says the planner handles “up to a few thousand partitions fairly well” when queries prune most of them; the more partitions are left after pruning, the longer planning takes and the more memory it uses.
Can I partition an existing table?
Not in place: “it is not possible to turn a regular table into a partitioned table or vice versa”. Create a new partitioned table and copy the data, or attach the old table as one partition.
Summary
- PostgreSQL table partitioning stores one logical table as several partitions; the parent itself holds no rows.
- RANGE splits by value ranges (dates), LIST by named values, HASH evenly by a hash of the key.
- Partition pruning skips partitions only when the
WHEREclause uses the plain partition key; check it withEXPLAIN. - Indexes on the parent are created on every partition; primary keys must include the partition key.
DETACH PARTITIONarchives old data without a bulkDELETE;ATTACH PARTITIONadds a prepared table.
Next lesson
Next: Lesson 38, SQL Project: Sales Analytics With Cohorts, Retention and Funnels.
Sources
- PostgreSQL documentation: Table Partitioning
- PostgreSQL documentation: Partition Pruning
- PostgreSQL documentation: CREATE TABLE (PARTITION OF, PARTITION BY)
- PostgreSQL documentation: ALTER TABLE (ATTACH PARTITION, DETACH PARTITION)
- PostgreSQL documentation: ANALYZE
- PostgreSQL documentation: WITH Queries (data-modifying statements in WITH)
- PostgreSQL documentation: Query Planning (enable_partition_pruning, plan_cache_mode)
- PostgreSQL documentation: Mathematical Functions (random, setseed)
- PostgreSQL 18 release notes (partitioning changes)





