UPI Study › Courses › Database Programming › Free lessons › Lesson 8.4 Free with a free account
Cross Joins: Generating Every Combination
Database Programming · Chapter 8: Joining Tables and Combining DataSection 8.4 · lesson 45 of 768 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: Self-Joins: Joining a Table to Itself →← Full Outer Joins: Capturing All RecordsNext lesson: Self-Joins: Joining a Table to Itself →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Pair every row of one table with every row of another.
- Explain how CROSS JOIN produces a Cartesian product and predict its row count
- Use a cross join to generate product variants, report skeletons and test grids
- Fill gaps in a report skeleton with a LEFT JOIN and COALESCE
- Recognize accidental Cartesian products caused by missing or always-true join conditions
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 (947 words). Read along, or search it.
Opening Problem
Every Notebook Format and Color
Leo Park develops the application at Lantern Books, our fictional bookstore. He needs a list of every notebook format and cover color before inventory exists. An inner join looks for a relationship already recorded in data. Leo instead wants all possible combinations, including variants that have never sold. A cross join creates that grid. The same operation can be useful on purpose, and disastrous when a matching condition disappears by accident.
Cartesian Product
Two Formats Times Three Colors
Restore the canonical bookstore, then add two small lists for this disposable variant example. Formats are pocket and desk; colors are blue, gold, and teal. These names describe invented candidate variants, rather than new canonical product records. Two formats and three colors should produce six combinations. Cross join needs no on clause because it imposes no matching restriction. Each row in the first input partners with every row in the second. Run the setup in SQLite. The same explicit cross join syntax is available in MySQL and SQL Server. The result is called a Cartesian product. Its size is the product of the input row counts, rather than their sum.
Generating Variants
Building SKU Labels From the Grid
Select a format, a color, and a combined label for the candidate variant. The label is a stock-keeping identifier, often called a SKU. This SQLite file joins text with double vertical bars. For MySQL or SQL Server, use the corresponding concat function to construct the same label. Ordering both columns makes the grid easy to inspect. Cross join itself guarantees combinations, not the order in which they will be displayed. Run the generator. Each of the two format values should be paired with all three color values exactly once, because each list has unique entries. Six rows appear, including every desk color and every pocket color. Creating this result does not insert six products into the stored catalog. If an input list repeated a color, its repeated row would create additional combinations. Cartesian counts use rows, not the number of distinct words.
Adding a Factor
A Third List Multiplies the Count
Add a packaging list with single and gift options. Crossing a third input multiplies the existing combination count by its row count. Two formats times three colors times two packaging choices gives twelve. Adding a factor grows the grid even though no individual list is large. A with clause supplies a named temporary query result for this statement. It is a compact way to show the entire two-row packaging list. Execute the count instead of printing the whole expanded grid. Count star measures every combination produced by the three inputs. The result is twelve. For a large product generator, estimate the full multiplication before asking the database to materialize or transmit all its rows.
Report Skeleton
Store-Month Rows With Zero Sales
A report skeleton lists combinations that should exist in a report. Here two invented store locations are crossed with three reporting months. Only campus in September has an observed sale. The other combinations still need a report row, because an absent observation should not hide an expected period. The cross product builds the skeleton, then a left join attaches sales on both store and month. Coalesce displays zero where no observation attached. Run the six-row report. This zero is a reporting decision for absent observations, rather than proof that a missing source record always means no activity. Every store-month combination appears. The same pattern builds calendar coverage, scheduling slots, and other grids before optional facts are joined to them.
Common Mistake
Accidental Multiplication From Missing Conditions
Now compare accidental multiplication with the intended order report. A comma-separated input list without a relationship pairs every customer with every order. An always-true on condition does the same thing, because every customer and order pair passes it. The final query uses the actual foreign-key relationship. It returns one row per order because each order references exactly one customer. Run all three counts. MySQL and SQLite also accept ordinary join without on; SQL Server rejects that ordinary-join syntax, though it accepts explicit cross join. The first two results are thirty-six, while the relationship returns six. Seeing the same customer beside every order should trigger an immediate predicate audit.
Test Grids
Customer-Product Combinations at Scale
A customer-product cross product can intentionally create test cases. Each customer is tested with every product, even when no matching purchase exists. Our small baseline generates forty-eight test combinations. Three hundred customers and two thousand products would generate six hundred thousand, before adding any further factor. If a three-table query links only two inputs, the remaining input can multiply every existing result. Check each table’s role when growth looks suspicious. Run the small test count. Counting can still require database work; it is an audit technique, not a guarantee that a bad large join is cheap. Previewing a few rows helps inspect meaning. MySQL and SQLite use limit, while SQL Server commonly uses top; limiting display does not necessarily limit all join work.
Quick Check
Invitations With an Empty Session List
A new invitation generator has three people, but its session list is empty. The program cross joins the two lists. How many invitation rows result? Pause, and decide.
Answer
An Empty Factor Gives Zero Rows
Zero invitation rows. Every invitation would need both a person and a session, and there is no session row to pair with anyone. The program confirms zero. Multiplication includes an empty factor, so a nonempty roster cannot create combinations by itself. Three would treat a missing session as an optional detail. That would require a different construction, rather than the Cartesian product shown here.
Key Takeaways
Predict the Size Before Crossing
Leo can generate candidate notebook variants with explicit cross join. Use it when every combination is intended, and predict its size first. Cross products also build report skeletons and test grids. A third input multiplies again, while an empty input leaves no combinations. When a business join suddenly expands, inspect its relationships. A missing condition, a self-comparison, or an unconnected input can turn a useful report into noise.
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 Cross Joins: Generating Every Combination
What does a CROSS JOIN do in SQL?
When is a CROSS JOIN useful?
What happens if you cross join with an empty table?
How can a missing join condition create an accidental Cartesian product?
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 →