Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Optimize SQL for Large Datasets

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

Your question is Optimize SQL for Large Datasets. Start with the requirements and the four 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

Business Context

Microsoft Teams analytics needs a weekly engagement report across active workspaces. The source tables contain millions of messages and reactions, so the query must reduce data before expensive joins and window calculations.

Task

Write an optimized PostgreSQL query for messages sent from 2025-01-01 through 2025-02-28. Return weekly metrics for active Teams workspaces and retain weeks with at least two qualifying messages.

Requirements

  1. Filter deleted messages, non-standard messages, inactive workspaces, and inactive authors before aggregation.
  2. Pre-aggregate reactions by message to avoid multiplying message rows during joins.
  3. Calculate message count, distinct active authors, total reactions, and reactions per message.
  4. Use LAG to show the previous observed week's message count and percentage change.
  5. Return only weeks with at least two messages, ordered by workspace and week.

Schema

teams
ColumnTypeDescription
team_idPKINTMicrosoft Teams workspace identifier
team_nameVARCHAR(100)Workspace name
statusVARCHAR(20)Workspace lifecycle status
users
ColumnTypeDescription
user_idPKINTMicrosoft Entra user identifier
display_nameVARCHAR(100)User display name
account_statusVARCHAR(20)User account status
channel_messages
ColumnTypeDescription
message_idPKBIGINTChannel message identifier
team_idINTReferences teams.team_id
author_idINTReferences users.user_id
sent_atTIMESTAMPMessage creation timestamp
is_deletedBOOLEANWhether the message was deleted
message_typeVARCHAR(30)Message classification
message_reactions
ColumnTypeDescription
reaction_idPKBIGINTReaction identifier
message_idBIGINTReferences channel_messages.message_id
user_idINTUser who added the reaction
reaction_typeVARCHAR(30)Reaction category
Tablesteamsuserschannel_messagesmessage_reactions
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results