# HackerRank: [SQL Advanced Join] (2/5) PLACEMENTS | inner join Students, Friends, Packages in SQL

I started studying SQL from a very famous site - HackerRank. Here I will try to provide multiple approaches & solutions to the same problem. It will help you learn and understand SQL in a better way.

Please make use of my blog posts for learning purpose only and feel free to ask your questions in the comment box below in case of any doubt.

Recommended SQL Courses:

SQL Problem Statement:

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:

`SamanthaJuliaScarlet`

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.

### Solution-1: Using INNER JOIN & SUB-QUERY (MySQL Query):

`SELECT t.NameFROM (    SELECT s1.ID, s1.Name, p1.Salary, f.Friend_ID, s2.name as friend_name, p2.Salary as friend_salary    FROM Students s1    JOIN Packages p1 ON s1.ID = p1.ID    JOIN Friends f ON s1.ID = f.ID    JOIN Students s2 ON f.Friend_ID = s2.ID    JOIN Packages p2 ON f.Friend_ID = p2.ID    ) tWHERE t.friend_salary > t.SalaryORDER BY friend_salary;`

NOTE:
1. Table s1 will give the ID and Name of the Students.

2. Table p1 will give Salary of the Student.

3. Table f will give Friend's ID.

4. Table s2 will give Friend's Name.

5. Table p2 will give Friend's Salary.

### Solution-2: Using INNER JOIN (MySQL Query):

`SELECT s.NameFROM Students sJOIN Packages p1 ON s.ID = p1.IDJOIN Friends f ON s.ID = f.IDJOIN Packages p2 ON f.Friend_ID = p2.IDWHERE p2.Salary > p1.SalaryORDER BY p2.Salary;`

NOTE:
1. Table p1 and p2 are used to compare student and friend's salary respectively.

### Expected Output:

`StuartPriyankaPaigeJaneJuliaBelvetAminaKristeenScarletPriyaMeera`

--------------------------------------------------------------------------------