Particionamento por intervalos de tempo
Aprenda a particionar tabelas grandes por intervalos de tempo para manter os dados recentes rápidos e arquivar os dados antigos com eficiência.
Particionamento por intervalos de tempo é uma aula grátis de Advanced PostgreSQL: Indexing, Partitioning, Replication no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Advanced PostgreSQL: Indexing, Partitioning, Replication, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Advanced PostgreSQL: Indexing, Partitioning, Replication inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Range Partitioning
Range partitioning splits a table into chunks based on a continuous value, most often a date or timestamp.
It is the most common strategy for time-series data such as logs, events, and orders, because old data can be dropped or archived as a whole partition.
Declaring a Range-Partitioned Table
You declare partitioning with PARTITION BY RANGE on the parent table.
CREATE TABLE events (
id bigserial,
created_at timestamptz NOT NULL,
payload jsonb
) PARTITION BY RANGE (created_at);Creating Monthly Partitions
Each child partition covers a half-open interval: the lower bound is inclusive and the upper bound is exclusive.
CREATE TABLE events_2024_01 PARTITION OF events
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
CREATE TABLE events_2024_02 PARTITION OF events
FOR VALUES FROM ('2024-02-01') TO ('2024-03-01');Half-Open Intervals
The exclusive upper bound prevents gaps and overlaps. A row at exactly 2024-02-01 00:00:00 lands in events_2024_02, never in January.
This makes consecutive partitions perfectly contiguous.
Inserting Routes Automatically
You insert into the parent table. PostgreSQL routes each row to the correct partition based on the range key.
INSERT INTO events (created_at, payload)
VALUES ('2024-01-15', '{"type":"login"}');
-- lands in events_2024_01A DEFAULT Partition
A DEFAULT partition catches any row that does not match a defined range, avoiding insert errors.
CREATE TABLE events_default PARTITION OF events DEFAULT;Indexes on Partitions
An index created on the parent is automatically propagated to all current and future partitions.
CREATE INDEX ON events (created_at);Dropping Old Data Instantly
The killer feature: deleting old data is just DROP TABLE on a partition. No row-by-row DELETE, no bloat, no vacuum pressure.
DROP TABLE events_2024_01;Querying with Pruning
When the planner sees a range predicate on the partition key it can skip entire partitions. This is called partition pruning.
SELECT count(*) FROM events
WHERE created_at >= '2024-02-10'
AND created_at < '2024-02-20';
-- only events_2024_02 is scannedAutomating Partition Creation
Tools like pg_partman create future partitions ahead of time on a schedule, so you never insert into the default partition by accident.
- Define a retention window
- Pre-create N future partitions
- Detach or drop expired ones
Choosing the Range Width
Pick a width that keeps each partition in the tens of millions of rows. Too many tiny partitions hurt planning time; too few huge ones lose pruning benefits.
Quick Check
Why is dropping an old partition better than a bulk DELETE?
Recap
You learned range partitioning by time: declare with PARTITION BY RANGE, create half-open child intervals, rely on automatic routing and pruning, and archive by dropping whole partitions. Automation tools like pg_partman keep the partition set healthy.
Perguntas Frequentes
A aula “Particionamento por intervalos de tempo” é grátis?
Sim — o texto completo de “Particionamento por intervalos de tempo” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Advanced PostgreSQL: Indexing, Partitioning, Replication, atualize para CoddyKit PRO. O curso de Advanced PostgreSQL: Indexing, Partitioning, Replication inclui 4 aulas no total.
O que vou aprender em “Particionamento por intervalos de tempo”?
Aprenda a particionar tabelas grandes por intervalos de tempo para manter os dados recentes rápidos e arquivar os dados antigos com eficiência. Você pratica Advanced PostgreSQL: Indexing, Partitioning, Replication com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Advanced PostgreSQL: Indexing, Partitioning, Replication?
Nenhuma experiência prévia é necessária. Advanced PostgreSQL: Indexing, Partitioning, Replication no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Particionamento por intervalos de tempo”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Advanced PostgreSQL: Indexing, Partitioning, Replication?
Sim. Cada aula de Advanced PostgreSQL: Indexing, Partitioning, Replication inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Particionamento por hash para distribuição
- Técnicas de subparticionamento
- Gerenciando tabelas particionadas
- Particionamento por intervalos de tempo