Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 137/ 160
07. Indexing, Query Optimization & Performance Tuning

Table Partitioning (Range, List, Hash) & Partition Pruning

Partition large tables and rely on partition pruning to skip cold data.

AdvancedRange / List / Hash · Partition Pruning3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Split a huge table into smaller tables by month (or region), so the database only opens the parts it needs.

Think of it like…

Filing invoices in one folder per month instead of a single giant drawer: finding March's invoices means opening one folder, and throwing out last year's is just removing twelve folders.

Where you’ve seen it

An events table receives 50 million rows a day and keeps 13 months. Partitioning by month means dashboards for the last 7 days scan one or two partitions, and retention is DROP TABLE events_2025_10; once a month, instantly, instead of a DELETE of 1.5 billion rows.

Words you’ll hear

Partition key
The column(s) that decide which partition a row goes to.
Partition pruning
Skipping partitions that can't contain matching rows, shown in EXPLAIN.
RANGE / LIST / HASH
Partition by value ranges, by explicit value lists, or by a hash for even spread.
Detach / drop
Removing a whole partition at once, which is the fast way to delete old data.

Visual diagram

Loading interactive diagram

Theory & example queries

How partitioning works

In PostgreSQL 10+ you declare a parent table PARTITION BY RANGE (created_at) and attach child tables for ranges such as each month. Inserts are routed to the right partition automatically, and queries against the parent are planned across the partitions. Each partition has its own indexes, which are smaller than one giant index.

When the WHERE clause constrains the partition key, the planner (and, for parameters, the executor) prunes partitions that can't match. EXPLAIN shows only the scanned partitions. RANGE suits time-series data; LIST suits a fixed set of values like country; HASH spreads rows evenly when there's no natural range.

Monthly range partitions (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE TABLE events (2  id bigint,3  created_at timestamptz NOT NULL,4  payload jsonb5)6PARTITION BY7  RANGE (created_at);89CREATE TABLE events_2026_11 PARTITION OF events FOR10VALUES11FROM12  ('2026-11-01') TO ('2026-12-01');
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Partition creation status
CREATE TABLE CREATE TABLE

Note: PostgreSQL-style command tags; the parent and November 2026 child partition are created successfully.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Rows are routed by the key; queries filtering on the key skip other partitions.

When it helps, and the costs

Partitioning pays off for very large tables (typically hundreds of gigabytes or billions of rows) where queries usually filter by the key, and especially for retention: dropping or detaching a partition is instant and leaves no bloat, unlike a huge DELETE. Maintenance like VACUUM and reindexing also runs per partition.

It doesn't replace indexes, and queries without the partition key get slower because they visit every partition. In PostgreSQL, primary keys and unique constraints must include the partition key. Partitions must be created ahead of time (tools like pg_partman automate this), a DEFAULT partition catches stray rows, and thousands of partitions add planning overhead.

Retention without DELETEQuery example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1ALTER TABLE events DETACH PARTITION events_2025_10;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/1
query.sql
1DROP TABLE events_2025_10;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/1
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative detach-and-drop path
ALTER TABLE DROP TABLE

Note: Shows the drop option after detaching the October 2025 partition. Archiving the detached table is the alternative path, so DROP is not inevitable.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

then archive it, or simply

Key takeaway: Partition for scale and retention, around the key your queries filter on.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Analysis

Confirm the need

Check that the table is very large, that most queries filter on one column (usually time), or that you need fast retention.

SQL at this stepReadable preview
1billions of rows ·2WHERE created_at …
What to watch at this step
Not a fix for
missing indexes
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Partitioning splits one large logical table into smaller physical pieces by a partition key: RANGE (by date, such as one partition per month), LIST (by values, such as region) or HASH (spread evenly by a key). Queries that filter on the key read only the relevant partitions, which is called partition pruning, and old data can be removed by dropping a partition instead of deleting rows.

Why it matters: Tables with billions of rows of time-series data (events, logs, orders) become slow to query, maintain and clean up. Partitioning makes retention instant and keeps indexes smaller, but it also adds complexity and only helps queries that filter on the partition key. It's a common senior database and system design topic.

When to reach for it

  • Large time-series tables with time-based queries
  • Fast data retention by dropping old partitions
  • Keeping indexes and maintenance per partition manageable

When to avoid or be careful

  • Partitioning small or medium tables
  • Choosing a key that most queries don't filter on
  • Thousands of tiny partitions

RANGE vs LIST vs HASH partitioning

RANGE
Best for: Time-series data: events, logs, orders

Strengths: Natural pruning on date filters; instant retention.

Watch out: Partitions must be created for future ranges.

LIST
Best for: A known set of values: region, tenant tier

Strengths: Clear separation; easy to manage per value.

Watch out: Uneven partition sizes; new values need new partitions or a DEFAULT.

HASH
Best for: Spreading load evenly when there's no natural range

Strengths: Balanced partition sizes.

Watch out: Pruning only for equality on the key; no easy retention.

Interview signals & numbers to know

When this topic comes up

  • “The events table has 5 billion rows”
  • “Deleting old data takes hours”
  • “How would you design storage for logs?”
  • Partition pruning
  • Retention policy

Benchmarks & rules of thumb

PostgreSQL 10 -
declarative partitioning
3 -
methods: RANGE, LIST, HASH
0 rows -
deleted row by row when you drop a partition

Common mistakes & follow-ups

Common interview mistakes

  • Partitioning by month and then querying mostly by user_id, so every query scans every partition.
  • Forgetting to create next month's partition, so inserts fail or land in the DEFAULT partition.
  • Expecting a global unique constraint on id alone in a PostgreSQL partitioned table.

Likely interviewer follow-ups

  • How does partition pruning work, and how do you check it's happening?
  • Why is dropping a partition better than deleting old rows?
  • When would partitioning make queries slower?
Interview tip: Lead with the retention benefit and pruning, then name the costs (queries without the key, unique constraint rules, partition management). Interviewers want to hear that partitioning is a trade-off, not a free speed-up.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Table Partitioning (Range, List, Hash) & Partition Pruning with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Keyset / Cursor Pagination vs Slow OFFSET Pagination
Next topic
Connection Pooling (PgBouncer) & Statement Timeouts