Query
Query
my previous explanation focused more on what each part does rather than the thought
process behind constructing them. My apologies for that oversight!
Let's shift gears and focus on the thought process and logic behind writing SQL queries,
broken down into a step-by-step approach. We'll build up from simple questions to more
complex ones, always focusing on how you'd think about getting the answer from your data.
Imagine you're talking to a very diligent, but very literal, assistant who only understands SQL.
You need to give them precise instructions.
1. Students Table:
2. Courses Table:
Putting it together:
SQL
| Name | Age |
| :------ | :-- |
| Alice | 20 |
| Bob | 22 |
| Charlie | 19 |
| David | 21 |
| Eve | 20 |
| Frank | 23 |
Putting it together:
SQL
SELECT Name
FROM Students
WHERE Major = 'Computer Science';
Result:
Name
Alice
David
Putting it together:
SQL
SELECT
Major,
COUNT(*) AS NumberOfStudents,
AVG(GPA) AS AverageGPA
FROM Students
GROUP BY Major
ORDER BY NumberOfStudents DESC;
Result:
Arts 2 3.45
Engineering 2 3.45
Scenario 4: Filtering Groups (HAVING clause)
Question: "Show me only the majors that have more than 1 student." (This builds on Scenario
3).
● Step 1, 2, 3, 4 (Same as Scenario 3):
○ SELECT Major, COUNT(*) AS NumberOfStudents, AVG(GPA) AS AverageGPA
○ FROM Students
○ (No WHERE for individual rows)
○ GROUP BY Major
● New Step: Filtering after grouping. I need to filter the groups based on the COUNT(*)
which is an aggregate. You cannot use WHERE with aggregate functions. For filtering
groups, you use HAVING.
○ SQL thought: HAVING COUNT(*) > 1
● Step 5: ORDER BY NumberOfStudents DESC (still want this).
Putting it together:
SQL
SELECT
Major,
COUNT(*) AS NumberOfStudents,
AVG(GPA) AS AverageGPA
FROM Students
GROUP BY Major
HAVING COUNT(*) > 1 -- This filters the groups *after* they are formed
ORDER BY NumberOfStudents DESC;
Result: (In our small dataset, all majors have 2 students, so the result is the same as Scenario
3, but imagine if a major only had 1 student, it would be excluded here).
Arts 2 3.45
Putting it together:
SQL
Result:
Name CourseName
Bob Mechanics
Eve Mechanics
Putting it together:
SQL
SELECT S.Name, C.CourseName
FROM Students S
LEFT JOIN Courses C ON S.StudentID = C.StudentID;
Name CourseName
Alice Algorithms
Bob Mechanics
Eve Mechanics
Zoe NULL
Putting it together:
SQL
SELECT Name
FROM Students
WHERE GPA > (SELECT AVG(GPA) FROM Students);
Result:
Name
Alice
Charlie
Eve
Putting it together:
SQL
SELECT S.Name
FROM Students S
WHERE EXISTS (
SELECT 1
FROM Courses C
WHERE C.StudentID = S.StudentID -- This connects the inner query to the current row of the
outer query
AND C.Credits = 4
);
Result:
Name
Bob
David
Eve
Don't be afraid to break down a complex question into smaller, simpler ones. SQL often
mirrors that logical thought process.