Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top 5 Products SQL Query

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

Your question is Top 5 Products SQL Query. Start with the requirements and the three tables 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

Jerry wants to identify the products generating the most sales on its customer and policy surfaces. Write a PostgreSQL query that returns the top five products by sales during the rolling 12-month period ending today.

Requirements

  1. Include only orders with status = 'completed'.
  2. Include orders from CURRENT_DATE - INTERVAL '1 year' through CURRENT_DATE.
  3. Calculate sales as quantity * unit_price, treating a missing unit price as zero.
  4. Return product name and total sales, sorted from highest to lowest. Break ties by product_id ascending.

Schema

products
ColumnTypeDescription
product_idPKINTUnique product identifier
product_nameVARCHAR(100)Jerry product name
orders
ColumnTypeDescription
order_idPKINTUnique order identifier
order_dateDATEDate the order was placed
statusVARCHAR(20)Order lifecycle status
order_items
ColumnTypeDescription
order_item_idPKINTUnique order-line identifier
order_idINTReferences orders.order_id
product_idINTReferences products.product_id
quantityINTNumber of units purchased
unit_priceNUMERIC(10,2)Price per unit at checkout
Tablesproductsordersorder_items
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results