0Pricing
PostgreSQL Performance & Query Optimization · Ders

Toplamaları ve pencere işlevlerini iyileştirme

Karmaşık toplamaları ve pencere işlevlerini verimli bir şekilde işlemeye yönelik teknikleri öğrenin.

Toplamaları ve pencere işlevlerini iyileştirme, CoddyKit'te ücretsiz bir PostgreSQL Performance & Query Optimization dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, PostgreSQL Performance & Query Optimization öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. PostgreSQL Performance & Query Optimization kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Aggregates & Windows Intro

Welcome to optimizing advanced queries! Today, we'll dive into making your aggregate and window functions run faster.

These powerful SQL features let you perform calculations across groups of rows or related rows. But, without care, they can become performance bottlenecks.

Aggregates Refresher

Aggregate functions summarize data for a group of rows, returning a single value per group. Common ones include COUNT(), SUM(), AVG(), MIN(), and MAX().

They often work with the GROUP BY clause to define these groups. Let's see a simple example:

SELECT
  category,
  COUNT(product_id) AS total_products
FROM
  products
GROUP BY
  category;

Window Functions Overview

Window functions also perform calculations across a set of table rows. However, unlike aggregates, they don't collapse rows. Instead, they return a result for each row in the original query.

They use an OVER() clause to define the 'window' of rows for the calculation. This window can be partitioned and ordered.

Optimizing Aggregates: Early Filtering

A key to fast aggregates is to process less data. Always filter your data as early as possible using the WHERE clause. This reduces the number of rows PostgreSQL needs to scan and group.

Consider this example where we only aggregate for 'Electronics':

SELECT
  category,
  AVG(price) AS avg_price
FROM
  products
WHERE
  category = 'Electronics'
GROUP BY
  category;

Optimizing Aggregates: Indexes for GROUP BY

Indexes can significantly speed up GROUP BY clauses. If an index exists on the column(s) used in GROUP BY, PostgreSQL can often use it to avoid sorting the entire dataset.

This is especially true for B-tree indexes, which store data in a sorted order.

CREATE INDEX idx_products_category
ON products (category);

Window Functions: PARTITION BY

The PARTITION BY clause within OVER() divides your dataset into independent groups, and the window function operates separately within each partition. Think of it like GROUP BY, but without collapsing rows.

Performance-wise, partitioning often involves sorting the data by the partition key(s), which can be resource-intensive for large datasets.

SELECT
  product_name,
  category,
  price,
  AVG(price) OVER (PARTITION BY category) AS avg_category_price
FROM
  products;

Window Functions: ORDER BY in Window

The ORDER BY clause inside OVER() defines the logical order of rows within each partition. This is crucial for ranking functions (like ROW_NUMBER()) and functions that depend on row order (like LAG(), LEAD()).

Just like with aggregates, this ordering step can be costly, especially if no suitable index exists to support the sort order.

SELECT
  product_name,
  category,
  price,
  ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rank_in_category
FROM
  products;

Window Frames: ROWS and RANGE

Beyond PARTITION BY and ORDER BY, you can define a specific window frame using ROWS or RANGE. This specifies which subset of rows within the current partition the function should consider.

  • ROWS: Based on a fixed number of rows relative to the current row.
  • RANGE: Based on a value range relative to the current row's value.

Using a smaller, more precise window frame (e.g., ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) often leads to better performance than larger, unbounded frames.

SELECT
  sale_date,
  amount,
  SUM(amount) OVER (
    ORDER BY sale_date
    ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
  ) AS three_day_moving_avg
FROM
  sales;

General Optimization Tips

Here are some general tips for both aggregates and window functions:

  • Use appropriate indexes: Especially on GROUP BY, PARTITION BY, and ORDER BY columns.
  • Minimize data: Filter early with WHERE clauses.
  • Avoid complex expressions: Calculations inside aggregates/windows can be slow. Pre-calculate if possible.
  • Understand data distribution: Skewed data can lead to uneven work distribution and slow partitions.

Quick Check: Optimizing Aggregates

You have a large orders table and want to find the total amount for orders placed in '2023-01' for each customer. Which approach is generally more performant?

Recap & Next Steps

Great job! You've learned how to approach optimizing both aggregate and window functions.

  • Filter data early for aggregates.
  • Use indexes on GROUP BY, PARTITION BY, and ORDER BY columns.
  • Be mindful of the cost of sorting for both aggregates and window functions.
  • Define precise window frames with ROWS/RANGE when possible.

Keep these techniques in mind to write faster, more efficient PostgreSQL queries!

Sıkça Sorulan Sorular

“Toplamaları ve pencere işlevlerini iyileştirme” dersi ücretsiz mi?

Evet — “Toplamaları ve pencere işlevlerini iyileştirme” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve PostgreSQL Performance & Query Optimization kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. PostgreSQL Performance & Query Optimization kursu toplamda 4 dersten oluşur.

“Toplamaları ve pencere işlevlerini iyileştirme” dersinde ne öğreneceğim?

Karmaşık toplamaları ve pencere işlevlerini verimli bir şekilde işlemeye yönelik teknikleri öğrenin. PostgreSQL Performance & Query Optimization ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

PostgreSQL Performance & Query Optimization öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te PostgreSQL Performance & Query Optimization, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.

“Toplamaları ve pencere işlevlerini iyileştirme” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu PostgreSQL Performance & Query Optimization dersinde kod yazıp çalıştırabilir miyim?

Evet. Her PostgreSQL Performance & Query Optimization dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Toplamaları ve pencere işlevlerini iyileştirme
  2. Özyinelemeli CTE'ler ve grafik sorguları
  3. Performans için gerçekleştirilmiş görünümleri kullanma
  4. FILTER ve Koşullu Birleştirmeyle Sorguları İyileştirme
← PostgreSQL Performance & Query Optimization Sayfasına Dön