Lendo estimativas de custo e contagens de linhas do EXPLAIN
Aprenda a interpretar os números de custo, as linhas estimadas e os valores de largura que o EXPLAIN associa a cada nó do plano, além de identificar quando as estimativas do planejador estão erradas.
Lendo estimativas de custo e contagens de linhas do EXPLAIN é uma aula grátis de PostgreSQL Performance & Query Optimization 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 PostgreSQL Performance & Query Optimization, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de PostgreSQL Performance & Query Optimization inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
What the Cost Numbers Mean
Every node in an EXPLAIN plan shows a cost=startup..total pair. These are arbitrary planner units, not milliseconds. The planner uses them only to compare alternative plans and pick the cheapest one.
Startup vs Total Cost
The two numbers tell different stories:
- Startup cost: work before the first row is returned (e.g. building a hash table)
- Total cost: work to return all rows
A node that must sort or aggregate everything has a high startup cost.
A Sample Plan
Run EXPLAIN on a simple query and read the cost on each line.
EXPLAIN SELECT * FROM orders WHERE total > 100;The rows Estimate
Each node shows rows=N, the planner's estimated number of rows it will emit. The planner derives this from table statistics gathered by ANALYZE.
Bad estimates lead to bad plans, so this number matters a lot.
The width Value
The width=N field is the estimated average row size in bytes. Multiplied by rows it estimates memory and I/O needs, which influences whether sorts or hashes spill to disk.
Estimated vs Actual
EXPLAIN alone shows only estimates. Add ANALYZE to also run the query and see real timings and real row counts side by side.
EXPLAIN ANALYZE SELECT * FROM orders WHERE total > 100;Spotting Estimate Errors
Compare rows (estimate) with actual rows in EXPLAIN ANALYZE output. A large gap — say estimate 10 but actual 100000 — signals stale or insufficient statistics.
Why Estimates Drift
Estimates go stale when:
- Data changed a lot since the last
ANALYZE - Columns are correlated and the planner assumes independence
- The default statistics target is too low for skewed data
Refreshing Statistics
Run ANALYZE to recompute statistics for a table. Better stats produce better row estimates and therefore better plans.
ANALYZE orders;Raising the Statistics Target
For columns with skewed distributions, increase how many distinct values are sampled. A higher target means more accurate estimates at the cost of slightly slower ANALYZE.
ALTER TABLE orders ALTER COLUMN total SET STATISTICS 500;
ANALYZE orders;Cost Multipliers in postgresql.conf
Constants like seq_page_cost, random_page_cost, and cpu_tuple_cost scale how the planner weighs disk vs CPU. On SSDs, lowering random_page_cost makes index scans look cheaper.
Quick Check
Test your understanding of cost estimates.
Recap
You learned to read EXPLAIN's numbers:
- Cost is in arbitrary units; startup vs total cost differ
rowsandwidthare estimates from statistics- Compare estimated vs actual rows to spot bad stats
- Fix drift with
ANALYZEand a higher statistics target - Cost constants tune disk-vs-CPU weighting
Perguntas Frequentes
A aula “Lendo estimativas de custo e contagens de linhas do EXPLAIN” é grátis?
Sim — o texto completo de “Lendo estimativas de custo e contagens de linhas do EXPLAIN” é 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 PostgreSQL Performance & Query Optimization, atualize para CoddyKit PRO. O curso de PostgreSQL Performance & Query Optimization inclui 4 aulas no total.
O que vou aprender em “Lendo estimativas de custo e contagens de linhas do EXPLAIN”?
Aprenda a interpretar os números de custo, as linhas estimadas e os valores de largura que o EXPLAIN associa a cada nó do plano, além de identificar quando as estimativas do planejador estão erradas. Você pratica PostgreSQL Performance & Query Optimization 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 PostgreSQL Performance & Query Optimization?
Nenhuma experiência prévia é necessária. PostgreSQL Performance & Query Optimization 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 “Lendo estimativas de custo e contagens de linhas do EXPLAIN”?
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 PostgreSQL Performance & Query Optimization?
Sim. Cada aula de PostgreSQL Performance & Query Optimization 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
- Introdução a EXPLAIN e ANALYZE
- Interpretando nós de planos
- Identificando gargalos de desempenho
- Lendo estimativas de custo e contagens de linhas do EXPLAIN