Pulling Data from Multiple Tables: Practical Applications

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

← 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 →

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

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.

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 Pulling Data from Multiple Tables: Practical Applications

What is the grain of a query result?
The grain is what one result row represents, such as one order, one customer or one item line. Joining orders to order_items changes the grain from orders to item lines, so each order repeats once per item. Decide the intended grain before adding a table, and predict whether the new join should keep the row count or create several matches per row.
Why does SUM give a larger total after joining tables?
Fan-out repeats a parent value once per matching child row. If an order with a shipping fee joins to its three item lines, SUM(fee) adds that fee three times. Total the fee at order grain instead, or summarize items into one row per order in a derived table before joining it to the fees. Each order then contributes its fee once while item totals still include every line.
Why is SUM(DISTINCT) not a fix for duplicated totals?
SUM(DISTINCT fee) adds each different value once, so legitimately equal amounts from different orders are lost. Two orders that each pay a fee of 4 return 4 instead of 8. Equal values are not duplicate records. The correct repair keeps one row per order, for example by summing fees from the orders table directly or by joining pre-aggregated item totals.
Why does adding an INNER JOIN after a LEFT JOIN remove rows?
A later inner join requires a match, so it drops the NULL-padded rows that the earlier left join preserved. In customers LEFT JOIN orders followed by JOIN order_items, a customer with no orders gets NULL order columns, finds no item, and disappears. Keep left joins through the whole optional path, as in LEFT JOIN orders then LEFT JOIN order_items, and put optional restrictions in ON rather than WHERE.

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 →