It's hard to explain a window function with words. And you know me, I like giving examples, they always make more sense.
Let's say we have this table called employee_salary that have all these values:
| Name | Job Title | Salary |
|---|---|---|
| Alice | Data Analyst | 70,000 |
| Bob | Data Scientist | 90,000 |
| Charlie | Product Manager | 85,000 |
| David | Data Analyst | 75,000 |
| Eva | Data Scientist | 95,000 |
| Frank | Product Manager | 80,000 |
| Grace | Data Analyst | 72,000 |
And I ask you to get me the total salary for each job title. You will use a group by and I know how good you are now at doing this:
SELECT
job_title,
SUM(salary) AS total_salary
FROM employee_salary
GROUP BY 1;
And this is the result you will get:
| Job Title | Total Salary |
|---|---|
| Data Analyst | 217,000 |
| Data Scientist | 185,000 |
| Product Manager | 165,000 |
But what if I want for each row of that employee_salary the total salary across each job title. Basically, something like that:
| Name | Job Title | Salary | Total Salary |
|---|---|---|---|
| Alice | Data Analyst | 70,000 | 217,000 |
| Bob | Data Scientist | 90,000 | 185,000 |
| Charlie | Product Manager | 85,000 | 165,000 |
| David | Data Analyst | 75,000 | 217,000 |
See, for the first row, Alice salary is 217k. How the heck am I able to do that for each single row of that table?
Well, you can do that using Window function and get some cool metrics, like what % Alice's salary represents compared to all employees in the same role.

Well, alright! I'll show you how it will look in SQL:
SELECT
job_title,
SUM(salary) AS total_salary,
SUM(total_salary) OVER (PARTITION BY job_title) AS total_salary_per_title
FROM employee_salary
GROUP BY 1;
I didn't want you to freak out! But a window function can go across the whole table and sum the whole thing. You just need to specify it! Here we are go over the whole table and SUMMING everything but only for each job title that row belongs to.
That's why I am using PARTITION BY. If you want to sum the whole salary across the whole table, you can just remove that.
SELECT
job_title,
SUM(salary) AS total_salary,
SUM(total_salary) OVER () AS total_salary_over_everything
FROM employee_salary
GROUP BY 1;
I know it might not make much sense now! But don't worry, we will as always go over more examples so that it makes sense.
See you in the next lesson!
| Eva | Data Scientist | 95,000 | 185,000 |
| Frank | Product Manager | 80,000 | 165,000 |
| Grace | Data Analyst | 72,000 | 217,000 |