K
K
KiT2016-12-11 22:26:26
MySQL
KiT, 2016-12-11 22:26:26

Why do aliases from SELECT work in HAVING?

I read that column aliases cannot be used in the WHERE clause because the query is processed according to the scheme:

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. ORDER BY

Thus, at the time the WHERE is processed, the aliases defined in the SELECT have not yet been assigned.
Indeed, the query...
SELECT model AS PcModel FROM PC
WHERE PcModel > 22
...gives the error "Lookup Error - MySQL Database Error: Unknown column 'PcModel' in 'where clause"
---------- ---------------------------
The essence of the question:
Following the voiced logic, I assumed that the aliases in HAVING should also generate this error, but the request. ..
SELECT model, MAX(price) AS PcPrice FROM PC
GROUP BY model
HAVING PcPrice > 800;
... calmly works.
Please explain why so? After all there should be an error as HAVING is fulfilled before SELECT.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
index0h, 2016-12-12
@index0h

HAVING is intended for post-filtering data, not for primary. One of the main reasons why it is written after GROUP BY. Due to GROUP BY, you have calculated fields by the functions GROUP_CONCAT, MAX, MIN, SUM, ... Filtering by these calculated fields is performed by HAVING.

S
Sumor, 2016-12-11
@Sumor

HAVING imposes conditions on an already executed and selected query, which already has aliases, and everything else works before the final issuance, where there are no aliases yet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question