UPI Study › Courses › Database Programming › Free lessons › Lesson 9.4 Free with a free account
Applying Subqueries in Practical Database Scenarios
Database Programming · Chapter 9: Subqueries, Views, and IndexesSection 9.4 · lesson 52 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: Removing Views with SQL DROP View →← EXISTS, NOT EXISTS, and WITH: Filtering with Subquery LogicNext lesson: Removing Views with SQL DROP View →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Solve averages, top-N, gap and duplicate problems with subqueries.
- Compare rows with overall and group-specific averages using scalar and correlated subqueries
- Select the top N rows per group with a correlated count and a tie policy
- Find gaps in a numeric sequence with NOT EXISTS
- Flag duplicate records and their extra copies with grouped and correlated subqueries
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 (987 words). Read along, or search it.
Opening Problem
One Family of Query Patterns
Maya Rao, Lantern Books' owner, wants a buying report. Leo Park, her developer, also needs to review a messy import. Above average, best in each category, missing numbers, and repeated contacts sound unrelated. Can one small family of query patterns answer them clearly? The key is deciding whether the inner question should return a number, a matching row, or a grouped set.
Sample Database
A Disposable Bookstore Copy
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.
Overall Average
Above Average With a Share of Total
The first report combines two scalar questions. One supplies the overall average for filtering; the other supplies a total for a percentage. We compare individual prices with the catalog average. Each displayed percentage is that product's price as a share of the sum of catalog prices. The decimal hundred forces fractional arithmetic, and NULLIF protects division when the total is zero. This is a price illustration, rather than a revenue measure. Run the report. We display the three highest qualifying prices, using their actual current values from the shared catalog. Biology Guide, Database Basics, and Statistics Workbook lead this result. The percentages use the whole catalog total, including products that the outer filter excludes.
Group Comparison
Products Above Their Category Average
Now compare each product with its own category. Our disposable extension groups the four books separately from the four accessories, without changing the canonical products schema. The outer aliases identify a product and its category. The inner query averages only products whose mapped category matches that outer category. This is a correlated scalar subquery. Removing the category link would change the business question back to comparison with the entire catalog. Run the category report. Its result can differ from the overall-average report, because each product now has a different reference group. Database Basics and Biology Guide exceed the books' average. Reading Lamp exceeds the accessories' average, although its price is below the books' average.
Top N per Group
Top Two per Category by Counting
Top two per category differs from limiting the entire result to two rows. Count how many same-category products have a strictly higher price. A product qualifies when that count is below two. Our named catalog step makes the category join available to both references in this statement. Ties need a policy. Equal prices do not beat each other, so this pattern may return more than two products in a tied category. Run the ranking. The ordering organizes the answer; the correlated count determines which products qualify within each group. The result contains two accessories and two books. For exactly two rows, also count an equal-price competitor with a preferred unique identifier.
Gap Finding
Missing Successors in a Number Sequence
Finding gaps is an absence question. This separate sequence sandbox contains one, two, four, and seven, so we search for stored numbers whose successors are absent. The maximum boundary prevents the final stored number from creating an endless gap after the range. This query reports gap starts, rather than every missing number. Number allocation can legitimately skip values after rollbacks or deletions. A missing identifier is a review clue, not proof that a save failed. Run the bounded gap query. The inner existence test looks for the successor of each outer number. The starts are three and five. Six is also missing, but it belongs to the gap beginning at five and is not separately returned.
Duplicate Review
Flagging Every Repeated Email
Duplicate review begins by defining what counts as the same entity. In this contact sandbox, matching email text is our chosen review key. A grouped subquery finds emails appearing more than once. The outer query lists every contact belonging to those repeated groups, including the earliest entries. An email match is an application rule, not universal proof of identical people. Shared addresses and normalization choices deserve review before any deletion. Run the import review. The synthetic example adds extra Asha and Ben contacts, using the canonical customer names. Four rows are flagged because both originals and copies belong to repeated groups. Finding only the extras requires a second, more specific question.
Extra Copies
Keeping the Lowest Identifier
To keep the lowest identifier in each email group, compare each contact with that group's minimum identifier. Higher identifiers are the extra copies under this policy. The qualified aliases create the link, matching the current contact with rows sharing its email. The aggregate returns one reference value. Null email addresses need an explicit policy, because ordinary equality does not match missing values. Our sample email values are all present. Run the query. We are only flagging rows for review, so no contact or customer is removed. Identifiers seven and eight are the extras. Back up and review the identity rule, before turning this report into a delete statement.
Quick Check
Top One With a Price Tie
A fresh category contains two offers at ten and one at eight. The query requests top one using the count of strictly higher prices. How many offers are selected? Choose two, one, or zero. Pause, and predict. Two offers are selected. Neither price-ten offer has a strictly higher competitor, so both satisfy the count-below-one condition. Run the query, and the result confirms two. Top one here means the highest price including ties, rather than exactly one identifier. One would require a tiebreaking rule. Zero overlooks that the leading offers have no better-priced competitor.
Key Takeaways
Choose the Reference Set Explicitly
Maya's report and Leo's import checks now use explicit reference sets. Scalar subqueries supply averages or totals, while correlated queries supply group-specific comparisons. Use EXISTS for presence, joins for columns from both relations, and a CTE or derived table to name reusable query steps. Test ties, nulls, empty sets, and duplicate policy. Compare execution plans before assuming that a clearer rewrite is also faster.
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 Applying Subqueries in Practical Database Scenarios
How do you get the top N rows per group with a subquery?
How do you find gaps in a sequence of numbers in SQL?
How do you find duplicate rows using a subquery?
How do you identify the extra copies of duplicates but keep one row?
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 →