8. Aggregate Functions, Window Functions and Indexes
Part I: Aggregate Functions
Description
Aggregate functions perform a calculation on a set of rows and return a single row. They are often used with GROUP BY, which splits the result into groups so the calculation is done per group. Aggregates can be used as expressions only in the SELECT and HAVING clauses (a WHERE condition can use them only inside a subquery).
| Function | Returns |
|---|---|
AVG() | Average value |
COUNT() | Number of values/rows |
MAX() | Maximum value |
MIN() | Minimum value |
SUM() | Sum of all or distinct values |
AVG
SELECT AVG(amount) FROM payment;
SELECT AVG(DISTINCT amount)::numeric(10,2) FROM payment;
SELECT AVG(amount)::numeric(10,2), SUM(amount)::numeric(10,2) FROM payment;
-- Per customer, with HAVING
SELECT customer_id, first_name, last_name, AVG(amount)::NUMERIC(10,2)
FROM payment
INNER JOIN customer USING (customer_id)
GROUP BY customer_id
HAVING AVG(amount) > 5
ORDER BY customer_id;
NULL handling: AVG ignores NULLs. For values 10, NULL, 30 the average is 20, not 13.33.
COUNT
SELECT COUNT(*) FROM payment; -- all rows
SELECT customer_id, COUNT(customer_id)
FROM payment
GROUP BY customer_id
HAVING COUNT(customer_id) > 40;
COUNT(*) counts rows; COUNT(column) counts non-NULL values.
SUM
SELECT SUM(amount) AS total FROM payment WHERE customer_id = 2000;
SELECT customer_id, SUM(amount) AS total
FROM payment GROUP BY customer_id ORDER BY total;
SELECT SUM(return_date - rental_date) FROM rental; -- SUM over an expression
MAX and MIN
MAX can be used in SELECT, WHERE (via subquery) and HAVING. DISTINCT has no effect on MIN/MAX.
SELECT MAX(amount) FROM payment;
-- Rows with the highest amount
SELECT * FROM payment
WHERE amount = (SELECT MAX(amount) FROM payment);
-- Minimum per category
SELECT name AS category, MIN(replacement_cost) AS replacement_cost
FROM category
INNER JOIN film_category USING (category_id)
INNER JOIN film USING (film_id)
GROUP BY name
ORDER BY name;
Part II: Window Functions
Description
A window function performs a calculation across a set of rows related to the current row, without collapsing them into one row (unlike GROUP BY).
Sample tables used in the lecture:
CREATE TABLE product_groups (
group_id serial PRIMARY KEY,
group_name VARCHAR(255) NOT NULL
);
CREATE TABLE products (
product_id serial PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
price DECIMAL(11, 2),
group_id INT NOT NULL REFERENCES product_groups (group_id)
);
Grouping gives one row per group:
SELECT group_name, AVG(price)
FROM products INNER JOIN product_groups USING (group_id)
GROUP BY group_name;
A window function keeps every product row and shows the group average beside it:
SELECT product_name, price, group_name,
AVG(price) OVER (PARTITION BY group_name) AS group_avg
FROM products INNER JOIN product_groups USING (group_id);
Syntax
window_function(arg1, arg2, ...) OVER (
[PARTITION BY partition_expression]
[ORDER BY sort_expression [ASC | DESC] [NULLS {FIRST | LAST}]]
)
Ranking Functions
| Function | Behaviour |
|---|---|
ROW_NUMBER() | Sequential number for each row within the partition |
RANK() | Same rank for equal values; the following ranks are skipped (1, 1, 3) |
DENSE_RANK() | Same rank for equal values; no gaps (1, 1, 2) |
SELECT product_name, group_name, price,
ROW_NUMBER() OVER (PARTITION BY group_name ORDER BY price) AS rn,
RANK() OVER (PARTITION BY group_name ORDER BY price) AS rnk,
DENSE_RANK() OVER (PARTITION BY group_name ORDER BY price) AS drnk
FROM products INNER JOIN product_groups USING (group_id);
Value Functions
FIRST_VALUE(expr): value from the first row of the partition.LAST_VALUE(expr): value from the last row of the partition.
SELECT product_name, group_name, price,
FIRST_VALUE(price) OVER (PARTITION BY group_name ORDER BY price) AS lowest_price_per_group,
LAST_VALUE(price) OVER (PARTITION BY group_name ORDER BY price
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS highest_price_per_group
FROM products INNER JOIN product_groups USING (group_id);
Note: with
ORDER BY, the default window frame ends at the current row, soLAST_VALUEneeds the explicit frame shown above to return the true last value of the partition.
LAG and LEAD
LAG reads the previous row; LEAD reads the next row.
LAG (expression [, offset] [, default]) OVER (...)
LEAD (expression [, offset] [, default]) OVER (...)
offset: how many rows back/forward (default 1).default: value returned when the offset goes beyond the window (default NULL).
SELECT product_name, group_name, price,
LAG(price, 1) OVER (PARTITION BY group_name ORDER BY price) AS prev_price,
price - LAG(price, 1) OVER (PARTITION BY group_name ORDER BY price) AS cur_prev_diff,
LEAD(price, 1) OVER (PARTITION BY group_name ORDER BY price) AS next_price,
price - LEAD(price, 1) OVER (PARTITION BY group_name ORDER BY price) AS cur_next_diff
FROM products INNER JOIN product_groups USING (group_id);
Part III: Indexes
Description
An index is a common way to enhance performance. It lets the database find and retrieve specific rows much faster than scanning the whole table. Indexes also add overhead, so use them sensibly.
Analogy: the alphabetical index at the end of a non-fiction book. Readers scan the index and jump to the right pages instead of reading the whole book. The database designer must foresee which indexes will be useful.
Why They Help
Without an index, a query such as SELECT content FROM test1 WHERE id = constant; forces a sequential scan of every row. With an index on id, the system uses a more efficient lookup.
CREATE INDEX test1_id_index ON test1 (id);
DROP INDEX test1_id_index;
- Name the index so you remember what it is for.
- Indexes can be added and removed at any time.
- Once created, the system maintains the index automatically and uses it when it thinks that is faster than a sequential scan. Run
ANALYZEregularly so the query planner has up-to-date statistics. - Indexes also help
UPDATE/DELETEwith search conditions and join conditions. - Cost: the index must be kept in sync after every data change, so indexes that are seldom or never used should be removed.
Index Types
| Type | Best for |
|---|---|
| B-tree (default) | Equality and range queries (<, <=, =, >=, >) on sortable data; can return rows in sorted order |
| Hash | Simple equality comparisons (=) only |
| GiST | Infrastructure for many strategies (geometric data, full-text search); operators depend on the operator class (<<, &<, @>, <@, &&, ...) |
| SP-GiST | Space-partitioned structures (non-balanced trees) |
| GIN | Composite values such as arrays, JSONB and full-text search |
| BRIN | Very large tables where values correlate with physical row order |
CREATE INDEX idx_hash ON table_name USING HASH (column_name);
CREATE INDEX idx_gin ON table_name USING GIN (column_name);
Multicolumn Indexes
An index can cover more than one column (up to 32 by default).
CREATE TABLE test2 (major int, minor int, name varchar);
CREATE INDEX test2_mm_idx ON test2 (major, minor);
Useful for queries that filter on major and minor together.
Indexes and ORDER BY
- Only B-tree indexes can produce sorted output.
- By default, entries are stored ascending with NULLs last.
- Adjust with
ASC,DESC,NULLS FIRST,NULLS LAST:
CREATE INDEX test2_info_nulls_low ON test2 (info NULLS FIRST);
CREATE INDEX test3_desc_index ON test3 (id DESC NULLS LAST);
Unique Indexes
- Enforce uniqueness of a column or combination of columns. Currently only B-tree indexes can be unique.
- NULLs are not considered equal; a multicolumn unique index rejects only rows where all indexed columns are equal.
- PostgreSQL automatically creates a unique index for each
UNIQUEconstraint andPRIMARY KEY.
CREATE UNIQUE INDEX name ON table (column [, ...]);
Indexes on Expressions
An index column can be a function or scalar expression computed from columns, giving fast access based on computed results.
-- Case-insensitive search
SELECT * FROM test1 WHERE lower(col1) = 'value';
CREATE INDEX test1_lower_col1_idx ON test1 (lower(col1));
Practical Examples
- B-tree for flight search: index columns used in
WHERE(e.g., departure airport, date) so queries avoid a full table scan. - Show all indexes of a database:
SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = 'public'; - Show indexes of one table: add
AND tablename = 'table_name'(or\d table_nameinpsql). - Monitor index usage: query
pg_stat_user_indexes(columns such asidx_scan) to find indexes that are never scanned.
Conclusion
Aggregates summarize groups, window functions add per-row analytics without collapsing rows, and indexes speed up access at the cost of extra storage and write overhead.
All rights remain with the original author (Algo-holics). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me