Particionamiento por rangos de tiempo
Aprenda a particionar tablas grandes por rangos temporales para mantener el acceso rápido a los datos recientes y archivar los antiguos de forma eficiente.
Particionamiento por rangos de tiempo es una lección gratuita de Advanced PostgreSQL: Indexing, Partitioning, Replication en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Advanced PostgreSQL: Indexing, Partitioning, Replication, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Advanced PostgreSQL: Indexing, Partitioning, Replication incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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.
Preguntas frecuentes
¿La lección «Particionamiento por rangos de tiempo» es gratis?
Sí — el texto completo de «Particionamiento por rangos de tiempo» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Advanced PostgreSQL: Indexing, Partitioning, Replication, actualiza a CoddyKit PRO. El curso de Advanced PostgreSQL: Indexing, Partitioning, Replication incluye 4 lecciones en total.
¿Qué aprenderé en «Particionamiento por rangos de tiempo»?
Aprenda a particionar tablas grandes por rangos temporales para mantener el acceso rápido a los datos recientes y archivar los antiguos de forma eficiente. Practicas Advanced PostgreSQL: Indexing, Partitioning, Replication con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Advanced PostgreSQL: Indexing, Partitioning, Replication?
No se requiere experiencia previa. Advanced PostgreSQL: Indexing, Partitioning, Replication en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Particionamiento por rangos de tiempo»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Advanced PostgreSQL: Indexing, Partitioning, Replication?
Sí. Cada lección de Advanced PostgreSQL: Indexing, Partitioning, Replication incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Particionamiento hash para distribución
- Técnicas de subparticionamiento
- Gestión de tablas particionadas
- Particionamiento por rangos de tiempo