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
Reverse Rows in a DataFrame
00:00
5 left

Reverse Rows in a DataFrame

MediumSQL · PostgreSQL

Problem

Protium's analytics team receives repayment events in chronological order but sometimes needs to display each loan's event rows in reverse order for investigation. Write a PostgreSQL query that reverses the event sequence independently for every active loan.

Requirements

  1. Use a window function to establish each loan's chronological event order, using event_date and event_id as a deterministic tie-breaker.
  2. Return active loans, including active loans with no repayment events.
  3. Assign reversed_position = 1 to the latest event for each loan, and preserve the original event details.
  4. Order the final result by loan_id and reversed position, placing loans without events last within their loan ordering.

Output details

  • Return columns in this order: loan_id, reversed_position, original_event_id, event_type, event_date, and amount.
  • Sort loan_id and reversed_position in ascending order, placing NULL reversed_position values last.

Schema

loans
ColumnTypeDescription
loan_idPKINTEGERUnique Protium loan identifier
borrower_nameVARCHAR(100)Borrower's name
statusVARCHAR(20)Current loan status
repayment_events
ColumnTypeDescription
event_idPKINTEGERUnique repayment event identifier
loan_idINTEGERReferenced loan identifier
event_dateDATEDate the event was recorded
event_typeVARCHAR(30)Repayment event category
amountNUMERIC(10,2)Event amount, which may be NULL
Tablesloansrepayment_events
Interviewer

Your question is Reverse Rows in a DataFrame. Start with the requirements and the two tables 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.