As others have (mostly) correctly stated, in SQL the WHERE
clause is evaluated before the SELECT
clause, therefore the result of a set function is 'out of scope' in the WHERE
clause.
For example, you CANNOT do this:
SELECT Subject, MAX(Mark) AS TopScore
FROM Exam_Marks
GROUP
BY Subject
WHERE TopScore <= 70;
because the column correlation name TopScore
is not in scope for the WHERE
clause.
Of course we could use a subquery:
SELECT DT1.TopScore
FROM (
SELECT Subject, MAX(Mark) AS TopScore
FROM Exam_Marks
GROUP
BY Subject
) AS DT1
WHERE DT1.TopScore <= 70;
The problem was, early implementations of SQL (starting with IBM's System R) lacked support for derived tables, hence the unintuitive HAVING
was born.
You can read the whole sorry story in HAVING A Blunderful Time (or Wish You Were WHERE) by Hugh Darwen, from which I've borrowed the above examples.