BETWEEN & IN
Two shorthands. Neither lets you ask anything you could not already ask with and and or — they just say it in a way that is shorter to write and much easier to read.
1BETWEEN — a range
That is exactly the same question as:
between. A student scoring exactly 70 is in, and so is one scoring exactly 90. Read it as “from 70 to 90 inclusive”, not “strictly between”. Exam questions are written to catch you on precisely this.The smaller value must come first. between 90 and 70 is valid SQL but finds nothing, because no number is both at least 90 and at most 70.
2BETWEEN works on dates too
Anything that can be compared can be given a range, so this is the neat way to ask for a period of time:
— everyone born in 2009, both ends of the year included. It is shorter and clearer than two conditions joined with and.
3NOT BETWEEN
Everyone outside the range, at either end. Four rows in the range plus six outside makes ten — not twelve, because Bhim and Pema have NULL percentages and fall out of both, exactly as they did with <> in the last lesson.
4IN — a list of values
The same question written the long way:
With two values the saving is small. With six it is the difference between a readable query and a mess — and the column name is written once instead of six times, so there is one place to get it wrong instead of six.
in (70, 90) means exactly 70 or exactly 90 — two values. between 70 and 90 means everything from 70 to 90. Mixing these up is a common slip; the brackets and commas of in are the reminder that it is a list.5NOT IN
Six students from anywhere else — and once again the two with a NULL city are in neither list.
6Recap
A range, with BOTH ends included. Same as >= a and <= b.
A list of exact values. Same as = v1 or = v2 or …
The opposite in each case.
As always — a row with NULL matches neither the condition nor its negation.
A student scores exactly 70. Is the row returned by where percent between 70 and 90?
Which is equivalent to where city = 'Gangtok' or city = 'Namchi'?
What does where grade in (9, 12) return?