优化聚合与窗口函数
学习高效处理复杂聚合和窗口函数的技术。
优化聚合与窗口函数 是 CoddyKit 上的免费 PostgreSQL Performance & Query Optimization 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 PostgreSQL Performance & Query Optimization 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 PostgreSQL Performance & Query Optimization 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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, andORDER BYcolumns. - Minimize data: Filter early with
WHEREclauses. - 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, andORDER BYcolumns. - Be mindful of the cost of sorting for both aggregates and window functions.
- Define precise window frames with
ROWS/RANGEwhen possible.
Keep these techniques in mind to write faster, more efficient PostgreSQL queries!
常见问题解答
「优化聚合与窗口函数」课时是免费的吗?
是的 — 「优化聚合与窗口函数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 PostgreSQL Performance & Query Optimization 课程的其余内容,请升级到 CoddyKit PRO。 PostgreSQL Performance & Query Optimization 课程共包含 4 节课。
「优化聚合与窗口函数」这节课中我会学到什么?
学习高效处理复杂聚合和窗口函数的技术。 你通过在浏览器中直接运行的动手代码来练习 PostgreSQL Performance & Query Optimization,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 PostgreSQL Performance & Query Optimization 需要有经验吗?
无需任何先前经验。CoddyKit 上的 PostgreSQL Performance & Query Optimization 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「优化聚合与窗口函数」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 PostgreSQL Performance & Query Optimization 课中编写并运行代码吗?
能。每节 PostgreSQL Performance & Query Optimization 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。