0
0
PostgreSQLquery~5 mins

PARTITION BY for grouping windows in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the PARTITION BY clause do in a window function?
It divides the rows into groups (partitions) so the window function is applied separately to each group, similar to grouping but without collapsing rows.
Click to reveal answer
beginner
How is PARTITION BY different from GROUP BY?
GROUP BY collapses rows into one row per group, while PARTITION BY keeps all rows but calculates window functions within each group.
Click to reveal answer
intermediate
Write a simple example of a window function using PARTITION BY.
Example: <br>SELECT department, employee, salary, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank FROM employees;<br>This ranks employees by salary within each department.
Click to reveal answer
intermediate
Can you use multiple columns in PARTITION BY? How?
Yes, separate columns by commas. For example: PARTITION BY department, job_title groups rows by both department and job title.
Click to reveal answer
beginner
What happens if you omit PARTITION BY in a window function?
The window function treats all rows as a single group and calculates over the entire result set.
Click to reveal answer
What is the main purpose of PARTITION BY in window functions?
ATo group rows and collapse them into one row per group
BTo sort rows in the entire table
CTo filter rows before aggregation
DTo divide rows into groups for separate window calculations without collapsing rows
Which of the following is a valid use of PARTITION BY?
ASELECT employee, RANK() OVER (PARTITION BY department ORDER BY salary DESC) FROM employees;
BSELECT * FROM employees WHERE PARTITION BY department;
CSELECT * FROM employees GROUP BY department PARTITION BY salary;
DSELECT SUM(salary) FROM employees PARTITION BY department;
If you want to rank employees by salary within each department and job title, how do you write the PARTITION BY clause?
APARTITION BY department, job_title
BPARTITION BY department ORDER BY job_title
CPARTITION BY salary
DPARTITION BY department AND job_title
What will happen if you omit PARTITION BY in a window function?
AThe window function will calculate separately for each row
BThe query will fail with an error
CThe window function will calculate over the entire result set as one group
DThe window function will ignore ordering
Which SQL clause is similar in concept to PARTITION BY but collapses rows?
AORDER BY
BGROUP BY
CWHERE
DHAVING
Explain in your own words how PARTITION BY works in window functions and how it differs from GROUP BY.
Think about how results look with and without grouping.
You got /4 concepts.
    Describe a real-life example where using PARTITION BY in a window function would be helpful.
    Consider ranking employees by department or calculating running sales totals per region.
    You got /3 concepts.