0
0
PostgreSQLquery~5 mins

Practical window function patterns in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the ROW_NUMBER() window function do?
It assigns a unique sequential number to each row within a partition of the result set, starting at 1 for the first row.
Click to reveal answer
intermediate
How does RANK() differ from ROW_NUMBER() in window functions?
RANK() assigns the same rank to rows with identical values, causing gaps in ranking numbers, while ROW_NUMBER() always assigns unique sequential numbers without gaps.
Click to reveal answer
beginner
Explain the use of the PARTITION BY clause in window functions.
PARTITION BY divides the result set into groups (partitions) and the window function is applied independently within each group.
Click to reveal answer
beginner
What is the purpose of the ORDER BY clause inside a window function?
ORDER BY defines the order of rows within each partition for the window function to process, affecting functions like ROW_NUMBER(), RANK(), and cumulative sums.
Click to reveal answer
intermediate
How can you calculate a running total using window functions?
Use SUM() as a window function with ORDER BY to accumulate values row by row, for example: SUM(amount) OVER (ORDER BY date ROWS UNBOUNDED PRECEDING).
Click to reveal answer
Which window function assigns unique sequential numbers to rows within a partition?
ARANK()
BDENSE_RANK()
CROW_NUMBER()
DCOUNT()
What does PARTITION BY do in a window function?
AFilters rows before window function runs
BGroups rows so the window function runs separately on each group
CSorts rows globally
DLimits the number of rows returned
Which window function will assign the same rank to tied rows but skip ranks after ties?
ARANK()
BDENSE_RANK()
CROW_NUMBER()
DNTILE()
How do you calculate a running total of sales ordered by date?
ASUM(sales) OVER (ORDER BY date ROWS UNBOUNDED PRECEDING)
BSUM(sales)
CCOUNT(sales) OVER (PARTITION BY date)
DAVG(sales) OVER (ORDER BY date)
What happens if you omit ORDER BY in a window function like ROW_NUMBER()?
ARows are numbered randomly
BRows are numbered in insertion order
CAn error occurs
DRows are numbered but order is not guaranteed
Describe how to use window functions to rank employees by salary within each department.
Think about grouping by department and ordering salaries to assign ranks.
You got /3 concepts.
    Explain how to compute a running total of sales over time using window functions.
    Running totals accumulate values in order.
    You got /3 concepts.