Friday, December 28, 2007

SQL, WHERE clause vs. JOIN clause conditions...

Today I found that there's a difference between the a condition in the WHERE clause and in the JOIN clause in a SQL Statement. Now, I realize there really isn't a difference, but in this case...it made all the difference.

Here's an approximation of the original SQL:
SELECT A.id_a, B.id_B
FROM apple A
LEFT JOIN banana B ON B.id_a = A.id_a
WHERE GetDate() BETWEEN B.start_date AND B.end_date

The idea here is to obviously only get the records where the current date falls in the range provided by the Banana table record. This worked great in all my scenarios where I had a Banana record. When I went to try it on a set of Apple records that did not have corresponding Banana record, I got no results at all.

So I took the WHERE clause (or the line containing the date check) and placed it on the LEFT JOIN clause, like so:
SELECT A.id_a, B.id_B
FROM apple A
LEFT JOIN banana B ON B.id_a = A.id_a AND GetDate() BETWEEN B.start_date AND B.end_date

Now it only applies to excluding out of range records in the JOIN only, rather than applying to the result set as a whole. In the initial flavor of the SQL statement, the date comparison would be made against two NULL values for the date fields. The Banana record requires those date values if it exists, but I want Apple records even if there is no corresponding Banana record, and do no date comparison at all. Only exclude the Banana record if the dates are out of range.

Just a gotcha to keep an eye out for!

- Will Belden
Friday, December 28, 2007