Phases of sql query
FROM & JOIN Phase
-
The DBMS starts by looking at the
FROM users utable. -
It then performs a LEFT JOIN with
borrows b:-
For each row in
users, it tries to find matching rows inborrowswhereu.id = b.user_id. -
If a user has no borrows, that user still appears, but with
NULLinb.*.
-
👉 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
WHEREclause, 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.idisNULL→ 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:-
WHEREfilters before grouping, -
HAVINGfilters 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 BYor in an aggregate.
-
-
ORDER BY Phase
-
Finally, the result set is sorted by
total_borrowsin descending order. -
So the users with the most borrowings appear first.
-
Comments
Post a Comment
What is your thought about this?