0Pricing
PostgreSQL Performance & Query Optimization · درس

تحسين الاستعلامات باستخدام FILTER والتجميع الشرطي

تعلّم كيف تتيح عبارة FILTER والتجميع الشرطي القائم على CASE حساب مقاييس متعددة في مرور واحد على الجدول بدلًا من تشغيل عدة استعلامات منفصلة

تحسين الاستعلامات باستخدام FILTER والتجميع الشرطي درس مجاني في PostgreSQL Performance & Query Optimization على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في PostgreSQL Performance & Query Optimization، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة PostgreSQL Performance & Query Optimization 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

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

الأسئلة الشائعة

هل درس «تحسين الاستعلامات باستخدام FILTER والتجميع الشرطي» مجاني؟

نعم — نص درس «تحسين الاستعلامات باستخدام FILTER والتجميع الشرطي» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة PostgreSQL Performance & Query Optimization، انتقل إلى CoddyKit PRO. تتضمن دورة PostgreSQL Performance & Query Optimization 4 دروس في المجموع.

ماذا ستتعلم في «تحسين الاستعلامات باستخدام FILTER والتجميع الشرطي»؟

تعلّم كيف تتيح عبارة FILTER والتجميع الشرطي القائم على CASE حساب مقاييس متعددة في مرور واحد على الجدول بدلًا من تشغيل عدة استعلامات منفصلة تتمرن على PostgreSQL Performance & Query Optimization مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ PostgreSQL Performance & Query Optimization؟

لا تُشترط خبرة سابقة. PostgreSQL Performance & Query Optimization على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «تحسين الاستعلامات باستخدام FILTER والتجميع الشرطي»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس PostgreSQL Performance & Query Optimization هذا؟

نعم. كل درس في PostgreSQL Performance & Query Optimization يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. تحسين الدوال التجميعية ودوال النوافذ
  2. CTEs العودية واستعلامات الرسوم البيانية
  3. استخدام العروض المادية لتحسين الأداء
  4. تحسين الاستعلامات باستخدام FILTER والتجميع الشرطي
← العودة إلى PostgreSQL Performance & Query Optimization