Conditions, Patterns & NULLs
Four operators appear in the SQL section of almost every paper: between, in, like and is null. They are worth practising together because the examiner picks between them deliberately — the wording of the question tells you which one is wanted.
1BETWEEN — a range, both ends included
25000 and 50000.▶Show the answer
Identical to salary >= 25000 and salary <= 50000. Either earns the mark.
between is inclusive at both ends, which is the single most common slip. Counting the employees between 26000 and 58000 gives nine, and that count contains both Bina Sharma on exactly 26000 and Arun Thapa on exactly 58000:2IN — one of a list
▶Show the answer
The long form — where job = 'Clerk' or job = 'Analyst' — is equally correct and equally accepted.
▶Show the answer
Six and six, adding to all twelve employees — which works here only because no employee has a NULL job. Where a column does hold NULLs, a condition and its negation do not add up to the whole table. That trap has its own question on the Predict the Output page.
3LIKE — matching a pattern
Two wildcards, and papers test both: % stands for any number of characters (including none), and _ stands for exactly one.
A.▶Show the answer
a.▶Show the answer
ra anywhere.▶Show the answer
Chandan Rai matches on the space-then-Ra of the surname: the default collation here is case-insensitive, so ra also matches Ra.
i and which start with any single character followed by ina.▶Show the answer
One underscore, one character. _ina% means: anything for the first letter, then i, n, a, then anything at all.
4LIKE works on dates too
A date is stored as YYYY-MM-DD, so a pattern can pick out a year, a month or a day without any date function at all.
▶Show the answer
where year(doj) = 2019 gives the same answer and is the clearer way to say it — but year() is a date function, which is on the Informatics Practices syllabus and not the Computer Science one. The like form works for everybody.
5IS NULL — the one that will not use =
▶Show the answer
▶Show the answer
where bonus = null does not fail. It quietly matches nothing, so you get an empty answer and no clue why:6Reading the question
between — and remember both ends count
in ('A','B') — or a chain of or
like with % and _
is null — never = null
How many employees does 'salary between 26000 and 58000' match, given salaries of exactly 26000 and exactly 58000 exist?
Which pattern finds names whose second character is 'i'?
What does 'where bonus = null' return?