0Pricing
NestJS Enterprise Backend APIs · درس

استراتيجيات تحسين الاستعلامات

تعمّق في تقنيات تحسين الاستعلامات المتقدمة، بما في ذلك تحليل خطط التنفيذ، وإعادة كتابة الاستعلامات، واستخدام العروض المادية

استراتيجيات تحسين الاستعلامات درس مجاني في NestJS Enterprise Backend APIs على CoddyKit. هذا هو الدرس 4 من أصل 6. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في NestJS Enterprise Backend APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة NestJS Enterprise Backend APIs 6 دروس في المجموع.

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

Why Optimize Database Queries?

Database queries are the backbone of most applications. When they run slowly, your users experience delays, and your application consumes more resources.

Query optimization is the process of improving the efficiency of database queries to reduce their execution time and resource usage.

PostgreSQL's Query Optimizer

Before executing a query, PostgreSQL's internal query optimizer analyzes it to determine the most efficient way to retrieve the data. It considers:

  • Available indexes
  • Table sizes and statistics
  • Join types and order
  • Data distribution

The optimizer then generates an execution plan.

Introducing EXPLAIN

The EXPLAIN command allows you to see the execution plan that PostgreSQL's optimizer generates for a query, without actually running the query.

This is invaluable for understanding how your database intends to fetch data and identifying potential bottlenecks.

Understanding EXPLAIN Output

When you run EXPLAIN, you'll see a tree-like structure. Key metrics to look for include:

  • cost: An estimated measure of the query's total execution expense. The first number is startup cost, the second is total cost. Lower is better.
  • rows: The estimated number of rows that will be processed or returned by each operation.
  • width: The estimated average width (in bytes) of the output rows from each operation.

EXPLAIN ANALYZE: Real Performance

While EXPLAIN shows estimates, EXPLAIN ANALYZE actually runs the query and collects real-world statistics. This is crucial for verifying if the optimizer's estimates match reality.

It adds actual time and actual rows to the output.

CREATE TABLE products (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255),
  price DECIMAL(10, 2)
);
INSERT INTO products (name, price) VALUES
('Laptop', 1200.00), ('Mouse', 25.00), ('Keyboard', 75.00), ('Monitor', 300.00), ('Webcam', 50.00);

-- Now, try explaining the query's actual performance:
-- EXPLAIN ANALYZE SELECT * FROM products WHERE price > 100;

Rewriting Suboptimal Queries: OR vs UNION ALL

Sometimes, how you write a query can drastically affect performance. For example, using OR in a WHERE clause can sometimes prevent index usage, leading to full table scans.

For multiple conditions, UNION ALL can sometimes be more efficient, especially if indexes exist on the individual columns, as it can leverage separate index scans.

-- Consider a 'users' table with indexes on 'country' and 'city'

-- Suboptimal (may not use index efficiently across OR)
-- EXPLAIN ANALYZE SELECT * FROM users WHERE country = 'USA' OR city = 'New York';

-- Potentially better (can use separate indexes for each part)
-- EXPLAIN ANALYZE
-- SELECT * FROM users WHERE country = 'USA'
-- UNION ALL
-- SELECT * FROM users WHERE city = 'New York' AND country <> 'USA'; -- Avoid duplicates if needed

Optimizing Joins for Speed

The order of tables in a join and the presence of indexes on the join columns are critical. PostgreSQL tries to pick the best join order, but sometimes hints or rewriting can help.

  • Ensure indexes are present on columns used in ON clauses.
  • Filter early: Apply WHERE clauses to individual tables before joining whenever possible.
  • Consider the impact of LEFT JOIN vs. INNER JOIN on the result set size.
-- Assume 'users' and 'orders' tables, with an index on orders.user_id

-- EXPLAIN ANALYZE
-- SELECT u.name, o.order_date
-- FROM users u
-- JOIN orders o ON u.id = o.user_id
-- WHERE u.country = 'Germany' AND o.total_amount > 100;

-- Filtering 'users' first can reduce the number of rows joined.

Introducing Materialized Views

Materialized Views are pre-computed sets of data that are stored on disk. Unlike regular views, which are just stored queries, materialized views store the actual results of a query.

They are ideal for complex, aggregate queries or reports that don't need real-time data and are queried frequently. Reading from a materialized view is much faster than re-running the original complex query.

Creating a Materialized View

To create a materialized view, you use the CREATE MATERIALIZED VIEW statement, followed by the query whose results you want to store.

Remember, the data in a materialized view is a snapshot at the time of creation.

CREATE TABLE orders (
  id SERIAL PRIMARY KEY,
  user_id INT,
  order_date DATE,
  total_amount DECIMAL(10, 2)
);
INSERT INTO orders (user_id, order_date, total_amount) VALUES
(1, '2023-01-15', 150.00), (2, '2023-01-20', 200.50),
(1, '2023-02-10', 300.00), (3, '2023-02-25', 50.00);

CREATE MATERIALIZED VIEW monthly_sales_summary AS
SELECT
    DATE_TRUNC('month', order_date) AS sales_month,
    SUM(total_amount) AS total_sales,
    COUNT(id) AS total_orders
FROM orders
GROUP BY 1
ORDER BY 1;

Refreshing Materialized Views

Since materialized views store a snapshot, their data doesn't automatically update when the underlying tables change. You must manually refresh them using the REFRESH MATERIALIZED VIEW command.

  • REFRESH MATERIALIZED VIEW view_name;: Locks the view during refresh.
  • REFRESH MATERIALIZED VIEW CONCURRENTLY view_name;: Allows concurrent reads during refresh (requires unique index on view).
REFRESH MATERIALIZED VIEW monthly_sales_summary;

-- For large views, consider concurrent refresh (if a unique index exists on the MV)
-- CREATE UNIQUE INDEX ON monthly_sales_summary (sales_month);
-- REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_sales_summary;

Query Performance Check

Let's check your understanding of PostgreSQL query optimization tools.

Recap: Optimize for Speed

In this lesson, we explored how to optimize your database queries for better performance and scalability.

  • You learned to use EXPLAIN and EXPLAIN ANALYZE to understand and profile query execution plans.
  • We discussed strategies for rewriting suboptimal queries, like using UNION ALL over OR.
  • You discovered Materialized Views as a powerful tool for pre-computing and storing complex query results, and how to refresh them.

Keep practicing with these tools to make your applications faster and more efficient!

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

هل درس «استراتيجيات تحسين الاستعلامات» مجاني؟

نعم — نص درس «استراتيجيات تحسين الاستعلامات» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة NestJS Enterprise Backend APIs، انتقل إلى CoddyKit PRO. تتضمن دورة NestJS Enterprise Backend APIs 6 دروس في المجموع.

ماذا ستتعلم في «استراتيجيات تحسين الاستعلامات»؟

تعمّق في تقنيات تحسين الاستعلامات المتقدمة، بما في ذلك تحليل خطط التنفيذ، وإعادة كتابة الاستعلامات، واستخدام العروض المادية تتمرن على NestJS Enterprise Backend APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ NestJS Enterprise Backend APIs؟

لا تُشترط خبرة سابقة. NestJS Enterprise Backend APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 6.

كم من الوقت يستغرق درس «استراتيجيات تحسين الاستعلامات»؟

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

هل يمكنني كتابة وتشغيل أكواد في درس NestJS Enterprise Backend APIs هذا؟

نعم. كل درس في NestJS Enterprise Backend APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

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

  1. استراتيجيات التخزين المؤقت (Redis)
  2. مراقبة أداء قاعدة البيانات
  3. موازنة التحميل والوكلاء
  4. استراتيجيات تحسين الاستعلامات
  5. النشر دون خوادم
  6. توسيع نطاق مشروع Supabase
← العودة إلى NestJS Enterprise Backend APIs