Understanding SQL Joins — Core Concepts and Inner Join Fundamentals

UPI Study › Courses › Database Programming › Free lessons › Lesson 8.1 Free with a free account

Understanding SQL Joins — Core Concepts and Inner Join Fundamentals

Database Programming · Chapter 8: Joining Tables and Combining DataSection 8.1 · lesson 42 of 769 min · free with a free account

← Clearing Tables with SQL TRUNCATE TableNext lesson: Left and Right Joins: When and How They Differ →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

How an inner join matches rows across tables through their keys.

  • Write an inner join that matches a foreign key to a primary key with ON
  • Explain why matched customers repeat and unmatched customers disappear from inner join results
  • Compare ON, USING and NATURAL JOIN and their support in SQLite, MySQL and SQL Server
  • Audit a join, including a multi-table chain, with row counts and actual keys

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,087 words). Read along, or search it.

Opening Problem

Orders and Customers in Separate Tables

Maya Rao owns Lantern Books, our fictional bookstore. She wants each order listed beside its customer, but those facts live in separate tables. Putting customer details on every order would repeat them. A change of city would then require many edits, with plenty of chances for disagreement. Can we keep the clean design, and still answer the business question? We will connect the rows, then check what the connection kept and lost.

Sample Database

Six Customers, Six Orders and Item Lines

Our setup restores the shared bookstore database. These names, prices, and orders are invented teaching data, reused so the relationships stay familiar. There are six customers and six orders. An order stores a customer identifier, a foreign key referencing the customer primary key. Item lines connect orders to products. Their combined key allows each product once per order, while quantity records how many copies were bought. Run the setup in the SQLite shell. Successful creation and insertion statements print nothing here; each following file asks a specific question. A join builds a query result. It does not permanently combine the tables, duplicate their stored records, or change any customer address.

Inner Join

Matching Orders to Customers With ON

Select the customer first name and the order identifier. The prefixes identify which table supplies each column, even when names could otherwise be ambiguous. From customers as c gives customers a nickname. Join orders as o introduces the second role; these aliases last only for this query. The on clause compares the order foreign key with the customer primary key. Only combinations making that comparison true belong in an inner join. Run the query, with order by making the display predictable. A plain join without the word inner means the same thing in these systems. Six rows appear. Asha appears twice because she placed two orders; that repetition represents two different matches, rather than duplicate customer records. Dara is absent because she has no order. Inner joins quietly omit unmatched rows, so this report cannot establish that every customer has bought something.

Count Audit

Comparing Order and Joined Row Counts

A useful audit compares the original order count with the joined count. Count star counts result rows, regardless of which columns we choose to display. These two selects are stacked only to compare their counts. Both should describe the same six orders, because every order has exactly one valid customer. That expectation depends on the relationship. A nullable foreign key, a missing referenced row, or a filter could legitimately reduce the joined count. Execute the count audit. Equal counts support our expectation here, although counts alone cannot prove that the correct customers were matched. Both counts are six. To check meaning as well as size, inspect actual identifiers and verify that the on clause compares the intended relationship. Unexpected growth suggests nonunique matching columns or a different row grain. A declared primary key itself cannot contain repeated key values.

Adding a Filter

Relationship in ON, Restriction in WHERE

Now ask for orders from customers in Pune. Keep the relationship in on, then put this business restriction in where. For an inner join, adding this same deterministic restriction to on would return the same combinations. That equivalence will change with outer joins. A join condition can also use inequalities or several tests. Equality on a key is common, but it is not the definition of a join. Run the filtered report. We still select explicit columns, so the result avoids an unexplained pair of same-named customer identifier columns. Four orders remain: two for Asha, one for Chen, and one for Farid. Filtering customers has not collapsed multiple orders into one customer row.

Join Shortcuts

USING and NATURAL JOIN Compared

Using names the shared matching column once. Here customer identifier exists in both inputs, so using expresses the same equality relationship. Natural join chooses every shared column name automatically. At present, customer identifier is the only shared name between these particular tables. SQLite and MySQL accept both forms. SQL Server supports neither shortcut; write an explicit on condition there instead. Run both counts. They agree for this schema, and using also exposes just one shared join column when selecting star. Both return six today. If orders later gains a city column, natural join will silently require city equality too. Explicit on makes that dependency visible.

Multi-Table Join

Four Tables Linked by Three Joins

The order detail needs four tables. Customers supply the person, orders identify the purchase, item lines supply quantities, and products supply readable descriptions. Each added table connects to one already present. The order identifier links items to orders, while the product identifier links those items to products. This connected chain uses three join clauses for four tables. That is a convenient construction pattern, rather than a universal limit on possible predicates. Run the detail for Asha’s first order. The filter keeps the output short enough to inspect every item and its quantity. Two rows appear for that order: Database Basics and Notebook. The result grain is one item line, so repeating the order identifier is expected. Across the full baseline, the chain produces ten item rows. Adding customer points across those rows would repeatedly count the same customer’s points.

Quick Check

Devices and Tickets Row Count

Try a fresh pair of inputs: two devices, seven and eight, and three tickets, for devices seven, seven, and nine. An inner join keeps only matching combinations. Predict the row count. Pause, and decide.

Answer

Two Matches, Unmatched Rows Omitted

Two joined rows. Device seven matches tickets a and b; device eight and ticket c find no partner. The program confirms two. One device can appear in several result rows when it has several matches. Three would count every ticket, including the unmatched one. An inner join omits rows with no partner.

Common Mistake

Cartesian Product Versus Wrong Comparison

Finally, compare a deliberate Cartesian product with a mistaken relationship. Cross join pairs every customer with every order, without a matching condition. Six times six gives thirty-six possible combinations. This is a logical way to reason about joins; the optimizer need not physically enumerate every candidate. The second query compares an order identifier with a customer identifier. Its syntax is legal, but those identifiers describe different kinds of thing. Run both audits. MySQL and SQLite also allow an ordinary inner join without on, producing a Cartesian result. SQL Server requires on for that form. The cross product returns thirty-six, while the wrong comparison returns zero. A query can execute successfully and still answer the wrong question.

Key Takeaways

State the Relationship and Check the Grain

Maya can keep customer facts separate and recover her report with a join. State the matching relationship explicitly, using qualified column names. Choose the intended row grain. Inner joins retain matching combinations, so missing customers and repeated names both deserve interpretation. Audit counts and inspect actual keys. A plausible number of rows is useful evidence, but the meaning of the relationship is the final check.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Understanding SQL Joins — Core Concepts and Inner Join Fundamentals

What does an inner join return in SQL?
An inner join returns only the combinations of rows for which the ON condition is true. SELECT c.first_name, o.order_id FROM customers AS c JOIN orders AS o ON o.customer_id = c.customer_id lists each order beside its customer. A customer with two orders appears twice, and a customer with no orders is left out. JOIN without the word INNER means the same thing in SQLite, MySQL and SQL Server.
What is the difference between ON, USING, and NATURAL JOIN?
ON states the match condition explicitly, such as ON o.customer_id = c.customer_id. USING (customer_id) expresses equality on a column that has the same name in both tables, and NATURAL JOIN matches every shared column name automatically. SQLite and MySQL accept USING and NATURAL JOIN, while SQL Server supports neither. NATURAL JOIN is risky: if both tables later gain a city column, the join silently requires equal cities too.
How do you join more than two tables in SQL?
Add one JOIN clause per extra table, each linked by an ON condition to a table already in the query. For example, customers join orders on customer_id, orders join order_items on order_id, and order_items join products on product_id: four tables, three joins. That result has one row per item line, so order and customer details repeat, and summing a customer-level column across those rows counts it repeatedly.
How can you check that a join returned the right rows?
Compare the joined row count with the count the relationship predicts, then inspect actual keys. If every order has exactly one valid customer, orders joined to customers should return as many rows as orders alone. A smaller count suggests a missing referenced row, a nullable foreign key or a filter; a larger count suggests nonunique matching columns. Equal counts alone cannot prove that the correct customers were paired.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →