Correlated Subqueries: How the Inner Query Depends on the Outer

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

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

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

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.

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 Correlated Subqueries: How the Inner Query Depends on the Outer

What is a correlated subquery?
A correlated subquery is an inner query that refers to a column of the outer query, so its answer can differ for each outer row. In SELECT c.first_name FROM customers AS c WHERE EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id), the inner query uses c.customer_id. Run on its own, the inner query fails because c is undefined, which is a quick test of dependence.
How do you compare each row with the average of its own group?
Use a correlated scalar subquery that averages only the rows sharing the outer row's group key: SELECT i.order_id, i.quantity FROM order_items AS i WHERE i.quantity > (SELECT AVG(x.quantity) FROM order_items AS x WHERE x.order_id = i.order_id). Without the correlation, the comparison uses the whole table's average. In SQL Server, AVG of an integer column returns an integer, so cast to decimal when fractions matter.
Why must columns be qualified in a correlated subquery?
An unqualified name binds to the nearest table that has that column, which can silently break the correlation. In (SELECT COUNT(*) FROM orders WHERE customer_id = customer_id), both names refer to orders, so each order is compared with itself and every customer receives the count of all orders with a customer_id. Writing o.customer_id = c.customer_id links the inner rows to the current outer customer.
Are correlated subqueries slow?
They can be, but not automatically. Without a helpful index or optimizer rewrite, re-scanning the inner table for each outer row is expensive: 1,000 outer rows times 10,000 inner rows suggests 10 million comparisons in the worst case. An index on the correlated column, such as orders.customer_id, can turn scans into narrow lookups. Check MySQL EXPLAIN or a SQL Server execution plan before rewriting the query as a join.

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 →