HomeInterview QuestionsExplain the following PostgreSQL query that finds …

Explain the following PostgreSQL query that finds the longest streak per player.

🟡 Medium Conceptual Mid level
1Times asked
Aug 2026Last seen
Aug 2026First seen

💡 Model Answer

The query calculates the longest consecutive streak of a particular result (e.g., wins) for each player. The innermost subquery assigns two row numbers: one partitioned by player_id and ordered by match_date, and another partitioned by both player_id and result. Subtracting these two row numbers yields a constant value (grp) for consecutive rows that share the same result, effectively grouping streaks. The middle subquery then counts the number of rows in each group, giving the streak length (streak_len). Finally, the outer query selects the maximum streak_len per player_id, returning the longest streak. The overall time complexity is O(n) with respect to the number of match rows, as each window function scans the data once. This pattern is a classic technique for detecting consecutive sequences in SQL without procedural code.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500