UPI Study › Courses › Database Programming › Free lessons › Lesson 8.7 Free with a free account
Pulling Data from Multiple Tables: Practical Applications
Database Programming · Chapter 8: Joining Tables and Combining DataSection 8.7 · lesson 48 of 7610 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: Advanced Subqueries: Patterns and Real-World Uses →← Using Aliases to Simplify SQL QueriesNext lesson: Advanced Subqueries: Patterns and Real-World Uses →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Combine several tables without losing rows or inflating totals.
- Chain joins across customers, orders, items, products and categories at a stated grain
- Reconcile grouped totals produced by different join paths
- Explain fan-out and repair inflated parent totals by aggregating before joining
- Keep optional rows by using left joins through the whole optional path
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,207 words). Read along, or search it.
Opening Problem
A Shipping Total That Suddenly Grows
Maya Rao owns Lantern Books, our fictional bookstore. Her sales report needs customers, orders, items, products, and categories in one connected result. Another report totals shipping after joining item lines, and the total suddenly grows. The query runs, but its rows describe the wrong level of detail. We will build the useful reports, reconcile their totals, and repair that inflated shipping figure by respecting what each row represents.
Sample Data
Categories, Sale Prices and Order Fees
Restore the shared bookstore in a disposable sandbox. This lesson adds a category to each product, a sale price to each item, and separate order fees. The illustrative sale prices begin at the baseline catalog prices. Real sale prices belong on item lines, because a later catalog change should not rewrite history. Categories are Books, Supplies, and Equipment. These additions are local teaching extensions; the underlying customer, order, product, and quantity rows stay canonical. Run the setup. Each fee row has a unique order identifier, and each item retains its combined order-and-product key. A result’s grain is what one row represents. Before adding a table, predict whether its relationship should preserve that grain or create several matches.
Detail Report
One Row per Item Line
Start with the question: which customer bought each product, in which category? Select a few useful fields, rather than every column from every input. Follow customers to orders, orders to item lines, item lines to products, and products to categories. Each on clause supplies the next relationship. The result should contain one row per item line. Every baseline item has exactly one order, customer, product, and assigned category. Run the short detail for Asha’s first order. Across the complete baseline, this chain has ten item rows; audit counts whenever you add another link. The book line totals twenty-five, and the notebook line totals nine. A missing match could remove an inner-join row; unexpected growth suggests additional matching combinations.
Customer Summary
Revenue per Customer With Zeros Kept
For a customer summary, preserve customers through both optional links. A customer without orders must still contribute a customer group. Logically, the joins assemble item combinations, then group by collapses them to customer grain. This describes meaning, rather than a mandatory physical execution sequence. Multiply quantity by the stored sale price, sum within each customer, and coalesce an absent total to zero for this report. Run the customer summary. Grouping by identifier and name prevents different people with identical names from sharing a group. Dara remains with zero revenue. Asha leads with sixty-nine dollars and fifty cents, and all customer totals together equal one hundred seventy-three dollars.
Category Summary
Reconciling Category and Customer Totals
The category report takes another path through the same sale facts. Categories connect to products, and products connect to the item lines that were sold. Because every product has exactly one category here, each sale line contributes to exactly one category total. A many-category design would need a different allocation rule. Reconcile independently grouped reports over the same intended sales. If their grand totals disagree, investigate lost matches, repeated matches, or different filters. Run the category summary. Books contribute one hundred twenty-two dollars and fifty cents; Supplies contribute thirty-one dollars and fifty cents. Equipment contributes nineteen dollars. The categories also total one hundred seventy-three dollars, supporting our claim that both reports cover the same sales.
Quick Check
Scans Without a Matching Label
A new scanner sees codes A and B. Its label list contains only A. The displayed inner join counts scans that find labels. How many scans survive? Pause, and decide.
Answer
The Inner Join Drops the Unlabeled Scan
One labeled scan. Only code A finds a label. The program returns one. Code B disappears without a warning. To audit every scan, preserve scans with a left join. Zero would miss the existing label; two would require keeping unmatched codes.
Fan-Out
Order Fees Repeated per Item
A shipping fee belongs to an order, while an item amount belongs to an item line. Joining those grains repeats each fee once per item. This repetition is fan-out: one parent matches several children. It is useful for detail reports, but dangerous when adding parent values afterward. The first aggregate totals the fee records directly. The second totals the same fee column after the item join, so its input contains repetitions. Run the comparison. The order-grain result is twenty dollars, while the item-grain result is thirty-five dollars. Both calculations are legal. The second measures repeated fees over item combinations, which is not the shipping total Maya asked for.
Fixing the Grain
Summarize Items Before Joining Fees
Repair the grain before combining summaries. This derived query totals item amounts into one row per order, then joins those rows to unique fee records. Each order now contributes its fee once, while its item total still includes every item quantity. Independently summing fees would also avoid the original repetition. Do not use distinct fee values as a general repair. Different orders can legitimately charge the same fee, and each order’s fee must count. Run the combined summary. Shipping returns to twenty dollars, and sales remain one hundred seventy-three dollars. This inner summary assumes these orders have items. To retain fee records for empty orders, preserve the fee input and handle a missing item total deliberately.
Join Order
A Later Inner Join Drops Dara
Written join order matters when preservation matters. A later inner join can remove the padded customer row created by an earlier left join. The first chain does that to Dara. The second keeps left joins through the optional path, so her absent order never becomes a reason to disappear. Pure inner joins can often be reordered while preserving equivalent predicates. Outer joins require attention to which input and grouping are preserved. Run the customer counts. The mixed chain retains five distinct customers, while the left chain retains all six. A null-rejecting where restriction on optional item details can also remove Dara. Put optional matching restrictions in on when preserving her is the report’s purpose.
Execution Plans
Indexes and Readable Date Ranges
An execution plan describes how the server chooses to obtain the result. Here an index covers the customer lookup followed by an order-date range. Write date ranges against the stored column, rather than wrapping every date in a year function. Suitable indexes can help; their use is not guaranteed. InnoDB creates a needed foreign-key index automatically, while SQL Server does not automatically index foreign keys. Choose indexes for actual access patterns. Run SQLite’s explain query plan, displayed as plain rows. MySQL uses explain; SQL Server provides execution plans through its tools. The output shows indexed searches here. An optimizer may push safe filters earlier or reorder inner joins; inspect the plan instead of assuming written order determines work.
Second Check
SUM DISTINCT on Equal Fees
A new shipping list contains two separate orders, each charged four dollars. Someone tries to prevent double-counting with sum distinct fee. What does this displayed query actually return? Pause, and decide.
Answer
Equal Amounts Are Not Duplicates
Four dollars. Distinct removes repeated values, so only one occurrence of the fee amount reaches the sum. The program confirms four, although the two real orders owe eight together. Equal amounts are not duplicate orders. Sixteen would require additional repeated input rows. The correct repair preserves one row per order, rather than one row per distinct fee value.
Key Takeaways
Choose the Grain, Then Reconcile Totals
Maya’s reports now follow explicit relationships and a chosen row grain. Customer and category sales reconcile, while shipping is totaled at order grain. Preserve optional rows through the complete join path. Recheck counts and totals whenever another table or filter changes that path. Use suitable indexes and readable date ranges, then inspect the chosen execution plan. Correct semantics come first; measured access behavior guides performance work.
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 Pulling Data from Multiple Tables: Practical Applications
What is the grain of a query result?
Why does SUM give a larger total after joining tables?
Why is SUM(DISTINCT) not a fix for duplicated totals?
Why does adding an INNER JOIN after a LEFT JOIN remove 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 →