Interview Q&A / PostgreSQL

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How is a window function different from GROUP BY?

SHORT ANSWER

GROUP BY collapses rows into one row per group. A window function computes over a related set of rows but keeps every original row, so you can show a row's value beside its group's total or its rank.

Explain it simply

A class teacher can announce only the section average (GROUP BY: one line per section), or can write each student's marks plus the section average next to them (window function: every student still has a line). The window does not remove rows; it adds a computed column.

OVER (PARTITION BY ...) defines the group each row looks at.

Example

sql
SELECT name, dept, salary,
       avg(salary) OVER (PARTITION BY dept)             AS dept_avg,
       salary - avg(salary) OVER (PARTITION BY dept)    AS diff_from_avg
FROM employees;

--  name  | dept | salary | dept_avg | diff_from_avg
--  Asha  | IT   | 60000  | 55000    |  5000
--  Rohit | IT   | 50000  | 55000    | -5000
--  Meera | HR   | 40000  | 40000    |     0

SELECT dept, avg(salary)
FROM employees
GROUP BY dept;                  -- one row per dept only

Window functions run after WHERE, GROUP BY and HAVING, so you cannot filter on them directly in WHERE; wrap the query in a subquery or CTE.

What to say in the interview

"GROUP BY reduces to one row per group, while window functions keep all rows and add a value computed over a partition. They are evaluated after WHERE and GROUP BY, so to filter by a window result I use a subquery or CTE."

Common mistakes

  • Writing WHERE rank = 1 in the same query level as the window function.

#postgresql#window-functions#aggregation

Related questions

Practise more PostgreSQL questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open PostgreSQL quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.