Загрузка...

SQL Trap: WHERE vs HAVING with GROUP BY (Interview Question Explained)

Most SQL interviews quietly test if you really understand WHERE vs HAVING with GROUP BY – and if you mix them up, your answer is either wrong or you hit errors.



In this video, we take a simple Sales table with region, sale_month, and amount and solve this real interview‑style question:

“Show each region’s total sales, but only keep the regions whose total sales are greater than 10,000.”

You’ll see:
– Why WHERE SUM(amount) greater than 10000 doesn’t work.
– Why WHERE amount greater than 10000 is syntactically correct but logically wrong for the question.
– The correct solution using HAVING SUM(amount) greater than 10000 after GROUP BY region.
– How the order of execution works: FROM → WHERE → GROUP BY → HAVING → SELECT.



We then go further and show:
– When to use WHERE (row‑level filter).
– When to use HAVING (aggregate/group‑level filter).
– How to combine WHERE, GROUP BY, and HAVING in one query for questions like “only January sales greater than 5,000 per region”.



This is a must‑know concept for SQL interviews (data analyst, data engineer, BI, backend dev) and for writing correct reports in real projects.


🔽 Try it yourself
I’ve used a simple Sales table with regions (North, South, East, West) and monthly amounts. You can recreate it with the script in the comments/description and practice the queries shown in this video.



If this helped you finally understand WHERE vs HAVING, like the video, subscribe to SQLWithAsif, and share it with someone preparing for SQL interviews.

#sql #sqltutorial #sqlinterview #sqlwithasif #wherevshaving #groupby #dataanalytics #dataengineer


Script for table
-- Drop if exists (SQL Server syntax; remove if not needed)
IF OBJECT_ID('dbo.Sales', 'U') IS NOT NULL
DROP TABLE dbo.Sales;

-- Base table
CREATE TABLE dbo.Sales (
sale_id INT IDENTITY(1,1) PRIMARY KEY,
region VARCHAR(20),
sale_month VARCHAR(10),
amount INT
);

-- Sample data
INSERT INTO dbo.Sales (region, sale_month, amount) VALUES
-- North: total 11,000
('North', 'Jan', 4000),
('North', 'Feb', 7000),

-- South: total 12,000
('South', 'Jan', 3000),
('South', 'Feb', 9000),

-- East: total 3,500
('East', 'Jan', 2000),
('East', 'Feb', 1500),

-- West: total 13,000
('West', 'Jan', 6000),
('West', 'Feb', 7000);

Видео SQL Trap: WHERE vs HAVING with GROUP BY (Interview Question Explained) канала SQLWithAsif
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять