Abfragen mit FILTER und bedingter Aggregation optimieren
Lernen Sie, wie die FILTER-Klausel und die bedingte Aggregation mit CASE mehrere Kennzahlen in einem einzigen Tabellendurchlauf berechnen, statt mehrere separate Abfragen auszuführen.
Abfragen mit FILTER und bedingter Aggregation optimieren ist eine kostenlose PostgreSQL Performance & Query Optimization-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des PostgreSQL Performance & Query Optimization-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der PostgreSQL Performance & Query Optimization-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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
Häufig gestellte Fragen
Ist die Lektion „Abfragen mit FILTER und bedingter Aggregation optimieren“ kostenlos?
Ja — der vollständige Text von „Abfragen mit FILTER und bedingter Aggregation optimieren“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des PostgreSQL Performance & Query Optimization-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der PostgreSQL Performance & Query Optimization-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Abfragen mit FILTER und bedingter Aggregation optimieren“?
Lernen Sie, wie die FILTER-Klausel und die bedingte Aggregation mit CASE mehrere Kennzahlen in einem einzigen Tabellendurchlauf berechnen, statt mehrere separate Abfragen auszuführen. Du übst PostgreSQL Performance & Query Optimization mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um PostgreSQL Performance & Query Optimization zu starten?
Keine Vorkenntnisse erforderlich. PostgreSQL Performance & Query Optimization auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Abfragen mit FILTER und bedingter Aggregation optimieren“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser PostgreSQL Performance & Query Optimization-Lektion Code schreiben und ausführen?
Ja. Jede PostgreSQL Performance & Query Optimization-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Aggregationen und Fensterfunktionen optimieren
- Rekursive CTEs und Graphabfragen
- Materialisierte Sichten für mehr Leistung verwenden
- Abfragen mit FILTER und bedingter Aggregation optimieren