Phases of sql query
FROM & JOIN Phase
-
The DBMS starts by looking at the
FROM users u
table. -
It then performs a LEFT JOIN with
borrows b
:-
For each row in
users
, it tries to find matching rows inborrows
whereu.id = b.user_id
. -
If a user has no borrows, that user still appears, but with
NULL
inb.*
.
-
👉 At this stage, we have a wide table with
u.id, u.name, b.id, b.issued_date, b.status
.-
-
WHERE Filtering
-
If you had a
WHERE
clause, it would be applied here, filtering individual rows before grouping. -
Since we’re not using
WHERE
, all rows pass through.
-
-
GROUP BY Phase
-
Rows are grouped by
u.id, u.name
. -
Each group corresponds to one user.
-
Example: If user #5 has 3 borrow rows, those rows are grouped into a single "bucket."
-
-
Aggregate Functions (COUNT)
-
For each group (each user),
COUNT(b.id)
is calculated. -
Important:
COUNT(b.id)
counts only non-NULL values.-
If a user has no borrows,
b.id
isNULL
→ count becomes0
.
-
-
-
HAVING Filtering
-
Now the engine applies
HAVING COUNT(b.id) > 0
. -
This removes users with no borrowings (where the count = 0).
-
Difference from
WHERE
:-
WHERE
filters before grouping, -
HAVING
filters after grouping/aggregation.
-
-
-
SELECT Phase
-
Only the grouped columns (
u.id
,u.name
) and the aggregated column (total_borrows
) are output. -
You cannot select columns that are not in the
GROUP BY
or in an aggregate.
-
-
ORDER BY Phase
-
Finally, the result set is sorted by
total_borrows
in descending order. -
So the users with the most borrowings appear first.
-
Comments
Post a Comment
What is your thought about this?