UPI Study › Courses › Database Programming › Free lessons › Lesson 11.1 Free with a free account
UNION vs. JOIN: Understanding the Difference
Database Programming · Chapter 11: Advanced Data Operations and Pattern MatchingSection 11.1 · lesson 64 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: Summarizing Data with ROLLUP and CUBE →← Dropping Indexes and Databases: Steps and ExamplesNext lesson: Summarizing Data with ROLLUP and CUBE →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Stack query results with set operators or relate rows with joins.
- Compare UNION and UNION ALL and predict the rows each returns
- Use INTERSECT and EXCEPT to find shared rows and left-only rows
- Explain when a JOIN is needed instead of a set operator
- Write compound queries with aligned columns and explicit grouping
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,151 words). Read along, or search it.
Opening Scenario
A Mailing List and Orders by Name
Maya Rao, owner of Lantern Books, wants one mailing list from customers and newsletter subscribers. She also wants each order beside its customer's name. Both requests combine data, but they need different shapes. Stacking names cannot attach an order to the right customer. Which tool belongs to each request? We'll build both answers, using a disposable copy of the bookstore's data.
Sandbox Setup
Two Lists That Overlap
Our customer projection keeps the original identifiers for Asha, Ben, and Chen. Newsletter subscribers add Ben, Chen, and Dara as an illustrative second list. Ben and Chen occur in both lists. That overlap will let us test whether a combination preserves repeated entries or removes them. The order projection keeps three original order numbers and their customer links. Those links, rather than name positions, tell a join which records belong together. Run the setup in SQLite. It creates a small scratch database, leaving the course's baseline unchanged. No query results are requested yet.
UNION ALL
Stacking Rows and Keeping Repeats
Union all stacks the rows of two queries. Each query returns one name column, so their results have matching shapes. The alias in the first select names the result column. The second select's column name does not rename that output. One order by belongs at the end, where it sorts the complete combined list. Without it, don't promise a display order. Run the query now. We want to keep every list entry, including people who appear once in each input. Six names appear. Ben occurs twice, and Chen occurs twice. Union all preserves that multiplicity; it does not establish unique people.
UNION
Removing Duplicate Name Rows
Plain union adds duplicate elimination. Here a complete result row contains only one name, so identical name rows collapse together. This is a set operator: it combines or compares whole query results. It does not look up additional customer details. Removing duplicates requires extra work, although actual speed depends on the execution plan. Choose union all when repeated rows are meaningful or impossible. Run this version against the same inputs. Only the operator changed, so we can isolate its effect on the result. Four names remain. Maya has a distinct name list, although real mailing systems should identify subscribers by a stable key, rather than names alone.
Whole-Row Matching
A Source Label Changes the Duplicates
Add a source label to each branch. The result now has two columns, and union compares both columns when deciding whether rows match. Ben labeled buyer differs from Ben labeled reader. Equal names no longer make those complete rows duplicates, because their source values differ. Column matching is positional. Put the same meaning in each position; compatible text types cannot catch an accidentally swapped first name and surname. Run the labeled query. Both branches return the same number of columns, with compatible values aligned in the same order. All six labeled entries survive. The labels explain provenance, but they also change the question that duplicate elimination answers.
Quick Check
Two Equal Scanner Entries Both Survive
Two scanners report the same item number, once each. This query combines their entries using union all, with no source label. How many rows will it return? Pause, and predict whether the repeated item number changes the row count. Two rows return. The scanners supplied two entries, and union all keeps them both even though the values agree. Run the query. A single result row would describe duplicate elimination, which this operator does not request. Both entries remain. Zero rows would need a filtering operation; merely stacking these inputs cannot remove every supplied row.
INTERSECT
Names Found in Both Lists
Intersect keeps only complete rows present in both query results. It answers an overlap question, rather than a request for all entries. Our lists share Ben and Chen. Repeated copies within either input do not create repeated output rows with this distinct form. MySQL added intersect and except in version eight point zero point thirty one. Older versions need alternatives, such as exists with distinct. Run the overlap query in SQLite. Its set operators support the distinct forms we are demonstrating here. The common names appear. Ordinary equality inside exists needs special treatment for nullable keys, because set comparisons treat nulls differently.
EXCEPT
Customers Without a Subscription
Except keeps rows in the first result that are absent from the second. Its direction matters: customers minus subscribers differs from subscribers minus customers. This direction asks which customer names lack a subscription. Reverse the branches, and the question becomes which subscriber names lack a customer match. Oracle traditionally spells this operation minus. Do not paste that spelling into MySQL or SQL Server; use the operator your server supports. Run the customer-first difference. The final order by still sorts the complete result, rather than either branch individually. Asha remains. Reversing the branches would retain Dara. With nulls, distinct set comparisons consider two null values equal; a join's equality test does not.
JOIN
Orders Beside Customer Names
Now answer Maya's second request. A join relates customer records to order records, using the shared customer identifier. The select list chooses a name and an order number. These are different kinds of details, placed together on each matching result row. A join can also multiply rows when several matches exist. It is not simply a guarantee that the output keeps the original row count. Run the join. Each selected order finds its customer's name through the equality condition, rather than through its position in a list. Maya gets order details beside names. For a full outer join workaround, preserve multiplicity with an unmatched branch; plain union can erase legitimate duplicates.
Portability Trap
Mixed Set Operators and Precedence
One portability trap remains: mixed set operators. MySQL and SQL Server evaluate intersect before union and except, unless explicit grouping changes the expression. SQLite instead groups compound operators from left to right. A query that omits grouping can therefore mean something different after migration. Use a derived table to make the intended first combination explicit. Here, the inner union finishes before the outer intersection compares it. Run this grouped version. The nesting communicates the intended operation, without relying on a server's default precedence. The result is two. Column counts, compatible types, positional meaning, and deliberate grouping are all part of a reliable compound query.
Final Check
Different Channel Labels Keep Two Rows
A fresh import labels the same item number with two sales channels. The query uses union, and both output columns are shown. How many complete rows survive? Choose one, two, or three rows. Pause, and predict before running the query. Two rows survive. Their item numbers agree, but their channel labels differ, so the complete rows are distinct. Run the new query to test that prediction. The deciding difference sits in the second column of each branch. Both channels appear. One row would require the entire rows to match; three cannot appear because the inputs supply only two rows.
Key Takeaways
Choose the Result Shape First
Maya's combined mailing list uses union when she wants distinct rows. Union all preserves entries when repeated rows carry meaning. Intersect finds common rows, and except finds left-only rows. Align compatible columns by position, and sort the combined result deliberately. For customer details beside orders, Maya uses a join. Decide the result's shape first, then choose the operation that produces it.
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 UNION vs. JOIN: Understanding the Difference
What is the difference between UNION and JOIN in SQL?
What is the difference between UNION and UNION ALL?
Does MySQL support INTERSECT and EXCEPT?
What are the rules for combining queries with UNION?
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 →