UPI Study › Courses › Database Programming › Free lessons › Lesson 9.2 Free with a free account
Correlated Subqueries: How the Inner Query Depends on the Outer
Database Programming · Chapter 9: Subqueries, Views, and IndexesSection 9.2 · lesson 50 of 7610 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: EXISTS, NOT EXISTS, and WITH: Filtering with Subquery Logic →← Advanced Subqueries: Patterns and Real-World UsesNext lesson: EXISTS, NOT EXISTS, and WITH: Filtering with Subquery Logic →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Write inner queries that depend on each outer row's values.
- Explain how a correlated subquery uses a column from the outer query
- Write EXISTS, scalar COUNT and own-group comparisons with qualified correlations
- Rewrite correlated subqueries as joins while preserving zero counts and distinct customers
- Evaluate correlated subquery performance with execution plans and suitable indexes
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,206 words). Read along, or search it.
Opening Problem
One Entry per Customer Who Ordered
Sofia Alvarez, a sales associate at Lantern Books, needs customers who have ordered. Leo Park, the developer, first joins every order to its customer. Asha appears twice. Sofia wanted one customer entry, so why did a perfectly valid join change the report's shape? A correlated subquery can ask a separate matching question about each customer, without adding order rows to the result.
Sample Database
A Fresh Copy of the Shop Data
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.
Correlated EXISTS
Checking Orders for Each Customer
A correlated subquery uses a column from the outer query. The condition compares an order's customer identifier with the current customer identifier. The aliases keep the two scopes clear. The inner query can see c, but the outer select cannot reach the inner alias o. Exists asks only whether at least one matching row exists. Selecting one is customary; its actual projected value does not decide the answer. Run the report. Think of a customer being considered, the matching orders being tested, and a yes-or-no result deciding whether that customer stays. Asha appears once, and Dara is absent. Logically, Asha's two orders give the same true existence answer; they do not create two outer rows. This per-row trace explains the meaning. It does not promise that the optimizer physically scans orders again for every customer.
Non-Correlated Contrast
An Inner Query That Runs Alone
Compare a non-correlated subquery. The catalog average refers only to products inside its own query, so it does not borrow an outer-row value. You can run that inner average alone. Remove the inner query from our earlier existence test, and its c alias has no surrounding definition. That standalone test is useful for finding dependence. A missing name can also be a typo, so inspect the qualified reference before diagnosing correlation. Run the catalog filter. We show three rows from the ordered answer, while every candidate is compared with the same overall average. Correlation changes which inputs the inner question needs. Scalar describes its result shape, so a query can be both scalar and correlated.
Scalar Count
Order Counts Including Zero
A scalar subquery in select can compute a value for each customer. Count star returns one number, including zero when the matching set is empty. For this small comparison, we display Asha and Dara. The outer identifier supplies a different input to the inner count for each customer. An unqualified customer identifier inside orders can bind to the inner table. It then compares with itself, so the link to the outer customer is lost. Run the counts. These two outer rows provide a useful test of both the matching and the empty-group paths. Asha has two orders, while Dara has zero. The scalar aggregate gives a value without needing a grouped outer result.
Own-Group Comparison
Lines Above Their Order's Average
A correlated comparison can use each row's own group. This statement compares a line's quantity with the average quantity inside that same order. The matching order identifiers are the correlation. Without them, we would ask about the whole store's average line quantity, which is a different question. SQLite preserves a fractional average here. SQL Server averages integer input as an integer; cast the quantity to decimal there when fractions matter. Run the comparison. The same formula is applied to different order groups, including orders with only one line. The notebook lines in Asha's two orders qualify. A single-line order cannot exceed its own line's quantity, because its average equals that quantity.
Join Rewrites
DISTINCT Join and Anti-Join Forms
Existence often has a join rewrite. The first statement uses distinct customer identifiers and names, removing repetitions created by multiple matching orders. Keep the key in that distinct list. Two different customers can share a name, and collapsing names alone could merge people. The second statement is an anti-join. A left join preserves unmatched customers, and testing the non-nullable order key finds the unmatched rows. Run both statements. Their outputs answer customers with orders, then customers without orders, using different join shapes. Dara appears only in the anti-join answer. Not exists states that absence directly, and is often easier to read than the null-extended join.
Grouped Rewrite
LEFT JOIN With COUNT of the Key
A left join with grouping can replace the scalar count. Count the real order key, rather than count star, to preserve the zero case. The unmatched Dara row still exists in the joined relation. Count star would count that placeholder and incorrectly report one order. The group by includes the customer key and name. Each customer receives one count, while the left join preserves customers without orders. Run the count rewrite. The displayed pair agrees with the correlated count, but correctness depends on counting the appropriate column. Equivalent output does not establish equivalent speed. The optimizer may transform either form, so compare the actual execution plans for your workload.
Performance
Repeated Scans and Helpful Indexes
Without a helpful index or transformation, repeated inner scans can be expensive. A thousand outer rows times ten thousand inner rows suggests ten million candidate comparisons. That is a conditional worst-case model, not a measured runtime. An index on the correlated order customer identifier can turn scans into narrower lookups. InnoDB supplies an index needed by a foreign key when none is suitable. SQLite and SQL Server do not automatically index every referencing foreign key. Use MySQL explain, or SQL Server's estimated execution plan, to inspect the access path. A dependent subquery label describes dependence, not an automatic failure. Write the clearest correct question first. Rewrite after evidence identifies repeated scans, poor estimates, or an index that does not fit the lookup.
Quick Check
Reminders for Customers Without Recent Orders
A reminder goes to customers with no order on or after September fourth. The candidates are Asha and Chen. Who receives the reminder? Choose Asha, Chen, or both. Pause, and predict. Chen receives the reminder. Chen ordered earlier, but has no order in the specified date window. Run the query, and Chen is the only printed name. Asha has a qualifying later order, so not exists is false for her. Both is tempting if you ignore the outer-row link. The query tests each customer's orders within the window, rather than any order anywhere.
Grouped Check
Quantities Above a Group Average of Five
A new three-line order contains quantities three, three, and nine. This version joins a grouped derived table back to the lines. How many lines exceed their group's average? Choose one, zero, or three. Pause, and predict. One line exceeds the average. The group average is five, so only the quantity nine qualifies. The run confirms one. This is the grouped-join replacement for an own-group correlated aggregate, using a fresh order. Three counts all lines without applying the comparison. Zero misses that one quantity is greater than the shared group average.
Key Takeaways
Borrowing an Outer Value Deliberately
Sofia can now keep one entry per customer, while using orders only to decide eligibility. Correlation means the inner question borrows an outer value. Qualify both sides of the link, and preserve duplicates or zero counts deliberately when rewriting with joins. Choose the clearest expression of the question, then use plans and suitable indexes to investigate performance.
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 Correlated Subqueries: How the Inner Query Depends on the Outer
What is a correlated subquery?
How do you compare each row with the average of its own group?
Why must columns be qualified in a correlated subquery?
Are correlated subqueries slow?
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 →