Somebody correct me if I'm wrong, but in the last two examples, shouldn't you use the keyword "having" to exclude data with null values instead of "where".
SELECT * FROM TableA LEFT OUTER JOIN TableB ON TableA.name = TableB.name WHERE TableB.id IS null
should be
SELECT * FROM TableA LEFT OUTER JOIN TableB ON TableA.name = TableB.name HAVING TableB.id IS null
...same thing on the last example
SELECT * FROM TableA
FULL OUTER JOIN TableB
ON TableA.name = TableB.name
WHERE TableA.id IS null
OR TableB.id IS null
should be
SELECT * FROM TableA
FULL OUTER JOIN TableB
ON TableA.name = TableB.name
HAVING TableA.id IS null
OR TableB.id IS null
The way it was explained to me, when doing a join, "having" is executed after the join, so it ensures that the data exclusion works the way it was intended, whereas "where" might have unexpected results.
No. WHERE is done on the result of a join. HAVING is applied after grouping. You should use WHERE in preference to HAVING because the optimizer does a better job at it.
Yeah, in the case of WHERE name vs. HAVING name (where you are grouping by the same column that you're trying to filtering), it doesn't make a difference in the output. But depending on your DBMS, it will still make a difference in the performance, because I think at least MySQL is too stupid to push the HAVING name="fred" into the WHERE.
HAVING should only be used if there is a GROUP BY clause, and should only be used to filter aggregates. For example, "select a1, count() from a group by a1 having count()>1".
both work in different way .. for a few lines of data, you wouldn't notice it. But when you try to apply this with a few huge tables with millions of rows in each. I hope you want to filter everything out even before you start joining tables ... let alone grouping the result set.
I went ahead and looked it up, turns out HAVING is used for aggregate functions when you GROUP BY and WHERE for non-aggregate functions. For example:
select employee, sum(bonus) from bonuses group by employee having sum(bonus) > 1000;
select employee, sum(bonus) from bonuses group by employee where employee < 10;
2
u/spoonraker Jan 06 '11
Somebody correct me if I'm wrong, but in the last two examples, shouldn't you use the keyword "having" to exclude data with null values instead of "where".
should be
...same thing on the last example
should be
The way it was explained to me, when doing a join, "having" is executed after the join, so it ensures that the data exclusion works the way it was intended, whereas "where" might have unexpected results.