Quick revision
The short answer
We declare the parent with PARTITION BY RANGE (created_at), make the primary key (id, created_at) because uniqueness is checked per partition, then add a partition FOR VALUES FROM ('2026-11-01') TO ('2026-12-01') and a DEFAULT partition. Partition pruning lets PostgreSQL skip partitions whose range cannot match, but only when the query compares created_at itself with values known at planning or execution time.
What to remember
In this answer, we wrote the DDL for a range-partitioned events table with a November 2026 partition and a default partition. We saw that the primary key must include created_at because each partition enforces uniqueness on its own, that pruning skips partitions by comparing conditions on created_at with partition bounds at planning or execution time, that functions on the column defeat pruning, and that a default partition slows down adding new partitions, so partitions should be created ahead of time.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We declare the parent with PARTITION BY RANGE (created_at), make the primary key (id, created_at) because uniqueness is checked per partition, then add a partition FOR VALUES FROM ('2026-11-01') TO ('2026-12-01') and a DEFAULT partition. Partition pruning lets PostgreSQL skip partitions whose range cannot match, but only when the query compares created_at itself with values known at planning or execution time.
Why this question is asked
Time-based partitioning is the most common partitioning in real systems: events, logs, audit trails and orders all grow by date, and old months are eventually dropped. Interviewers ask for the DDL to see whether we know the rules PostgreSQL enforces, and they ask about pruning because a partitioned table only pays off when queries are written so the planner can skip partitions. In this answer, we will recap declarative partitioning, write the DDL step by step, see why the primary key must include created_at, understand how pruning works and what a query must look like, and look at the cost of a default partition.
1A Quick Recap of Declarative Partitioning
A partitioned table in PostgreSQL is a parent table that holds no rows itself. Its rows live in child tables called partitions, and each partition owns a slice of the values of the partition key. With range partitioning, each partition owns a range, here one calendar month of created_at.
When we insert into the parent, PostgreSQL routes the row to the partition whose range contains its created_at. When we query the parent, PostgreSQL decides which partitions could hold matching rows and reads only those. That second step is partition pruning, and it is where most of the read performance benefit comes from.
2Writing the DDL
Here is the full DDL. The parent declares the columns, the key and the partitioning method; the partitions declare only their bounds.
Notice that the upper bound is exclusive. FROM ('2026-11-01') TO ('2026-12-01') holds every instant from midnight on 1 November up to, but not including, midnight on 1 December, so consecutive months never overlap and never leave a gap. Also notice the time zone: a timestamptz bound written without an offset is interpreted in the session's TimeZone setting, so we should set it deliberately (or write the offset, such as '2026-11-01 00:00+00') to get the month boundaries we intend. The created_at column is NOT NULL because a range partition cannot hold a null key except in the default partition, and we do not want nulls there either.
3Why the Primary Key Must Include created_at
PostgreSQL enforces a primary key or unique constraint with a unique index, and on a partitioned table each partition has its own index. An index on events_2026_11 knows nothing about the rows in events_2026_12. So if the key were only id, two partitions could each accept id 42 and no single index would notice.
PostgreSQL avoids this by requiring every unique constraint on a partitioned table to include all partition key columns. If created_at is in the key, two rows with the same key would necessarily have the same created_at, so they would land in the same partition, and that partition's index can enforce uniqueness. That is why PRIMARY KEY (id) is rejected and PRIMARY KEY (id, created_at) is accepted. In practice the identity column still gives unique ids; the composite key is the price of partitioning, and foreign keys that point to events must reference both columns.
4How Partition Pruning Works
Pruning means PostgreSQL compares the query's conditions on created_at with each partition's bounds and removes partitions that cannot contain a match. It happens at two moments. At planning time, when the values are constants written in the query, the planner simply leaves those partitions out of the plan. At execution time, when the values arrive as parameters of a prepared statement, or come from a subquery or a join, the executor prunes before scanning; EXPLAIN shows this as 'Subplans Removed'.
- Query on events arrivesWHERE created_at >= $1 AND created_at < $2
- Condition on created_at itself?YesCompare with partition boundsNoRead every partition
- Values known at planning time?YesPlanner removes partitionsNoExecutor removes them at run time
- Scan remaining partitionsusually one month
4 steps in order. Play them, or step through them one at a time.
Pruning needs a plain comparison on the partition key column.
So a query benefits when it filters on the partition key directly with comparisons the planner understands: =, <, <=, >, >=, BETWEEN or IN on created_at. JPA and JDBC queries are usually prepared statements with parameters, and they are still pruned, at execution time. A query that has no condition on created_at, like the second one, reads every partition and is often slower than on a plain table, because there are more indexes and more plan nodes.
5The Cost of a Default Partition
The default partition catches any row whose created_at has no partition yet, so inserts never fail with 'no partition of relation found for row'. That safety is useful, but it has a cost. When we later create events_2027_01, PostgreSQL must make sure no row already in the default partition belongs in January 2027, so it scans the default partition while holding a lock. If the default has collected millions of rows, creating the next month becomes slow and blocks writes. Worse, if it finds such rows, the CREATE fails and we must move them first.
The practical rule is to create partitions well ahead of time, for example three months in advance, with pg_partman or a scheduled job (a Spring @Scheduled task or a cron job running a small SQL function), and to alert when the default partition is not empty. Then the default is an emergency net, not a place where data lives.
6Follow-up questions
Why is WHERE date_trunc('day', created_at) = ... worse for pruning?
Because the condition is on the result of a function, not on created_at itself. The planner compares conditions on the partition key with the partition bounds, and it cannot in general turn date_trunc('day', created_at) = '2026-11-10' back into a range on created_at, so it reads every partition. The same applies to casts such as created_at::date. The fix is to rewrite it as a range: created_at >= '2026-11-10' AND created_at < '2026-11-11', which prunes to one partition and can use an index on created_at.
Do indexes have to be created on every partition?
No. Since PostgreSQL 11 we create the index once on the parent, and PostgreSQL creates a matching index on every existing partition and on every new partition automatically. Creating it on the parent is the safe habit, because then no partition is ever forgotten.
How do we remove November 2026 when it expires?
We detach or drop the partition: ALTER TABLE events DETACH PARTITION events_2026_11 CONCURRENTLY, then DROP TABLE events_2026_11. That takes seconds regardless of size and leaves no bloat, unlike a DELETE of millions of rows.
7Conclusion
In this answer, we wrote the DDL for a range-partitioned events table with a November 2026 partition and a default partition. We saw that the primary key must include created_at because each partition enforces uniqueness on its own, that pruning skips partitions by comparing conditions on created_at with partition bounds at planning or execution time, that functions on the column defeat pruning, and that a default partition slows down adding new partitions, so partitions should be created ahead of time.
Open with
I would create the parent as events with id, created_at timestamptz not null and payload jsonb, with PRIMARY KEY (id, created_at), and PARTITION BY RANGE (created_at). Then CREATE TABLE events_2026_11 PARTITION OF events FOR VALUES FROM '2026-11-01' TO '2026-12-01', where the upper bound is exclusive, and CREATE TABLE events_default PARTITION OF events DEFAULT.
Then, if they want more
The key has to include created_at because uniqueness is enforced by a separate index in each partition, so PostgreSQL only allows unique constraints that contain the partition key. Partition pruning means the planner compares the query's conditions on created_at with each partition's bounds and skips partitions that cannot match.
With constants it happens at planning time, and with prepared-statement parameters, which is what JPA sends, it happens at execution time. To benefit, the query must compare created_at itself, like created_at >= :from and created_at < :to.
If I wrap the column in a function, like date_trunc or a cast to date, or filter on something else entirely, every partition is scanned. On the default partition: it stops inserts failing, but creating a new partition has to scan the default for rows that belong to it, so if it fills up, adding next month gets slow.
I would create partitions a few months ahead with pg_partman or a scheduled job and alert if the default is not empty.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 11
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write PostgreSQL DDL for an events table partitioned by month on created_at, with one...": https://scrivio-interview-library.netlify.app/databases/partitioning-and-sharding/531c7fbb47/