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
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: Applying Subqueries in Practical Database Scenarios →← 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 →
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.
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 EXISTS, NOT EXISTS, and WITH: Filtering with Subquery Logic
What does EXISTS do in SQL?
Why does NOT IN return no rows when the subquery contains NULL?
What is a common table expression (CTE) in SQL?
How does a recursive CTE work?
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 →