Lectura de las estimaciones de coste y recuentos de filas de EXPLAIN
Aprenda a interpretar los valores de coste, las filas estimadas y los valores de width que EXPLAIN asigna a cada nodo del plan, y a detectar cuándo las estimaciones del planificador son incorrectas.
Lectura de las estimaciones de coste y recuentos de filas de EXPLAIN es una lección gratuita de PostgreSQL Performance & Query Optimization 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 PostgreSQL Performance & Query Optimization, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de PostgreSQL Performance & Query Optimization incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en 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
Preguntas frecuentes
¿La lección «Lectura de las estimaciones de coste y recuentos de filas de EXPLAIN» es gratis?
Sí — el texto completo de «Lectura de las estimaciones de coste y recuentos de filas de EXPLAIN» 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 PostgreSQL Performance & Query Optimization, actualiza a CoddyKit PRO. El curso de PostgreSQL Performance & Query Optimization incluye 4 lecciones en total.
¿Qué aprenderé en «Lectura de las estimaciones de coste y recuentos de filas de EXPLAIN»?
Aprenda a interpretar los valores de coste, las filas estimadas y los valores de width que EXPLAIN asigna a cada nodo del plan, y a detectar cuándo las estimaciones del planificador son incorrectas. Practicas PostgreSQL Performance & Query Optimization 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 PostgreSQL Performance & Query Optimization?
No se requiere experiencia previa. PostgreSQL Performance & Query Optimization 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 «Lectura de las estimaciones de coste y recuentos de filas de EXPLAIN»?
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 PostgreSQL Performance & Query Optimization?
Sí. Cada lección de PostgreSQL Performance & Query Optimization 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
- Introducción a EXPLAIN y ANALYZE
- Interpretación de nodos de planes
- Identificación de cuellos de botella de rendimiento
- Lectura de las estimaciones de coste y recuentos de filas de EXPLAIN