in reply to SQL JOINs vs WHERE statements
You're not crazy, you can indeed get an equivalent join using a WHERE clause.
But I don't recommend it.
It mixes up your different types of clauses (JOIN vs WHERE), which makes your SQL harder to understand, and worse, you can get unintuitive results.
For example, what would you expect the following to return?
Would you be surprised to get the following results?create table people (person_id integer not null primary key, surname v +archar(40) not null) insert into people values (1,'Smith') insert into people values (2,'Jones') insert into people values (3,'Harry') insert into people values (4,'Peanut') create table town (person_id integer not null references people(person +_id), town varchar(40) null) insert into town values (1,'Bristol') insert into town values (2,'Washington') insert into town values (3,NULL) insert into town values (4,'Cairns') SELECT surname, town FROM people, town WHERE people.person_id *= town.person_id AND (town <> 'Washington' AND town IS NOT NULL)
surname town + ------------------------------ --------------------------------------- +- Smith Bristol Jones NULL Harry NULL Peanut Cairns
(Hint: You should be surprised, the SELECT was trying to exclude NULLS)
The source of this ambiguity is that the IS NOT NULL part of the WHERE clause got evaluated before the join part, and the join part then re-introduced the NULLs.
In contrast, the LEFT OUTER JOIN makes the intention clearer (albeit somewhat self-defeating in this example)
SELECT surname, town FROM people LEFT OUTER JOIN town ON people.person_id = town.person_id WHERE (town <> 'Washington' AND town IS NOT NULL)
Results:
Update: It seems that Oracle gives different results to MS SQL Server 2000, where this code was tested.surname town + ---------------------------------------- ----------------------------- +----------- Smith Bristol Peanut Cairns
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: SQL JOINs vs WHERE statements
by bean (Monk) on Aug 19, 2003 at 19:00 UTC | |
by EdwardG (Vicar) on Aug 19, 2003 at 19:28 UTC | |
by bean (Monk) on Aug 19, 2003 at 20:57 UTC |