Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
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.

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
You need to log in / sign up to run or submit.Ln 1
Run your query to see results here.