I have written a query like below using NorthWind.
select COUNT(o.OrderId) as Orders
from Orders o
join [Order Details] od on o.OrderID = od.OrderID
The table Orders
has 830 data. However when I join Orders
on Order Details
query gives me the number of data inside Order Details
table which is 2155.
Why is the query result not 830?
select COUNT( distinct o.OrderId) as Orders
from Orders o
join [Order Details] od on o.OrderID = od.OrderID
It's because of the join. The details create a one to many relationship repeating order ID in your results. The repeated ID is then counted each time; thus inflating the count to match record count in order details. This can be avoided by either not doing the join, or by using a distinct count of orderID as listed above.
If you need any of the details from order details, or you want to exclude from your count orders without details, then you need the join. Otherwise I'd remove it and the distinct as it's just generating overhead and adding cost to getting your results.
Additionally though, if you have orders without details then and you want them included, you need to alter your join to be a LEFT join not just an join (Inner). As the join will exclude orders w/o details. If you don't want those orders w/o details in your count then an inner join is appropriate.