Applying Subqueries in Practical Database Scenarios, Explained

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

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

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

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.

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 Applying Subqueries in Practical Database Scenarios

How do you get the top N rows per group with a subquery?
Count how many rows in the same group have a strictly higher value, and keep rows where that count is below N. For the top two per category: WHERE (SELECT COUNT(*) FROM products AS p2 WHERE p2.category = p.category AND p2.price > p.price) < 2. Tied values are kept, so a group can return more than N rows; add a tiebreaker on a unique key when exactly N are required.
How do you find gaps in a sequence of numbers in SQL?
Look for numbers whose next value is missing: SELECT n + 1 AS gap_start FROM seq AS s WHERE NOT EXISTS (SELECT 1 FROM seq AS t WHERE t.n = s.n + 1) AND s.n < (SELECT MAX(n) FROM seq). For 1, 2, 4 and 7, the gaps start at 3 and 5. The MAX test stops the last value from reporting a gap. Skipped identifiers after rollbacks or deletions can be normal.
How do you find duplicate rows using a subquery?
Find the repeated values with a grouped subquery, then list every row carrying one of them: SELECT * FROM contacts WHERE email IN (SELECT email FROM contacts GROUP BY email HAVING COUNT(*) > 1). This returns the originals and the copies together for review. Decide first what counts as the same entity; a shared email is evidence, not proof, that two records describe one person.
How do you identify the extra copies of duplicates but keep one row?
Compare each row with the lowest identifier in its group: SELECT c.id FROM contacts AS c WHERE c.id > (SELECT MIN(x.id) FROM contacts AS x WHERE x.email = c.email). Rows above the minimum are the extras, and the lowest one is kept. NULL emails do not match through ordinary equality, so they need their own rule. Review and back up before turning such a report into a DELETE.

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 →