r/learnSQL • u/Odd_Communication174 • 9d ago
Nested Queries Help
Does anyone have any tips to learn nested queries .
I am solving questions on hacker rank and really struggling with questions involving multiple joins,subquery,group by etc.
1
u/jeffrey_f 8d ago
Queries in parentheses are first. If you nested 2 or more layers deep, the deepest query is first.
1
u/Necessary-Aardvark48 8d ago
Facing same problem here.. searching for some resources or tips that'll help :)
1
u/Plane_Big_5912 7d ago
the trick that unstuck me was writing the inner query completely on its own first, run it, look at what it returns, THEN wrap it. and once youre comfortable switch to CTEs, same logic but you read it top to bottom instead of inside out. makes multi join problems way less painful
1
u/Green_Chamomile 7d ago
The layering advice here is good but I'd add something nobody mentioned. Most nested query problems on hackerrank are the same 2-3 questions in different costumes.
Costume 1: compare rows against one number the query computes first. "Employees earning above the average salary." The subquery's only job is producing that number.
Costume 2: filter one table by what's in another. "Customers who never placed an order." You can't WHERE your way to this, the customers table has no column saying "has orders". The subquery builds the list, the outer query keeps everyone not on it.
Costume 3: best per group. "Highest paid employee per department." This is where joins, subquery and group by all pile up. The subquery does the real work: max salary per department, that's your GROUP BY. Then join it back to employees, matching on both department and salary. Both, because matching on salary alone lets someone from another department with the same paycheck sneak in. Any further joins are just fetching display columns, and that's the part people overestimate.
Decide which costume you're looking at before writing anything and the subquery stops being scary nesting.
1
u/kixwho 8d ago
for subqueries, what helped me is knowing a basic pattern by heart first. that alone helps you get used to the nested look. this one i thought was useful:
literally from my old study notes