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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Left and Right Joins: When and How They Differ →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What is the difference between ON, USING, and NATURAL JOIN?
How do you join more than two tables in SQL?
How can you check that a join returned the right rows?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →