SQL Child / Thinking In Sets

The Question Comes First, The Query Comes Second

Most bad answers begin as vague questions that nobody bothered to make precise.

Try this before you touch anything. Write your question down in one sentence, in ordinary language, as though you were asking a knowledgeable colleague who has no access to the data. How many customers bought something last month. That sounds complete. It is not. Does a customer who bought four times count once or four times? Does last month mean the calendar month, or the last thirty days? Does bought mean the order was placed, or paid for, or delivered, or not later cancelled? Each of those choices produces a different, defensible number, and you have to make them whether you notice or not.

The value of writing the sentence down is that it forces the ambiguity into the open while it is still cheap to resolve. If you skip this step, you do not avoid the choices. You simply make them by accident, in the middle of building the request, without recording what you decided. Then three weeks later somebody asks why your figure differs from theirs and neither of you can reconstruct the difference, because the definitions were never written anywhere. Two correct answers to two different questions look exactly like one correct answer and one wrong one.

So make the sentence exact and keep it. Put it at the top of your working file, in plain words, with the decisions spelled out: distinct customers, calendar month, orders placed and not cancelled. Now your request has a specification to be checked against, and so do you. When the answer comes back, you can hold it up next to the sentence and ask whether it really answers that. Surprisingly often it does not, and you will catch it yourself, which is far more comfortable than being caught by somebody else.