Magicsheet logo

Order Two Columns Independently

Medium
85.5%
Updated 6/1/2025

Asked by 2 Companies

Topics

Order Two Columns Independently

What is this problem about?

The Order Two Columns Independently SQL problem asks you to return two columns from a table sorted independently — column A in ascending order and column B in descending order — without their values being linked to their original row. This is a row_number trick problem where you detach the pairing and re-pair based on independent rankings.

Why is this asked in interviews?

Booking.com asks this to test window functions — specifically, using ROW_NUMBER() to create independent sorted orderings for two columns. It requires understanding that you must first assign independent row numbers to each sorted column, then join on row number to create the "independently sorted" result.

Algorithmic pattern used

ROW_NUMBER() with independent sorting + JOIN. For column A: SELECT ROW_NUMBER() OVER (ORDER BY A ASC) AS rn, A FROM table. For column B: SELECT ROW_NUMBER() OVER (ORDER BY B DESC) AS rn, B FROM table. Join both CTEs on rn to get independently sorted columns.

Example explanation

Table: A=[3,1,2], B=[5,1,3]. A sorted ASC: [1,2,3] with rn=[1,2,3]. B sorted DESC: [5,3,1] with rn=[1,2,3]. Join on rn: [(1,5),(2,3),(3,1)]. Output: A=[1,2,3], B=[5,3,1] independently sorted.

Common mistakes candidates make

  • Sorting both columns together (creates correlated pairs, not independent sorts).
  • Using ORDER BY without ROW_NUMBER (doesn't separate the ranking from the values).
  • Joining on the wrong condition.
  • Missing that "independent" means row pairings from the original table are broken.

Interview preparation tip

Independent column sorting requires decoupling the columns using ROW_NUMBER(). This window function pattern appears in "rank items in two categories independently," "display parallel rankings," and "reorder columns independently." The join-on-row-number technique is the standard tool. Practice window function problems involving ROW_NUMBER, RANK, and DENSE_RANK for ordering and pairing tasks.

Similar Questions