EXISTS, NOT EXISTS, and WITH: Filtering with Subquery Logic

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

EXISTS, NOT EXISTS, and WITH: Filtering with Subquery Logic

Database Programming · Chapter 9: Subqueries, Views, and IndexesSection 9.3 · lesson 51 of 768 min · free with a free account

← Correlated Subqueries: How the Inner Query Depends on the OuterNext lesson: Applying Subqueries in Practical Database Scenarios →

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

Test for matching rows safely and name query steps with CTEs.

  • Use EXISTS and NOT EXISTS to test for the presence or absence of related rows
  • Explain why NOT IN finds nothing when its list contains NULL, and repair it
  • Write common table expressions with WITH to name dependent query steps
  • Build a recursive CTE with an anchor member, a recursive member and a stopping rule

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

Opening Problem

A Reminder List That Suddenly Empties

Amina Diallo, Lantern Books' database administrator, adds a guest-order import to a test report. Suddenly, the list of customers without orders is empty. Nobody changed the customer table. How can one missing customer identifier erase every reminder candidate? We will fix that filter, then give a growing query readable names with common table expressions.

Sample Database

Rebuilding the Bookstore Sandbox

Our examples use Lantern Books, a fictional campus bookstore. This disposable database starts with the shared course data. Customers and products hold people and inventory. Prices and quantities are illustrative, and each lesson resets its own copy. Orders link to customers, while order items link orders to products. Foreign key checks are enabled for this connection. Save the setup file, then run it against a fresh shop database. Successful creation prints no rows here. Later commands reopen that database file. These examples use the real SQLite shell, and server dialect differences will be labeled.

EXISTS Basics

Testing for Matching Orders

Exists returns true when its subquery produces at least one row. Not exists returns true when there are no matching rows. The projected value is irrelevant to that test. This query even selects null, yet the existence question still has a definite true-or-false answer. The qualified customer identifiers make the subquery correlated. Logically, it asks about orders belonging to the customer currently being considered. Run the report. It asks for absence of matching orders, while leaving every stored customer and order unchanged. Dara is returned. An in test also filters without multiplying rows, while a join can return one row per matching order.

Null Trap

NOT IN With a Null Identifier

The import sandbox copies the ordering customer identifiers, then adds a guest with no identifier. Canonical orders still requires a customer identifier. Not in asks whether a candidate differs from every listed value. Comparing an unmatched identifier with null yields unknown, rather than true. A where clause retains only true. Combining true comparisons with the remaining unknown cannot establish that the candidate is outside the list. Run the import test. We count the resulting reminder candidates, so an empty filtered set appears as a visible zero. Zero does not mean every customer ordered. The nullable list broke this formulation, which explains Amina's disappearing reminder.

Two Repairs

NOT EXISTS or Filtering Out Nulls

There are two repairs. A correlated not exists asks whether a matching import row exists, so an unrelated guest cannot establish a match. Alternatively, remove nulls inside the not in subquery. This version is appropriate here because the outer customer key cannot be null. Plain in can also return unknown when nothing matches and null remains. A true match still wins, so its behavior differs from negated membership. Run both repairs. Each prints Dara, confirming that we restored the intended absence test rather than changing the customer data. These formulations agree under the stated non-null outer-key assumption. Make null policy explicit, instead of treating an unknown as an ordinary identifier.

Common Table Expressions

Naming Query Steps With WITH

With introduces a common table expression, or C T E. The first name here holds one order count per ordering customer. A comma introduces the second named query, which reads the first. The final select can use both names within this single statement. A C T E is not a stored table or a promise of cached evaluation. Its main benefit here is making dependencies readable from top to bottom. Run the statement. Only customers present in customer counts contribute to this average; customers without orders are outside that population. Customer one has two orders and exceeds the average. End the statement, and these C T E names cease to exist. MySQL needs version eight or later for this syntax. In SQL Server, terminate the preceding batch statement with a semicolon before with.

Recursive CTE

Anchor, Recursive Member and Stopping Rule

A recursive C T E refers to itself. Its anchor member supplies a starting row, and its recursive member produces later rows from earlier results. Union all combines those stages. Here the anchor supplies one, and the recursive member advances while the previous number is below five. The stopping rule matters. Without a finite boundary or exhausted data, a recursive query can continue producing work indefinitely. Run the sequence. Each round contributes another number, until the recursive condition no longer permits another row. The output runs from one through five. SQLite and MySQL use with recursive; SQL Server uses with, without the recursive keyword.

Hierarchy Walk

Following Manager Links by Depth

A hierarchy gives recursion a practical job. This explicitly fictional staff extension starts with Maya, then follows manager links to Amina and Sofia, and finally Leo. The anchor selects staff without a manager. The recursive member joins each discovered person to staff reporting to that person, increasing depth along the way. A fixed self-join handles a fixed number of levels. Recursion can follow a varying depth, provided the data and stopping policy are controlled. Run the hierarchy. Ordering by depth and identifier makes the display stable, rather than relying on the engine's traversal order. Maya is at depth one, Amina and Sofia at two, and Leo at three. In production, detect cycles and impose an appropriate depth guard. MySQL defaults to a thousand recursive rounds, and SQL Server to a hundred. Their configuration options differ; neither limit is a SQLite promise.

Quick Check

A Sequence Stepping by Two

A new sequence starts at two, adds two each round, and continues while the previous value is below six. What maximum is printed: six, four, or eight? Pause, and predict. Six is the maximum. The row holding four permits the recursive member to produce six, but six fails the next continuation test. Run the statement, and the aggregate confirms six. This tests the old value before producing a new one. Four stops one round too soon. Eight would require the row holding six to pass the strict less-than test.

Key Takeaways

Explicit Null Policy and Named Steps

Amina's reminder works again because the filter asks about matching rows, with an explicit null policy. Use common table expressions to name dependent steps within one statement. Reusing a name improves clarity, without promising physical caching. For recursion, identify the anchor, recursive member, and stopping rule. Check empty sets, missing values, and cycles before trusting the result.

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 EXISTS, NOT EXISTS, and WITH: Filtering with Subquery Logic

What does EXISTS do in SQL?
EXISTS returns true when its subquery produces at least one row, and NOT EXISTS returns true when it produces none. The selected value does not matter, so SELECT 1 or even SELECT NULL works. For example, SELECT c.first_name FROM customers AS c WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id) lists customers with no orders, without repeating anyone.
Why does NOT IN return no rows when the subquery contains NULL?
Comparing a value with NULL yields unknown, so NOT IN cannot prove that a candidate differs from every listed value, and WHERE keeps only true results. For example, 5 NOT IN (1, 2, NULL) is unknown, not true. Use a correlated NOT EXISTS instead, or add WHERE customer_id IS NOT NULL inside the subquery when the outer value itself cannot be NULL.
What is a common table expression (CTE) in SQL?
A common table expression is a named query defined with WITH that exists only for the single statement that follows it. For example: WITH counts AS (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id) SELECT customer_id FROM counts WHERE n > 1. Several CTEs can be separated by commas, and later ones can read earlier ones. MySQL needs version 8.0 or later.
How does a recursive CTE work?
A recursive CTE has an anchor member that supplies starting rows and a recursive member that builds new rows from the previous round, combined with UNION ALL. It ends when the recursive member produces no more rows, so a stopping condition is essential. Starting at 1 and adding 1 while n < 5 returns 1 through 5. MySQL requires WITH RECURSIVE, SQLite accepts it, and SQL Server uses plain WITH.

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 →