SQL and data modelling · Chapter 3
HAVING, subqueries and set operations
About this chapter
A condition that works as a row filter can fail once rows are grouped, and the reason is the order in which a query actually runs. This chapter uses that order to explain when to filter rows and when to filter groups, then builds up subqueries that return one value, a column or a whole table. It goes on to subqueries that look at the outer row, three ways of asking whether a match exists, and combining two result sets.
Who it is for: Learners who can write a basic SELECT with joins and now want to answer questions that need a count, an average or a comparison against another query.
You will be able to
- Decide whether a condition belongs in a row filter or a group filter, and say why.
- Write a subquery that returns one value, a column of values or a whole table, and put it in the right place.
- Explain what makes a subquery depend on the outer row, and when that is the right tool.
- Choose between EXISTS, IN and a join for a question about whether a matching row exists.
- Combine two result sets with the set operations and predict which rows survive.
The key idea: A query does not run in the order you type it. Rows are filtered first, then grouped, then the groups are filtered, and only then are the columns you named worked out. Most puzzling errors are the same mistake: using something before the step that creates it has happened.
In this chapter
- HAVING, WHERE and the order a query runs in
- Subqueries: scalar, column and table
- Correlated subqueries
- EXISTS, IN and JOIN
- Set operations: UNION, INTERSECT, EXCEPT
Locked: needs a plan
You can read chapter 1 free. Chapter 3 is the next one.
What you can do now, free: re-read chapter 1 and try its problems.
What a plan gives you: all chapters of the track you pick and their checks. Starter is ₹229 a month or ₹1,699 a year. It renews until you cancel, and you can cancel any time. Paid plans open at launch.
Why is this locked?
Chapter 1 of every track is free, so you can see how the track reads. The rest of a track and its checks come with a plan, or open as you pass each chapter's check.
The price is for one period, a month or a year. A plan renews until you cancel.