Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

SQL Top-N Query

EasySQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is SQL Top-N Query. Start with the requirements and the one table on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Business context

Hitachi Energy wants a quick view of which products generate the most recorded sales. Use the product sales data to identify the five highest-selling products.

Task

Write a PostgreSQL query that calculates total sales for each product and returns the top five products.

Requirements

  1. Exclude rows where product_name is NULL because they cannot be attributed to a product.
  2. Group sales by product, calculate total sales, sort from highest to lowest, and return exactly five products. Break ties alphabetically by product name.

Schema

product_sales
ColumnTypeDescription
sale_idPKINTEGERUnique sale record identifier
product_nameVARCHAR(100)Hitachi Energy product name
sales_amountNUMERIC(12,2)Recorded sales amount
Tablesproduct_sales
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results