Cross Joins: Generating Every Combination, Explained

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

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

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

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.

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 Cross Joins: Generating Every Combination

What does a CROSS JOIN do in SQL?
A CROSS JOIN pairs every row of one table with every row of another, producing a Cartesian product without any matching condition. Its row count is the product of the input counts, not their sum: 2 formats CROSS JOIN 3 colors gives 6 rows, and adding a third table of 2 packaging options gives 12. The explicit CROSS JOIN syntax works in SQLite, MySQL and SQL Server and needs no ON clause.
When is a CROSS JOIN useful?
A CROSS JOIN is useful when every combination is genuinely wanted, such as product variants, calendar or scheduling slots, and test cases. A common report pattern crosses stores with months to build a skeleton, then LEFT JOINs sales on both store and month and uses COALESCE(s.total, 0) so periods without sales still appear. Estimate the size first: 300 customers times 2,000 products is already 600,000 rows.
What happens if you cross join with an empty table?
The result has zero rows. Each output row needs one row from every input, so crossing 3 people with an empty sessions table produces no combinations, just as 3 times 0 is 0. If the people must still appear when there are no sessions, a cross join is the wrong construction; an outer join or a separate query for the people is needed instead.
How can a missing join condition create an accidental Cartesian product?
Without a real matching condition, every row pairs with every row, exactly as in a deliberate cross join. Listing tables with commas and no linking WHERE test, as in FROM customers, orders, or writing an always-true ON 1 = 1, turns 6 customers and 6 orders into 36 rows instead of 6. Seeing one customer beside every order is a signal to audit the join predicates.

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 →