Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Reverse Rows in a DataFrame

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

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

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
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results