UNION vs. JOIN: Understanding the Difference, Explained

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

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

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

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.

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 UNION vs. JOIN: Understanding the Difference

What is the difference between UNION and JOIN in SQL?
UNION stacks the rows of two queries vertically, while a JOIN places columns from related tables side by side on the same row. Use UNION to merge similar lists, such as customer names and subscriber names, into one column. Use a JOIN to attach details through a shared key, such as each order with its customer's name. A join can also multiply rows when several matches exist, so the result can contain more rows than either table.
What is the difference between UNION and UNION ALL?
UNION removes duplicate result rows, while UNION ALL keeps every row from both queries. If two lists of three names share two names, UNION ALL returns six rows and UNION returns four. Duplicates are judged on whole rows, so adding a source label column can make rows distinct again. Removing duplicates also takes extra work. Use UNION ALL when repeated rows are meaningful or cannot occur, and UNION when you want each distinct row once.
Does MySQL support INTERSECT and EXCEPT?
Yes, MySQL supports both from version 8.0.31; older versions need alternatives such as EXISTS or NOT EXISTS subqueries. INTERSECT returns rows found in both results, and EXCEPT returns rows from the first result that are absent from the second, so the order of the two queries matters. SQL Server and SQLite also support both. Oracle traditionally spells EXCEPT as MINUS, a spelling MySQL and SQL Server do not accept.
What are the rules for combining queries with UNION?
Each query must return the same number of columns, and columns are matched by position, not by name, so each position needs compatible types and the same meaning. Output column names come from the first query, and a single ORDER BY at the end sorts the combined result. When mixing operators, MySQL and SQL Server evaluate INTERSECT before UNION and EXCEPT, while SQLite works left to right, so make the grouping explicit with a derived table.

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 →