r/learnSQL • u/DrUstela • Mar 24 '26
Need Help :( stuck in loop
Okay so I can understand syntax and can write code at intermediate level if provided with a hint like which table to look at , what to join,but without hint i can't logically think of the connection especially in sub query , case etc when slightly complicated questions are asked. I tried writing on paper and decoding,still struggled a lot .Any suggestions how to improve my logical reasoning. Sorry I'm from a non tech role , trying hard to learn this stuff thx .
7
Upvotes
View all comments
Show parent comment
1
u/tlefst Mar 25 '26
The query processing order is the most important part.
Every stage (i.e. FROM, WHERE, GROUP BY, etc.) takes a table as input, does something with it, and sends it to the next stage.
Then, the next stage takes THAT table as input and the cycle repeats. Obviously, FROM starts with the original table (or JOINed tables if a JOIN is happening).
Once you'll learn the simpler Common Table Expressions (CTE), you will not have to bother about sub-queries but before that, you need to understand why sub-queries are good to know when the table is small and some intermediate result is needed through a quick calculation.
Suppose there are two tables
employees(empID, empName, salary, deptID)anddepartment(deptID, deptName).When asked find all employee IDs who are earning salary more than the average salary of 'sales' department, you can notice that the columns to seek are
empID, salary, deptID, deptName.So locate the tables in which they are present, find which column(s) are common between the tables (
deptIDhere in our case), join the tables on the common column(s), filtersalesrows, findAVG(salary), and finally find allempIDwhosesalary > AVG(salary).Keep practicing and reading queries, & you'll get faster at recognizing which column is in which table, and which columns in the tables are common.