HackerRank SQL

Isabelle
JEN-LI CHEN IN DATA SCIENCE
2 min readJul 25, 2020

Placements

Problem:

You are given three tables: Students, Friends and Packages. Students contains two columns: ID and Name. Friends contains two columns: ID and Friend_ID (ID of the ONLY best friend). Packages contains two columns: ID and Salary (offered salary in $ thousands per month).

Write a query to output the names of those students whose best friends got offered a higher salary than them. Names must be ordered by the salary amount offered to the best friends. It is guaranteed that no two students got same salary offer.

Sample Input

Sample Output

Samantha
Julia
Scarlet

Explanation

See the following table:

Now,

  • Samantha’s best friend got offered a higher salary than her at 11.55
  • Julia’s best friend got offered a higher salary than her at 12.12
  • Scarlet’s best friend got offered a higher salary than her at 15.2
  • Ashley’s best friend did NOT get offered a higher salary than her

The name output, when ordered by the salary offered to their friends, will be:

  • Samantha
  • Julia
  • Scarlet

Logic:

Firstly, select name from Students, and then join with Friends table to get their corresponding Friend_ID, and then join with Packages table to get each ID’s salary, and then join with Packages table again to get Friends’ salary. Lastly, filter by Friends’ Salary greater than each ID’s salary and then order by Friends’ salary.

Solution:

select Name from Students as s
join Friends as f
on s.ID = f.ID
join Packages as p
on p.ID = s.ID
join Packages as fp
on fp.ID = f.Friend_ID
where p.Salary < fp.Salary
order by fp.Salary;

Link

Inspiration

--

--