Create your free BvLogic ID to continue this course and save your progress.
Advanced SQL 5 lessons
  1. 1 Joins, properly
  2. 2 Window functions sign in to open
  3. 3 CTEs, subqueries and structure sign in to open
  4. 4 Making queries fast sign in to open
  5. 5 Queries in production sign in to open
Course overview
Data: video · change

This lesson: 122KB

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.

Lab — try it yourself

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
Continue to lesson 2 Up next 2. Window functions