Junções e agregações por partição
Descubra como o PostgreSQL pode unir e agregar tabelas particionadas, partição por partição, obtendo grandes ganhos de desempenho.
Junções e agregações por partição é 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.
What Are Partition-wise Operations
When two tables are partitioned the same way, PostgreSQL can join matching partitions to each other instead of joining the whole tables. This is a partition-wise join.
The same idea applies to grouping: a partition-wise aggregate.
Enabling the Feature
These optimizations are off by default because they increase planning cost. Turn them on per session or in postgresql.conf.
SET enable_partitionwise_join = on;
SET enable_partitionwise_aggregate = on;Matching Partition Boundaries
For a partition-wise join the tables must share the same partition key type and identical bounds. Otherwise the planner cannot pair partitions.
Example Setup
Two tables partitioned by the same range on customer_id.
CREATE TABLE orders (customer_id int, total numeric)
PARTITION BY RANGE (customer_id);
CREATE TABLE refunds (customer_id int, amount numeric)
PARTITION BY RANGE (customer_id);The Join
With matching partitions, this join runs as several small joins, each fitting in memory more easily.
SELECT o.customer_id, sum(o.total), sum(r.amount)
FROM orders o
JOIN refunds r USING (customer_id)
GROUP BY o.customer_id;Why It Is Faster
Smaller per-partition joins mean:
- Smaller hash tables that fit in
work_mem - Better cache locality
- Opportunities for parallel workers per partition
Reading the Plan
Use EXPLAIN to confirm. You will see an Append node over several join nodes rather than one giant join.
EXPLAIN
SELECT * FROM orders o JOIN refunds r USING (customer_id);Partition-wise Aggregate
If you group by the partition key, each partition is aggregated independently and the results are concatenated. No global sort or hash across the whole table is needed.
SELECT customer_id, sum(total)
FROM orders
GROUP BY customer_id;Planning Cost Trade-off
With many partitions, considering each one increases planning time. Enable these settings only when partition counts are moderate and the query benefits clearly.
Combining with Pruning
Partition-wise joins combine well with partition pruning: pruning removes irrelevant partitions first, then the remaining ones are joined pair-by-pair.
When It Does Not Apply
If only one table is partitioned, or the bounds differ, PostgreSQL falls back to a normal join over the appended partitions.
Quick Check
What is required for a partition-wise join?
Recap
You learned to speed up queries on partitioned tables with partition-wise joins and aggregates. Enable the settings, ensure matching bounds, verify with EXPLAIN, and combine with pruning for the best results.
Perguntas Frequentes
A aula “Junções e agregações por partição” é grátis?
Sim — o texto completo de “Junções e agregações por partição” é 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 “Junções e agregações por partição”?
Descubra como o PostgreSQL pode unir e agregar tabelas particionadas, partição por partição, obtendo grandes ganhos de desempenho. 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 “Junções e agregações por partição”?
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
- Otimização de consultas com particionamento
- Anexando e desanexando partições
- Eliminação e exclusão de partições
- Junções e agregações por partição