Left and Right Joins: When and How They Differ, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 8.2 Free with a free account

Left and Right Joins: When and How They Differ

Database Programming · Chapter 8: Joining Tables and Combining DataSection 8.2 · lesson 43 of 768 min · free with a free account

← Understanding SQL Joins — Core Concepts and Inner Join FundamentalsNext lesson: Full Outer Joins: Capturing All Records →

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

Keep unmatched rows with LEFT and RIGHT JOIN and handle the nulls.

  • Explain which input a LEFT JOIN and a RIGHT JOIN preserve
  • Find rows without a match using a LEFT JOIN and an IS NULL test
  • Decide whether a condition belongs in ON or WHERE in an outer join
  • Count real matches, including zero, with COUNT of a key column

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 (996 words). Read along, or search it.

Opening Problem

A Customer Report That Misses Dara

Sofia Alvarez handles sales at Lantern Books, our fictional bookstore. Her customer report misses Dara, who has never placed an order. That absence matters when Sofia plans outreach. She needs every customer, including people for whom the optional order details do not exist. Which side must the report preserve? We will make that choice explicit, and watch how a later filter can accidentally undo it.

Join Direction

What Left and Right Refer To

Restore the canonical bookstore rows in a disposable database. The fictional baseline has six customers, including Dara, and six orders with valid customer references. The word left describes the input written before join. Right describes the input after it; neither word refers to business importance or screen position. An outer join adds unmatched rows from its preserved input. The missing input contributes null values, called null padding, rather than invented order records. Run the setup. Our SQLite version supports left, right, and full joins; MySQL supports left and right, while SQL Server also supports full. Outer is optional in left outer join and right outer join. For each query, decide which roster must survive before writing the statement.

Left Join

Preserving Customers With Null Padding

This first report narrows the roster to Asha and Dara, using a customer-side where restriction. Customers is written first, so left join preserves those customers. The on test still connects matching identifiers. Asha can produce several joined rows, because preserving a customer does not limit the number of matching orders. The shell setting at the top displays missing values as NULL. It is a SQLite display instruction, not portable SQL sent to a database server. Run the report. The order by clause controls presentation; choosing left join alone does not guarantee any particular row sequence. Asha has two order rows. Dara has one padded row with a null order identifier; her customer record remains visible without pretending that an order exists. Null means the order side supplied no value here. It is different from a real order with a zero amount, an empty description, or a zero identifier.

Right Join

Keeping Every Intake Order

To demonstrate the other direction, create a separate intake sandbox. It allows a null customer reference, unlike the canonical orders table. One intake order belongs to Asha, while another has no recorded customer. A foreign key can allow null when its column is not declared required. Right join preserves intake, the input written after join. It keeps every intake order, even when no customer satisfies the equality test. Execute the file. This nullable intake list is a teaching extension, and does not alter the course rule that canonical orders require a customer. Both intake identifiers appear. The anonymous intake order has null for the customer name, while customers with no intake record do not appear. The mirror form is intake left join customers, with the same comparison and selected columns. Swapping inputs and changing right to left preserves these results.

Anti-Join

Finding Customers Who Never Ordered

Now ask specifically who has never ordered. An anti-join starts with a left join, then keeps only rows whose optional order key is null. Test the order primary key because it cannot be null in a real matching order. A nullable ordinary column could mistake a real match for an absence. Write is null, rather than equals null. Ordinary equality with null yields unknown, which neither satisfies an on condition nor passes a where filter. Run the anti-join. The where clause acts on the joined result, after the unmatched customer has received null order columns. Only Dara remains. In the other direction, intake left join customers followed by a null customer-key test finds the anonymous intake order.

ON Versus WHERE

Where a Date Restriction Belongs

Suppose Sofia needs Asha and Elena, showing only their recent orders. The date restriction belongs in on, because recent orders are optional details. Asha’s orders are earlier than the boundary. Failing that on test prevents a match, but it does not remove Asha from the preserved customer input. The customer restriction stays in where, because we actually want to remove other customers. Conditions serve different purposes even when they mention similar data. Run the query. Think of on as deciding which order details attach, and where as deciding which assembled rows remain. Asha stays with a null order, while Elena receives her recent order. Moving the date restriction into where would remove Asha’s row altogether. Likewise, putting a customer-city restriction only in on would not remove other customers. It would merely stop their orders from attaching.

Counting Matches

COUNT Star Versus COUNT of the Order Key

Counting requires the same care. Count star measures assembled rows, including the padded row that represents Dara’s unmatched customer. Count of the order identifier ignores null. It therefore measures actual matched orders, and reports zero when no order attached. Group by the customer key and name, so each result row describes one customer. Repeated names alone would not reliably identify different people. Run both aggregates together. This comparison exposes the difference between a preserved customer row and a real order row. Asha has two in both columns. Dara has one assembled row, but zero orders. Sofia should use the order-key count for the outreach report.

Quick Check

Devices Filtered by Open Tickets

A new support report lists two devices. Only one has a ticket, and that ticket is closed. The program keeps rows where ticket state is open. How many assembled rows survive? Read the filter’s position carefully. Pause, and decide.

Answer

WHERE Removed Both Device Rows

Neither device survives. The closed ticket fails the filter, and the other device’s null ticket state also fails it. Running the program confirms zero. A left join preserved the devices during matching, but the subsequent where test removed both assembled rows. To keep every device while attaching only open tickets, move the state restriction into on. Changing count star alone would not restore the missing devices.

Key Takeaways

Choose the Preserved Input Deliberately

Sofia can retain Dara by preserving customers. Left join keeps the left input, while right join keeps the right input. Use a null test on the optional primary key to find absence. Count that key to measure real matches, including zero. Place restrictions according to intent. On limits optional matches; where can remove the preserved rows that the outer join just created.

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 Left and Right Joins: When and How They Differ

What is the difference between a LEFT JOIN and a RIGHT JOIN?
A LEFT JOIN keeps every row from the table written before JOIN, and a RIGHT JOIN keeps every row from the table written after it. Preserved rows without a match get NULL in the other table's columns. The two are mirror images: orders RIGHT JOIN customers matches the same rows as customers LEFT JOIN orders with the same ON condition. OUTER is optional, as in LEFT OUTER JOIN.
How do you find rows with no match in another table using a LEFT JOIN?
Use a LEFT JOIN, then keep only rows where the other table's primary key IS NULL: SELECT c.first_name FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.customer_id WHERE o.order_id IS NULL. Test a non-nullable key, because a nullable ordinary column could be NULL in a real match. Write IS NULL, not = NULL, since a comparison with NULL yields unknown.
Why can a WHERE condition turn a LEFT JOIN into an inner join?
A WHERE test that NULL cannot pass, such as an equality on a right-table column, removes the NULL-padded rows that the LEFT JOIN preserved. For example, devices LEFT JOIN tickets followed by WHERE t.state = 'open' drops devices with no ticket, because NULL = 'open' is not true. An IS NULL test keeps those rows instead. To keep every device while attaching only open tickets, move the test into the join: ON t.device_id = d.device_id AND t.state = 'open'.
Why should you use COUNT(column) instead of COUNT(*) after a LEFT JOIN?
COUNT(*) counts the NULL-padded row of an unmatched customer as 1, while COUNT(o.order_id) ignores NULL and correctly reports 0 orders. For example: SELECT c.customer_id, c.first_name, COUNT(o.order_id) FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name. Group by the key as well as the name, since two customers can share a name.

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 →