Window Functions · Question 12 · Medium

A table Scores(player, team, runs) is given. Why is the following query rejected?

SELECT player
FROM Scores
WHERE ROW_NUMBER() OVER (PARTITION BY team
                         ORDER BY runs DESC) = 1;
  1. ROW_NUMBER() cannot be combined with PARTITION BY
  2. ROW_NUMBER() needs GROUP BY team in the same query
  3. A window function may appear only in ORDER BY, never in a condition or the SELECT list
  4. Window functions are computed after WHERE, so they cannot be used in WHERE; compute it in a subquery or CTE and filter outside
Answer and explanation

Answer: D. Window functions are computed after WHERE, so they cannot be used in WHERE; compute it in a subquery or CTE and filter outside

Explanation: Window functions are evaluated after WHERE, GROUP BY and HAVING, so they are allowed only in the SELECT list and ORDER BY. To filter on one, give it an alias in an inner query and test the alias in the outer WHERE.

Previous: Table Scores: player | team | runs Arjun | Royals | 82 Bhuvan | Royals | 82… · Next: Table Scores: player | team | runs Arjun | Royals | 82 Bhuvan | Royals | 82…

Practise window functions

Try a fresh set of window functions questions with an explanation after every answer, free and without signing up: Window Functions practice. Or sit a full placement mock test.

More window functions questions

More sql practice

NULL Handling · SQL Functions & CASE · UNION, INTERSECT & EXCEPT · Tables, Keys & Constraints · DML & Transactions · SELECT, WHERE & ORDER BY · SQL Joins · Aggregates & GROUP BY

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge