Consider a table sales with columns id, employee, and amount. The data is:
id | employee | amount ---+----------+------- 1 | Alice | 100 2 | Bob | 200 3 | Alice | 200 4 | Bob | 200 5 | Carol | 300
What is the output of this query?
SELECT employee, amount, ROW_NUMBER() OVER (PARTITION BY amount ORDER BY employee) AS rn FROM sales ORDER BY amount, employee;
SELECT employee, amount, ROW_NUMBER() OVER (PARTITION BY amount ORDER BY employee) AS rn FROM sales ORDER BY amount, employee;
ROW_NUMBER assigns a unique number to each row within the partition, ordered by the specified column.
ROW_NUMBER() restarts numbering for each amount group and orders by employee. For amount=200, Alice is first (rn=1), Bob is second (rn=2), and the second Bob is third (rn=3) because there are two rows with Bob and amount=200.
Using the same sales table, what is the output of this query?
SELECT employee, amount, RANK() OVER (ORDER BY amount DESC) AS rnk FROM sales ORDER BY amount DESC, employee;
SELECT employee, amount, RANK() OVER (ORDER BY amount DESC) AS rnk FROM sales ORDER BY amount DESC, employee;
RANK() assigns the same rank to ties and skips ranks after ties.
Carol has the highest amount 300, so rank 1. Alice and Bob with amount 200 tie for rank 2. Because there are 3 rows with amount 200, the next rank after 2 is 5 (2 + 3). Alice with amount 100 gets rank 5.
Using the same sales table, what is the output of this query?
SELECT employee, amount, DENSE_RANK() OVER (ORDER BY amount DESC) AS drnk FROM sales ORDER BY amount DESC, employee;
SELECT employee, amount, DENSE_RANK() OVER (ORDER BY amount DESC) AS drnk FROM sales ORDER BY amount DESC, employee;
DENSE_RANK() assigns ranks without gaps after ties.
Carol has the highest amount 300, rank 1. Alice and Bob with amount 200 tie for rank 2. Unlike RANK(), DENSE_RANK() does not skip ranks, so the next rank after 2 is 3 for amount 100.
You want to assign a rank to sales amounts where ties get the same rank and the next rank number should not skip any numbers. Which function should you use?
Think about which function assigns ranks without gaps after ties.
DENSE_RANK() assigns the same rank to ties and does not skip rank numbers after ties, unlike RANK(). ROW_NUMBER() assigns unique numbers even for ties.
Which option contains a syntax error in this window function query?
SELECT employee, amount, RANK() OVER PARTITION BY amount ORDER BY employee) AS rnk FROM sales;
Check the parentheses and placement of the OVER clause.
Option A is missing parentheses around the OVER clause, causing a syntax error. The correct syntax requires parentheses enclosing PARTITION BY and ORDER BY inside OVER().