Advanced Subqueries: Patterns and Real-World Uses, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 9.1 Free with a free account

Advanced Subqueries: Patterns and Real-World Uses

Database Programming · Chapter 9: Subqueries, Views, and IndexesSection 9.1 · lesson 49 of 7610 min · free with a free account

← Pulling Data from Multiple Tables: Practical ApplicationsNext lesson: Correlated Subqueries: How the Inner Query Depends on the Outer →

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

Choose scalar, row, column or table subqueries for each question.

  • Classify subqueries as scalar, row, column or table results
  • Filter rows against a calculated value such as the catalog average
  • Use IN, ANY and ALL with column subqueries, including empty-set and NULL edge cases
  • Build nested subqueries step by step from the inside out

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,255 words). Read along, or search it.

Opening Problem

Books Priced Above the Catalog Average

Maya Rao, the owner of Lantern Books, wants the books priced above the catalog average. Leo Park, her developer, could calculate that average and paste it into a filter. But tomorrow, a price changes. Would yesterday's number still answer today's question? A subquery keeps the calculation and the question together. We will make that report work, then test what happens when an inner query returns an unexpected shape.

Sample Database

Resetting the Bookstore 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.

Subquery Shapes

Scalar, Row, Column and Table Results

A subquery is a select statement inside another statement. The surrounding statement is the outer query, and parentheses mark the inner one. A scalar subquery supplies one column as one value. A row subquery supplies several columns for a single row, such as a product identifier and its price. A column subquery supplies a list for membership tests. A table subquery supplies rows and columns, often as a derived table in the from clause. These shapes describe what the surrounding expression expects. A scalar position is not a safe place to put an unrestricted list of prices. Start by naming what comes back, before choosing the operator. That habit prevents errors that indentation alone cannot reveal.

Scalar Filter

Comparing Prices With SELECT AVG

The filter compares each product price with a scalar average. The inner query has no outer reference, so it can be understood on its own. Its average is sixteen point two five. The outer query keeps products above that value, and the calculation stays connected to the data. Notice the parentheses around SELECT AVG. This is a value-producing expression, rather than a second command typed after the first. Run the file against shop. Explicit ordering makes these printed rows predictable. The returned products answer Maya's question using the current catalog. Changing a price changes the calculation when the statement runs again. Inside-out is a logical model. The optimizer may reorganize the work, while preserving meaning.

Select-List Placement

Showing the Average Beside Products

The same scalar expression can appear in the select list. Here it adds the catalog average beside two chosen product identifiers. That placement displays a value, rather than filtering by it. The alias catalog average gives the calculated column a useful name. A scalar query returning no rows supplies null. MySQL and SQL Server reject multiple scalar rows, while SQLite takes the first row. Run this aggregate example. It supplies one result row, matching the scalar position. The average repeats beside both products. It is a shared catalog figure, not an average recalculated for each product's own category. For portable SQL, enforce one result through an aggregate or a unique-key condition.

Derived Table

Filtering Grouped Order Counts

A derived table is a subquery in the from clause. This one groups orders, producing one count per ordering customer. The outer query can then filter that grouped result. Customer identifiers and order counts are columns of the derived relation. The name t identifies the derived table, and order count names its aggregate expression. MySQL and SQL Server require the derived-table alias. Run the report. The outer filter keeps customers with more than one order. Asha's customer identifier appears with two orders. The result is a compact answer to a grouped question, rather than a duplicate-filled join. Use a join for columns from both tables. Use a subquery when only filtering information matters.

Membership Test

IN With a Column Subquery

A column subquery returns a list. In tests whether the outer value belongs to that list, so repeated identifiers inside it do not multiply customers. Here the inner query supplies customers from the last two dates in our small example. The outer query supplies their first names. Use membership when you need the other query's identifiers, rather than its full rows. A plain equals comparison expects a scalar instead. Run the file. The date boundary belongs to the inner query, and ordering controls the final names. Elena and Farid qualify. Their names come from customers, while the qualifying identifiers came from orders. A not in list containing null leaves unmatched candidates unknown. A where filter keeps only true.

ANY and ALL

Quantified Comparisons and Empty Sets

MySQL and SQL Server offer any and all after a comparison operator. SQLite does not support this quantified syntax, so this file is a non-run listing. Greater than any means greater than at least one listed price. Some is a synonym for any, and equals any has the membership meaning of in. Greater than all means greater than every listed price. Less than any reverses the relevant boundary, and not equals all has the meaning of not in. For a nonempty list without nulls, greater than any can use the minimum boundary. Greater than all can use the maximum boundary. Those shortcuts fail as general rewrites for empty sets or nulls. Any over an empty set is false, while all over an empty set is true. A null comparison can leave the quantified result unknown. Check those edge cases, before replacing the logic with an aggregate.

Nested Subqueries

Building a Query From the Inside Out

A subquery can contain another subquery. Here the innermost question finds products in Asha's first order, and the middle question averages their catalog prices. The outside question finds products above that reference average. Indentation lets us follow the dependency from identifiers, to average, to comparison. Build this kind of statement from the inside out. Test the list, test the aggregate, then wrap the final query around them. Run the completed file. We display three products, ordered by identifier. The reference average is fourteen point seven five. The first three qualifying products are Database Basics, World History, and Biology Guide. For deeper nesting, a named common table expression or derived table may be easier to read.

Quick Check

Row Comparison With Pen Set

A fresh report compares both identifier and price with the row for Pen Set. The unique identifier fixes the inner result to one row. How many products match this row comparison? Choose zero, one, or eight. Pause, and predict. One product matches. Both components must agree with the inner row, so Pen Set is the match. The real run prints one. SQLite and MySQL support this row-value comparison; SQL Server needs separate scalar comparisons instead. Eight is tempting if you focus on the whole catalog, but a row comparison tests the paired values. Zero ignores the matching source product.

Null Check

NOT IN a List Holding Only Null

A new block list contains only a missing identifier. The query counts products whose identifiers are not in that list. What does the count show? Choose eight, seven, or zero. Pause, and predict. Zero products are counted. Each non-null product identifier is compared with an unknown value, so the predicate never becomes true. Run the query, and the aggregate prints zero. There are still eight stored products; this is a filtering result, not a deletion. Seven assumes the null names one real product to remove. It names none, and eight would require a true exclusion test for every product.

Key Takeaways

Match the Shape to the Expression

Maya's report now uses the current average, rather than a copied constant. Match the result shape to the surrounding expression. Choose where to use it: filter in where, display a scalar in select, or name a derived table in from. Check cardinality, nulls, empty sets, and dialect support. Clear SQL starts with a precise question about what the inner query returns.

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 Subqueries: Patterns and Real-World Uses

What is a scalar subquery in SQL?
A scalar subquery is an inner SELECT that returns one column and at most one row, so it can stand where a single value is expected. Example: SELECT name, price FROM products WHERE price > (SELECT AVG(price) FROM products). The average is recalculated each time the statement runs, so the filter stays current when prices change. If the subquery returns no rows, its value is NULL.
What happens if a scalar subquery returns more than one row?
MySQL and SQL Server raise an error when a subquery in a single-value position returns more than one row, while SQLite quietly uses the first row. To keep the query portable and predictable, guarantee one result with an aggregate such as MAX or AVG, or with a condition on a unique key, such as WHERE product_id = 16. Use IN instead of = when a list is genuinely expected.
What is the difference between ANY and ALL in SQL subqueries?
ANY is true when the comparison holds for at least one listed value, and ALL is true only when it holds for every one. So price > ANY (subquery) means above at least one listed price, while price > ALL (subquery) means above all of them. = ANY means the same as IN. ANY over an empty list is false, ALL over an empty list is true, and SQLite does not support either keyword.
Should you use IN with a subquery or a join?
Use IN with a subquery when the other table only decides which rows qualify, and a join when you need columns from both tables. SELECT first_name FROM customers WHERE customer_id IN (SELECT customer_id FROM orders) lists each qualifying customer once, even if that customer has several orders. A plain join would repeat the customer once per matching order unless duplicates are removed.

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 →