SQL Child / Thinking In Sets

Stop Walking The Rows, Start Describing The Result

The single hardest shift for a beginner is giving up the mental picture of moving through records one at a time.

Almost everyone arrives with the same instinct, and it is a reasonable one. You picture a long list. You picture yourself starting at the top, looking at each record, deciding whether it belongs, and putting the keepers into a pile. That is how a person would do it with paper, and it is how most ordinary programming works. So when you first sit down to ask a database a question, you try to describe that walk. Where do I start, what do I look at next, how do I know when to stop. The system will not answer any of those questions, because it is not built around the walk.

What it is built around is description. You do not tell it how to get the records. You tell it what the records you want look like, and it works out the getting for itself. That sounds like a small difference and it is actually an enormous one. You are no longer giving instructions. You are writing a specification of a set: every record that satisfies these conditions, all at once, considered together rather than in sequence. The order in which the machine looks at things is genuinely none of your business, and the moment you stop caring about it your questions get much clearer.

The practical benefit shows up quickly. When you think in sets, you naturally start asking better questions of yourself. Which collection of records am I describing? Is a single real world thing represented once in that collection, or could it appear more than once? If I add a condition, am I making the set smaller or am I accidentally making it larger? These are answerable questions. The walking question, which record comes next, is not answerable and was never worth asking. Let it go early and the rest of this subject becomes considerably less mysterious than it first appears.