This query looks like a LEFT JOIN, but it does not behave like one.
#sql #backenddevelopment #softwareengineering
This query looks like a LEFT JOIN, but it does not behave like one. A LEFT JOIN should keep every user, even when they have no order.
But users without an order get: o.status = NULL
Then this condition runs:
WHERE o.status = ‘COMPLETED’
Since NULL is not equal to COMPLETED, those users are removed. So the query ends up returning only users with completed orders, almost like an INNER JOIN.
Move the condition inside the ON clause:
LEFT JOIN orders o
ON u.id = o.user_id
AND o.status = ‘COMPLETED’
Now all users remain, and completed order details are added only when available.
[SQL LEFT JOIN, SQL INNER JOIN, SQL joins explained, SQL bug challenge, SQL interview questions, SQL query debugging, SQL WHERE clause, JOIN ON condition, SQL NULL values, database interview questions]
#sql #backenddevelopment #softwareengineering #codinginterview #database
Comments
Comments from the original post on Instagram
No comments yet
