When working with queries, specifically joining one or more tables together, it is easy to "drop" rows. The cause? The inner join.
Depending on the situation, consider using outer joins to avoid unintentionally dropping rows.
One Last Thing...
This video is part of my Intermediate Learning series. If you're interested in learning SQL subscribe to @Essential SQL and then check out our Intermediate Learner Playlist. Of course, I also encourage you to visit https://www.essentialsql.com to learn even more!
Important links:
Sample PizzaDB: https://github.com/kwenzel1/Essential...
Corresponding Article:
Source Code:
--First Query
select o.CustomerOrderID, o.OrderDate, c.CustomerID, c.LastName, cp.PercentDiscount
from CustomerOrder o
inner join Customer c on o.CustomerID = c.CustomerID
inner join Coupon cp on o.CouponID = cp.CouponID
--Sanity Check
select count(1)
from CustomerOrder
--Query Fix
select o.CustomerOrderID, o.OrderDate, c.CustomerID, c.LastName, cp.PercentDiscount
from CustomerOrder o
inner join Customer c on o.CustomerID = c.CustomerID
left join Coupon cp on o.CouponID = cp.CouponID
--Summary
select c.LastName, Avg(cp.PercentDiscount) AvgDiscountTaken
from CustomerOrder o
inner join Customer c on o.CustomerID = c.CustomerID
left join Coupon cp on o.CouponID = cp.CouponID
Group By c.LastName
--Summary Accounting for Null
select c.LastName, Avg(isnull(cp.PercentDiscount,0)) AvgDiscountTaken
from CustomerOrder o
inner join Customer c on o.CustomerID = c.CustomerID
left join Coupon cp on o.CouponID = cp.CouponID
Group By c.LastName
On this page of the site you can watch the video online Avoid Missing Rows - Don't Make This SQL Mistake | Essential SQL with a duration of hours minute second in good quality, which was uploaded by the user Essential SQL (EssentialSQL) 22 April 2022, share the link with friends and acquaintances, this video has already been watched 1,060 times on youtube and it was liked by 43 viewers. Enjoy your viewing!