Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Start free
SQL Window Function Ranking
00:00
5 left

SQL Window Function Ranking

EasySQL · PostgreSQL

Problem

A company wants to identify the highest-value customers in each sales region. Write a SQL query to rank customers by their total revenue within each region.

Requirements

  1. Aggregate revenue per region and customer_id.
  2. Rank customers within each region by total revenue, highest first.
  3. Use a window function to assign the rank.
  4. Return only customers with at least one completed order.

Output details

  • Return region_name, customer_id, customer_name, total_revenue, and revenue_rank, in that order.
  • Order rows by region_name ascending, then revenue_rank ascending, then customer_id ascending.
  • Break equal total-revenue ties by customer_id ascending.

Schema

regions
ColumnTypeDescription
region_idPKINTPrimary key for the region
region_nameVARCHAR(100)Region name
customers
ColumnTypeDescription
customer_idPKINTPrimary key for the customer
customer_nameVARCHAR(100)Customer name
region_idINTRegion assigned to the customer
orders
ColumnTypeDescription
order_idPKINTPrimary key for the order
customer_idINTCustomer who placed the order
order_statusVARCHAR(20)Order status, such as completed or cancelled
order_amountDECIMAL(10,2)Revenue from the order
order_dateDATEOrder date
Tablesregionscustomersorders
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements and the three tables are in the Question tab.

Sign up free to run or submit. Log in
CodePostgreSQL
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 1
Run your query to see results here.