Advanced SQL
Lesson 1 of 5 5 lessons · free
Advanced SQL 5 lessons
  1. 1 Joins, properly
  2. 2 Window functions
  3. 3 CTEs, subqueries and structure
  4. 4 Making queries fast
  5. 5 Queries in production
  1. ✎ Course lab6 tasks · marked out of 100
Course overview
Data: video · change

This lesson: 356KB

Advanced SQL · Lesson 1 of 5

Joins, properly

Combine tables without producing wrong numbers.

That was a one-minute preview. The full course video is for signed-in learners. Sign in to watch it here, or create a free BvLogic ID.

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.

Exercise: 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

Up next: 2. Window functions

Continue to lesson 2 Up next 2. Window functions