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
Get started
SQL Bottleneck Refactoring
00:00
5 left

SQL Bottleneck Refactoring

HardSQL · PostgreSQL

Problem

Identify potential bottlenecks in a provided database query and suggest refactoring strategies.

Review the following query, then provide a refactored PostgreSQL query that preserves its intended result while addressing inefficient filtering, repeated calculations, duplicate rows, and aggregation.

SELECT DISTINCT
    c.customer_id,
    c.customer_name,
    TO_CHAR(o.order_date, 'YYYY-MM') AS order_month,
    (
        SELECT SUM(oi2.quantity * oi2.unit_price)
        FROM order_items oi2
        WHERE oi2.order_id = o.order_id
    ) AS order_revenue
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE c.segment = 'Enterprise'
  AND TO_CHAR(o.order_date, 'YYYY-MM') BETWEEN '2024-01' AND '2024-03'
ORDER BY c.customer_id, order_month;

Output

  1. One row per Enterprise customer and calendar month with orders in the inclusive January through March 2024 period.
  2. Columns: customer_id, customer_name, order_month, order_count, and total_revenue.
  3. Sort by customer_id, then order_month ascending.

Schema

customers
ColumnTypeDescription
customer_idPKINTUnique customer identifier
customer_nameVARCHAR(100)Customer display name
segmentVARCHAR(30)Customer market segment
orders
ColumnTypeDescription
order_idPKINTUnique order identifier
customer_idINTCustomer who placed the order
order_dateTIMESTAMPTimestamp when the order was placed
statusVARCHAR(20)Order processing status
order_items
ColumnTypeDescription
order_item_idPKINTUnique order-line identifier
order_idINTOrder containing the item
quantityINTQuantity purchased
unit_priceNUMERIC(10,2)Price per item at purchase time
Tablescustomersordersorder_items
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.

You need to log in / sign up to run or submit.
CodePostgreSQL
Sign up free to run your codeLog inLn 1
Run your query to see results here.