Library › Data AI › Business analysts

Write SQL for the top 2 reps per region with ties

  • For Business analysts
  • You practice Setting limits and rules
  • Time about 5 minutes
  • Level Advanced

About this exercise

A sales ops manager wants the top 2 reps by closed-won revenue in each region for Q3 2025, and if two reps tie for 2nd place both should appear. Ask for one Postgres query in a single code block with at most 35 words outside it. Count only deals with stage 'Closed Won' closed between July 1 and September 30, 2025.

Common mistakes when you ask AI for this

  • Using ROW_NUMBER. It numbers rows 1, 2, 3 and drops a rep who tied for 2nd. Try: Add: "Use RANK() so ties for 2nd both appear."
  • Wrong deal filter. The AI counts every deal, including refunded or lost ones. Try: Add: "Closed Won, Q3 dates inclusive, is_refunded false."
  • Filtering rank in WHERE. Window functions can't be used in WHERE, so the query errors. Try: Add: "Compute revenue in a CTE, rank in a subquery, filter rank <= 2 outside."
  • Leaving the format to chance. The AI picks its own length and layout unless told the exact shape. Try: Add: "Put the code in exactly 1 code block. Keep the writing outside the code under 35 words."

What a strong prompt includes

  • Names the ranking function
  • Describes the deal filter
  • Says where to filter
  • Keeps departed reps
  • Limits the writing

Practice this now ↑

Related exercises