Advanced Data Manipulation Using Subqueries, Explained

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

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

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

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.

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 Advanced Data Manipulation Using Subqueries

How do you update rows based on a subquery in SQL?
Put the subquery in the WHERE clause to choose which rows change. For example, UPDATE customers SET tier = 'gold' WHERE customer_id IN (SELECT customer_id FROM order_totals WHERE total >= 30); updates each customer with a qualifying order once, even if they have several. Run the same condition as a SELECT first to preview the targets. Without the WHERE clause, every customer would change. For a negative test, NOT EXISTS avoids the NULL trap of NOT IN.
How does a correlated subquery work in an UPDATE statement?
It refers to the row being updated, so it computes a separate value for each target row. For example, UPDATE customers SET spending = COALESCE((SELECT SUM(o.total) FROM order_totals o WHERE o.customer_id = customers.customer_id), 0); gives each customer the sum of their own orders, and COALESCE turns NULL into zero for customers with none. The subquery must return one value: MySQL and SQL Server raise an error for multiple rows, while SQLite uses the first.
How do you delete duplicate rows but keep one in SQL?
Pick an explicit survivor rule, such as keeping the smallest id for each email, then delete the other rows. One method numbers rows with ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) inside a derived table and deletes the ids numbered above 1, because a window function cannot be filtered directly in WHERE. Another keeps MIN(id) for each email. Afterward, add a unique index on email so the duplicates cannot return.
What causes MySQL error 1093 in an UPDATE or DELETE?
Error 1093 occurs when a subquery reads the same table the statement is modifying, for example DELETE FROM subscribers WHERE id NOT IN (SELECT MIN(id) FROM subscribers GROUP BY email); A common fix wraps that subquery in a derived table that MySQL materializes, such as one using GROUP BY, or stores the keeper ids in a temporary table first. SQL Server does not have this restriction, and subqueries that read a different table are unaffected.

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 →