Question : Difference between the way a sql query is written

Can someone explain to me :
1) what the difference is between the way the two queries are written (higlighted in bold text), 2) why is the result set different and
3) what would be a more efficient way of writting the 1st query so that is runs faster, currently it takes over 3 minutes to run.

SELECT DISTINCT   f1,f2,f3
Case when f3='0'  then f3
Else f2 END as orig,
SUM(gry) AS gt,
FROM        dbo.vent left join old on vent.id = old.id and vent.num = '0'
Where state in ('A','B','C','D','F')
GROUP BY      f1,f2,f3
order by f1            

VS.

SELECT DISTINCT   f1,f2,f3
Case when f3='0'  then f3
Else f2 END as orig,
SUM(gry) AS gt,
FROM        dbo.vent left join old on vent.id = old.id
Where state in ('A','B','C','D','F')  and vent.num = '0'
GROUP BY      f1,f2,f3
order by f1      

      

Answer : Difference between the way a sql query is written

Just so you can see, and also see how it is predictable...

Check out the little test below :

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
create table #vent (id int, num int, comments varchar(100))
create table #old (id int, comments varchar(100))

insert #vent values (1,0,'Shows up anyway')
insert #vent values (2,1,'Shows up if vent=0 in join')
insert #vent values (3,0,'Shows up anyway')
insert #vent values (4,1,'Shows up if vent=0 in join')
insert #vent values (5,0,'Shows up anyway')

insert #old values (1,'shows up anyway')
insert #old values (2,'never shows')
insert #old values (3,'shows up anyway')
insert #old values (4,'never shows')
GO
-- query1
select *
from #vent
left join #old on #old.id = #vent.id and #vent.num = 0

-- query2
select *
from #vent
left join #old on #old.id = #vent.id 
where #vent.num = 0
GO

/*
-- query 1
id   num  comments
1    0    Shows up anyway               1    shows up anyway
2    1    Shows up if vent=0 in join    NULL NULL                 -- note how the join doesnt show any #old columns because only join if num = 0
3    0    Shows up anyway               3    shows up anyway
4    1    Shows up if vent=0 in join    NULL NULL                 -- note how the join doesnt show any #old columns because only join if num = 0
5    0    Shows up anyway               NULL NULL                 -- there isnt a id = 5 in #old

-- query 2
id   num  comments
1    0    Shows up anyway               1    shows up anyway
3    0    Shows up anyway               3    shows up anyway
5    0    Shows up anyway               NULL NULL

*/
Random Solutions  
 
programming4us programming4us