TGViewer
Data Analytics Data Analytics @sqlspecialist ยท 111K subscribers
Post #2915 4.83K
๐—œ๐—ป๐˜๐—ฒ๐—ฟ๐˜ƒ๐—ถ๐—ฒ๐˜„๐—ฒ๐—ฟ:
You have 2 minutes to solve this SQL query.
Find the departments where the average salary is greater than the company's overall average salary.

๐— ๐—ฒ: Challenge accepted! ๐Ÿ’ช
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > (
SELECT AVG(salary)
FROM employees
);

๐Ÿ’ก Explanation:
The query compares each department's average salary with the company's overall average salary.

โ€ข GROUP BY department calculates the average salary for each department.
โ€ข The subquery computes the overall average salary across all employees.
โ€ข HAVING filters only those departments whose average salary exceeds the company average.

This question tests your understanding of:
โœ… GROUP BY
โœ… HAVING
โœ… Aggregate Functions AVG
โœ… Subqueries

๐ŸŽฏ Expected Output Example
Department: Average Salary
IT: 88,500
Finance: 84,000

HR is excluded because its average salary is below the company average.

๐Ÿš€ Alternative Using a Common Table Expression CTE
WITH company_avg AS (
SELECT AVG(salary) AS avg_salary
FROM employees
)
SELECT
department,
AVG(salary) AS average_salary
FROM employees, company_avg
GROUP BY department, company_avg.avg_salary
HAVING AVG(salary) > company_avg.avg_salary;

Using a CTE can improve readability, especially when the same calculated value is reused in larger queries.

๐Ÿš€ Tip for SQL Job Seekers:
Interviewers often ask questions that compare group-level aggregates with overall aggregates. Master the use of HAVING with subqueriesโ€”itโ€™s a key SQL pattern.

โค๏ธ React with โค๏ธ for more SQL interview challenges!
  • โค 12
More from @sqlspecialist
  1. Oct 8, 2026๐ŸŽ“ ๐— ๐—ถ๐—ฐ๐—ฟ๐—ผ๐˜€๐—ผ๐—ณ๐˜ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ ๐˜„๐—ถ๐˜๐—ต ๐—–๐—ฒ๐—ฟ๐˜๐—ถ๐—ณ๐—ถ๐—ฐ๐—ฎ๐˜๐—ฒ๐˜€! ๐Ÿš€๐Ÿ”ฅ Upgrโ€ฆ
  2. Oct 7, 2026๐Ÿ“Š Kandinsky 6.0 Video: AI-Powered Content Creation for Analysts The new Kandinsky 6.0 Vidโ€ฆ
  3. Oct 7, 2026Alternatively, depending on the Excel version and requirement, I could use functions suchโ€ฆ
  4. Oct 7, 2026๐Ÿ“Š Data Analyst Interview Series โ€” Part 5 Guys, let's continue our Data Analyst Interviewโ€ฆ
  5. Oct 7, 2026๐Ÿš€๐—ฃ๐—ฎ๐˜† ๐—”๐—ณ๐˜๐—ฒ๐—ฟ ๐—ฃ๐—น๐—ฎ๐—ฐ๐—ฒ๐—บ๐—ฒ๐—ป๐˜ ๐—ง๐—ฟ๐—ฎ๐—ถ๐—ป๐—ถ๐—ป๐—ด | ๐—•๐—ฒ๐—ฐ๐—ผ๐—บ๐—ฒ ๐—ฎ ๐—™๐˜‚๐—น๐—น๐˜€๐˜๐—ฎ๐—ฐโ€ฆ
  6. Oct 7, 2026๐Ÿ”Ÿ What is the difference between UNION and JOIN? Sample Answer: "JOIN combines columns frโ€ฆ
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook โ†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 โ†’