Skip to content
Quantoros

How does HAVING differ from WHERE when using aliases?

SQLLevel: IntermediateAggregations & GROUP BY

How does HAVING differ from WHERE when using aliases?

Hints
  • Define one output row and the source-table keys.
  • Check duplicates, NULLs and the order of filtering and aggregation.

Answer

В PostgreSQL псевдоним из SELECT нельзя использовать ни в WHERE, ни в HAVING. WHERE фильтрует исходные строки, HAVING — группы. Повторите выражение либо вынесите его в подзапрос:

SELECT department, SUM(salary) AS total_sal
FROM employees
GROUP BY department
HAVING SUM(salary) > 100000;

Псевдонимы SELECT разрешены в PostgreSQL в ORDER BY и GROUP BY. Возможности других диалектов не следует переносить на PostgreSQL автоматически.

Source and licence: SQL Interview Questions — Arda Kocadoru · MIT · answer: Quantoros editorial

Related questions