UPI Study › Courses › Database Programming › Free lessons › Lesson 11.3 Free with a free account
Advanced Data Manipulation Using Subqueries
Database Programming · Chapter 11: Advanced Data Operations and Pattern MatchingSection 11.3 · lesson 66 of 7611 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: Inserting Across Multiple Tables: Techniques and Examples →← Summarizing Data with ROLLUP and CUBENext lesson: Inserting Across Multiple Tables: Techniques and Examples →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Use subqueries to choose target rows and compute their new values.
- Use a subquery in WHERE to choose the rows an UPDATE or DELETE changes
- Write a correlated subquery that computes a new value for each target row
- Delete duplicate rows with ROW_NUMBER and a deterministic survivor rule
- Explain MySQL error 1093 and how a materialized derived table avoids it
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,323 words). Read along, or search it.
Opening Scenario
Refreshing Spending and Cleaning an Import
Amina Diallo, Lantern Books' database administrator, must refresh customer spending and remove duplicate newsletter entries. A wrong subquery could change every customer the same way. She needs two decisions: which rows qualify, and which value belongs to each qualifying row. Those decisions can use different subqueries. We'll rehearse on disposable bookstore data. First inspect the targets, then compute the replacement values, and finally clean a separate subscription import.
Sandbox Setup
Customers With Tier and Spending Fields
The customer projection keeps our original identifiers and names. Tier and spending are disposable extension fields. Orders keep their original customer links. Asha has two orders, and Dara has none. Foreign keys are enabled before any transaction. Updating a customer attribute is different from deleting a parent that other rows still reference. Run the setup. It creates our targets, without requesting output.
More Setup
Line Items and Prices From the Baseline
Prices and quantities also come from the shared baseline. These projections keep only the fields needed here. Each order total sums quantity times price across its items. We derive it from the original data. Grouping gives each order one total. That supports customer selection and spending calculations. Run the remaining setup. We now have the required line items and prices.
Preview Targets
Customers With an Order of at Least Thirty
A view groups the line items into one total per order. We can reuse that named query, while keeping the baseline tables unchanged. The condition asks whether a customer has any order worth at least thirty. The subquery produces customer identifiers; the outer query selects matching people. Previewing the predicate as a select reveals the intended target rows. A customer with several qualifying orders still qualifies as one target customer. Run the preview. Check these targets, before reusing the same predicate in the update. Asha and Chen qualify. Asha's two qualifying orders do not mean we should apply an arithmetic update twice; membership is a yes-or-no decision.
Subquery in WHERE
Upgrading Qualifying Customers to Gold
Use the checked predicate in an update. The set clause assigns gold, while where limits the change to the customer identifiers returned by the subquery. An exists test can express the same positive relationship. For a negative relationship, not exists avoids the null trap associated with not in. Without where, this statement would change every customer. Keeping the assignment and the selection mentally separate makes that mistake easier to catch. Run the update on our scratch copy. Then inspect the tiers, in customer identifier order. Only Asha and Chen are gold. The other customers stay standard, which matches the target preview rather than a blanket change.
Correlated Update
Each Customer's Own Spending Total
A correlated update computes a value tied to the target row. The inner customer identifier refers back to the customer currently being considered. Sum produces one value across that customer's order totals. Coalesce replaces its null result with zero when the customer has no qualifying orders. This description is logical, not a promise about physical execution. The optimizer can transform the work without changing the required result. Run the recalculation. Omitting where is intentional, because every customer's spending needs refreshing. Asha receives sixty-nine point five, Chen receives thirty-eight, and Dara receives zero. Every value comes from that person's matching orders, rather than a shared global sum.
Server Syntax
UPDATE and DELETE With Joins
A join can also drive an update. MySQL places the join before set, while SQL Server names the target alias and then supplies a from clause. These are non-run server references. If a new value comes from several source rows, reduce them to one value per target. SQL Server does not define which matching source value wins in an ambiguous update. Grouping the source, or using a scalar aggregate, avoids that ambiguity. A scalar subquery supplies one column and at most one row. MySQL and SQL Server reject multiple rows; SQLite takes the first, so do not rely on that difference. The shared delete-join form names the customer alias after delete. Its left join retains unmatched customers, which the null order identifier then selects.
Quick Check
A Scalar Total for One Customer
A new charge list contains two amounts for customer nine and one for customer ten. The scalar query selects only customer nine's charges. What value will total contain? Choose six, ten, or eighteen. Pause, and predict the effect of the customer condition. Ten is the total. The matching amounts are four and six; customer ten's eight belongs to another customer. Run the query to confirm. The aggregate returns one scalar value, and coalesce would supply zero only if that aggregate were null. Ten appears. Six would drop a matching charge, while eighteen would ignore the customer condition and sum the entire charge list.
NOT EXISTS
Deleting Customers Who Have No Orders
Not exists asks whether there is no related order. We preview the predicate before applying it to a delete, and consider foreign-key dependencies first. A null inside a not-in list can turn a negative comparison into unknown. Not exists instead asks whether any row satisfies the matching condition. In this sandbox, only Dara has no orders. The delete removes that unreferenced parent; customers with order references remain. Run this rehearsal. A live cleanup also needs transaction and concurrency controls, beyond an earlier preview. Dara is listed as the candidate, and five customers remain afterward. The target condition was checked, and the parent links were respected.
Window Function
Numbering Repeated Emails With ROW_NUMBER
The separate newsletter import has repeated email addresses. Our rule is to retain the smallest identifier for each email, not whichever row happens to appear first. Row number partitions the records by email, then numbers each partition in identifier order. The first row receives one; later copies receive larger numbers. A window function cannot be filtered directly in the same where clause. Put its result in a derived table, then filter the numbered rows outside it. Run the numbering preview. A derived table is a from subquery; physical materialization depends on optimization. Rows three, five, and six have numbers above one. They are deletion candidates, while identifiers one, two, and four are the intended survivors.
Deduplication
Delete Later Copies, Then Enforce Uniqueness
The outer delete uses the identifiers of later copies. Its nested window query makes the survivor rule explicit and deterministic for this import. After cleanup, a unique index prevents the same non-null email from reappearing. Real business rules must decide whether case or normalization changes email identity. The minimum-identifier method is another option. Its keeper list contains non-null primary keys, so not in is safe for that particular list. Run the SQLite cleanup. MySQL needs special care, when the subquery reads its own target. The retained identifiers are one, two, and four. Cleanup and future enforcement solve separate problems, so removing duplicates should not replace a uniqueness rule.
MySQL Error 1093
Subqueries That Read the Target Table
MySQL error ten ninety-three restricts same-target subqueries. A materialized derived result is an important exception; wrapping a query is insufficient if the optimizer merges it. Grouping and window functions prevent that merge in these keeper examples. The server reads a separate derived result, rather than the prohibited direct target subquery. A temporary keeper table offers an inspectable alternative, and a suitable self-join can also express duplicate deletion. SQL Server does not impose this same restriction. Reading orders while updating customers is a different case: the subquery reads another table. Don't turn the same-target restriction into a ban on all correlated updates.
Final Check
The Smallest Identifier Survives
A fresh import arrives in the order seventeen, twelve, nineteen, all for one email. Its survivor rule still says to retain the smallest identifier. Which identifier survives? Pause, and decide whether arrival order or the stated ordering rule controls the result. Twelve survives. The rule chooses the minimum identifier, regardless of which record arrived first or last. Run the keeper query. Its aggregate gives one survivor, following the rule for this email group. The keeper is twelve. Seventeen follows arrival order, and nineteen selects the greatest identifier; neither implements the rule.
Key Takeaways
Separate Row Selection From New Values
Amina separates row selection from replacement values. Where subqueries choose targets, while correlated scalar expressions compute values from matching records. She inspects deletion candidates and defines a deterministic duplicate survivor. Null behavior, foreign keys, and multiple source matches remain part of the decision. Finally, she checks the target server's rules. Materialized keepers solve a MySQL restriction, while uniqueness prevents the cleaned import from drifting back into duplicates.
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 Advanced Data Manipulation Using Subqueries
How do you update rows based on a subquery in SQL?
How does a correlated subquery work in an UPDATE statement?
How do you delete duplicate rows but keep one in SQL?
What causes MySQL error 1093 in an UPDATE or DELETE?
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 →