LIMITED TIME OFFER: 50% OFF OF PREMIUM WITH OUR ANNUAL PLAN (THAT'S $294 IN SAVINGS).
GET OFFER

SQL - Querying rows from GROUP BY

Screen Link:

My Code:

    (SELECT * FROM customer_usa
     
    INTERSECT
     
    SELECT * FROM customer_gt_90_dollars )
    
SELECT 
    e.first_name || " " || e.last_name employee_name,
    COUNT(u90.customer_id) customers_usa_gt_90

FROM employee e
LEFT JOIN usa_gt_90 u90 ON u90.support_rep_id = e.employee_id
WHERE e.title = "Sales Support Agent"
GROUP BY 1 ORDER BY 1;

What I expected to happen:
I was expecting an error because I was about using WHERE on a virtual table generated by the GROUP BY clause.

What actually happened:
There was no ERROR!

Please I need more insight on the use of HAVING vs WHERE

Thanks in advance.

Hii @austin-deccentric,

WHERE clause is executed before GROUP BY clause. So here query will filter out title then it will group by rows with employee name.

Rule of thumb for having vs where:
use where when you want to filter data before any other clause and use having when you want to filter data after execution of other clauses.

I recommend checking these two articles.

Having vs Where

Execution order of SQL clauses

Hope it helps!!

3 Likes

Thanks for the reply. This helped a lot.

1 Like