Optimización de consultas con FILTER y agregación condicional
Aprenda cómo la cláusula FILTER y la agregación condicional basada en CASE permiten calcular varias métricas en un único recorrido de la tabla en lugar de ejecutar varias consultas independientes.
Optimización de consultas con FILTER y agregación condicional 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.
The Problem: Many Counts, One Table
Dashboards often need several metrics from the same table — total orders, paid orders, refunded orders. Running three separate queries scans the table three times. We can do it in one pass.
Conditional Aggregation with CASE
The classic trick wraps a CASE inside an aggregate. Rows that do not match contribute NULL, which COUNT and SUM ignore.
SELECT
COUNT(*) AS total,
COUNT(CASE WHEN status = 'paid' THEN 1 END) AS paid
FROM orders;The Cleaner FILTER Clause
PostgreSQL offers a more readable form: the FILTER clause attached to any aggregate. It expresses intent directly.
SELECT
COUNT(*) AS total,
COUNT(*) FILTER (WHERE status = 'paid') AS paid,
COUNT(*) FILTER (WHERE status = 'refunded') AS refunded
FROM orders;Why This Is Faster
All metrics are computed in a single scan of the table. The planner reads each row once and updates every aggregate, instead of scanning the table separately for each metric.
FILTER with SUM and AVG
FILTER works with any aggregate, not just COUNT. Compute conditional sums and averages in the same query.
SELECT
SUM(total) FILTER (WHERE status = 'paid') AS revenue,
AVG(total) FILTER (WHERE status = 'paid') AS avg_paid
FROM orders;Combining with GROUP BY
FILTER shines inside grouped queries, producing a pivot-like result with one row per group and several conditional columns.
SELECT
region,
COUNT(*) FILTER (WHERE status = 'paid') AS paid,
COUNT(*) FILTER (WHERE status = 'refunded') AS refunded
FROM orders
GROUP BY region;Pivoting Months into Columns
A common report turns rows into columns. FILTER makes a clean monthly pivot without extension functions.
SELECT
product_id,
SUM(total) FILTER (WHERE month = 1) AS jan,
SUM(total) FILTER (WHERE month = 2) AS feb
FROM sales
GROUP BY product_id;Reading the Plan
EXPLAIN ANALYZE confirms a single Aggregate node over one scan. Compare it against three separate queries to see the saved scans.
EXPLAIN ANALYZE
SELECT
COUNT(*) FILTER (WHERE status = 'paid') AS paid,
COUNT(*) FILTER (WHERE status = 'refunded') AS refunded
FROM orders;FILTER vs WHERE
Remember the difference:
- WHERE removes rows before any aggregate sees them
- FILTER keeps all rows but restricts which ones a specific aggregate counts
Use FILTER when different aggregates need different conditions.
Combining with Indexes
If most metrics target a subset (e.g. only recent rows), add a WHERE for the shared condition so an index narrows the scan, then use FILTER for the per-metric splits.
SELECT
COUNT(*) FILTER (WHERE status = 'paid') AS paid
FROM orders
WHERE created_at >= now() - interval '30 days';Counting Distinct Conditionally
FILTER also pairs with COUNT(DISTINCT ...), letting you count unique customers per status in one scan instead of several grouped queries.
SELECT
COUNT(DISTINCT customer_id) FILTER (WHERE status = 'paid') AS paying_customers
FROM orders;Quick Check
Test your conditional aggregation knowledge.
Recap
You learned conditional aggregation:
- Compute many metrics in one scan with FILTER or CASE
- FILTER is more readable and works with any aggregate
- Combine with GROUP BY for pivot-style reports
- WHERE removes rows; FILTER restricts a single aggregate
- Add a shared WHERE so indexes narrow the scan
Preguntas frecuentes
¿La lección «Optimización de consultas con FILTER y agregación condicional» es gratis?
Sí — el texto completo de «Optimización de consultas con FILTER y agregación condicional» 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 «Optimización de consultas con FILTER y agregación condicional»?
Aprenda cómo la cláusula FILTER y la agregación condicional basada en CASE permiten calcular varias métricas en un único recorrido de la tabla en lugar de ejecutar varias consultas independientes. 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 «Optimización de consultas con FILTER y agregación condicional»?
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
- Optimización de agregaciones y funciones de ventana
- CTE recursivas y consultas sobre grafos
- Uso de vistas materializadas para mejorar el rendimiento
- Optimización de consultas con FILTER y agregación condicional