Ottimizzare le query con FILTER e l'aggregazione condizionale
Impari come la clausola FILTER e l'aggregazione condizionale basata su CASE permettono di calcolare più metriche in un'unica scansione della tabella, invece di eseguire diverse query separate.
Ottimizzare le query con FILTER e l'aggregazione condizionale è una lezione PostgreSQL Performance & Query Optimization gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento PostgreSQL Performance & Query Optimization, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso PostgreSQL Performance & Query Optimization include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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
Domande Frequenti
La lezione «Ottimizzare le query con FILTER e l'aggregazione condizionale» è gratuita?
Sì — il testo completo di «Ottimizzare le query con FILTER e l'aggregazione condizionale» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso PostgreSQL Performance & Query Optimization, passa a CoddyKit PRO. Il corso PostgreSQL Performance & Query Optimization include 4 lezioni in totale.
Cosa imparerò in «Ottimizzare le query con FILTER e l'aggregazione condizionale»?
Impari come la clausola FILTER e l'aggregazione condizionale basata su CASE permettono di calcolare più metriche in un'unica scansione della tabella, invece di eseguire diverse query separate. Eserciti PostgreSQL Performance & Query Optimization con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare PostgreSQL Performance & Query Optimization?
Non è richiesta alcuna esperienza precedente. PostgreSQL Performance & Query Optimization su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Ottimizzare le query con FILTER e l'aggregazione condizionale»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione PostgreSQL Performance & Query Optimization?
Sì. Ogni lezione PostgreSQL Performance & Query Optimization include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Ottimizzazione di aggregazioni e funzioni finestra
- CTE ricorsive e query su grafi
- Utilizzo delle viste materializzate per le prestazioni
- Ottimizzare le query con FILTER e l'aggregazione condizionale