Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
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
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess 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
Build my plan
Compare With Previous Row
00:00
5 left

Compare With Previous Row

MediumSQL · PostgreSQL

Problem

Write a SQL query using window functions to compare each row with the previous row in the same partition.

Use the observations table. Within each partition_key, rows are ordered by observed_at and then observation_id.

Output

  1. Return one row per observation with partition_key, observation_id, observed_at, metric_value, previous_metric_value, and difference_from_previous.
  2. The previous value and difference should be NULL when no previous row exists or either value needed for subtraction is NULL.
  3. Order the result by partition_key with NULL partitions last, then observed_at, and observation_id.

Schema

observations
ColumnTypeDescription
observation_idPKINTUnique observation identifier
partition_keyVARCHAR(50)Partition to which the observation belongs
observed_atTIMESTAMPTimestamp used to order observations
metric_valueDECIMAL(10,2)Observed numeric metric
Tablesobservations
Interviewer

Your question is Compare With Previous Row. Start with the requirements and the one table in the Question tab.

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.
CodePostgreSQL
Sign up free to run your codeLog inLn 1
Run your query to see results here.