Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');The query as written:
sql
SELECT dept_id, AVG(salary) AS avg_sal FROM employees WHERE avg_sal > 60000 GROUP BY dept_id; -- error on purposetext
Error: misuse of aggregate: AVG()SQLite resolves the alias to the AVG() expression and reports a misuse of aggregate, because WHERE filters individual rows before any average is computed. PostgreSQL gives a 'column does not exist' error for the same reason (not run here).
A corrected version:
sql
SELECT dept_id, ROUND(AVG(salary), 1) AS avg_sal FROM employees GROUP BY dept_id HAVING AVG(salary) > 60000 ORDER BY dept_id;| dept_id | avg_sal |
|---|---|
| 1 | 103333.3 |
| 2 | 66000.0 |
HAVING runs after grouping, so the average exists. Departments 1 and 2 pass; department 3 averages 51500, and Lena's NULL department has a NULL average and is dropped. Repeating AVG(salary) in HAVING is portable; PostgreSQL does not accept the alias there.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
-- error on purpose
SELECT dept_id, AVG(salary) AS avg_sal FROM employees WHERE avg_sal > 60000 GROUP BY dept_id;
SELECT dept_id, ROUND(AVG(salary), 1) AS avg_sal FROM employees GROUP BY dept_id HAVING AVG(salary) > 60000 ORDER BY dept_id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- WHERE runs before grouping and aliases
- HAVING filters groups
- Repeat the aggregate for portability
Common mistakes
- Wrapping the query in a subquery only to reuse an alias, when HAVING suffices
- Using HAVING for row filters that belong in WHERE
Follow-ups
- In what order are SELECT clauses evaluated?
- Can ORDER BY use the alias?
Tips
- Explain logical evaluation order