Advanced SQL · Lesson 1 of 5
Joins, properly
Combine tables without producing wrong numbers.
Most wrong numbers in business reporting come from a join, and the error is almost always one of two things.
Silent row loss. An inner join drops every row without a match on the other side. An inner join between orders and customers quietly excludes every order whose customer record is missing, and your revenue total is wrong with no error anywhere. Use a left join when the left table is the thing you are counting, and use an inner join deliberately rather than by default.
Silent row multiplication. Joining to a table where the key is not unique multiplies rows, and every sum computed afterwards is inflated. This is the more dangerous of the two because the number is larger rather than smaller, which nobody questions.
So check the row count before and after every join, every time. If it changed unexpectedly, stop and find out why before computing anything.
Verify uniqueness before joining. Count the rows and count the distinct keys in the table you are joining to. If they differ, your key is not unique and you need to decide what to do about it.
Self joins compare rows within one table: an employee with their manager, this month against the same month last year.
Anti joins, written as a left join with a null test on the right key, find what is missing. Orders with no customer, customers with no orders, records that failed to import.
And always qualify column names with a table alias, because two tables with a column called id give you an ambiguity error at best.
Count rows and distinct keys in every table you join to. If they differ, your totals are being multiplied.
ہر اس ٹیبل میں رو اور منفرد کلیدیں گنیں جس سے آپ جوڑ رہے ہیں۔ اگر تعداد مختلف ہے تو آپ کے مجموعے بڑھ رہے ہیں۔
Check what you learned
Create your free BvLogic ID to take the quiz and record your score.
Create your BvLogic ID