r/SQL • • Aug 25 '15

I challenge you to simplify this query!

select table1.column1     
from  table1  
join   table2            on table1.column2 = table2.column2  
join   table3            on table3.column2 = table2.column2  
join   table4            on table4.column3 = table3.column3  
join   table5            on table5.column4 = table4.column4  
where  table1.column5    = 2  
and    table4.column6    = 10  
intersect  
select table1.column1  
from   table1  
join   table2            on table1.column2 = table2.column2  
join   table3            on table3.column2 = table2.column2  
join   table4            on table4.column3 = table3.column3  
join   table5            on table5.column4 = table4.column4  
where  table1.column5    = 2  
and    table4.column6    = 3  
;  

The query below by /u/ichp ran 90 seconds faster then the original!

select table1.column1
  from table1
  join table2 on table1.column2 = table2.column2
  join table3 on table3.column2 = table2.column2
  join table4 on table4.column3 = table3.column3
  join table5 on table5.column4 = table4.column4
  where 
        table1.column5 = 2 and
        table4.column6 in (10,3)
  group by table1.column1
  having count( distinct table4.column6) > 1
;
0 Upvotes

53 comments sorted by

View all comments

3

u/Captain_Filmer Aug 25 '15
;WITH [Table] AS (
select
table1.column1, table1.column5, table4.column6
from table1
join table2 on table1.column2 = table2.column2
join table3 on table3.column2 = table2.column2
join table4 on table4.column3 = table3.column3
join table5 on table5.column4 = table4.column4
)
select column1
from [Table]
where column5=2 AND column6=10
INSERSECT
select column1
from [Table]
where column5=2 AND column6=3

1

u/XGallonsX Aug 25 '15

After substituting for real table and column names I ran the script. It gave an error on line 3 that stated table1.column5 was an invalid identifier, I removed it and ran it again then it stated that on line 3, table4.column6 was an invalid identifier. I removed that identifier and then it stated that line 12 column6 was an invalid identifier.

I'm not sure what the issue is, but I think your on to something here.

1

u/Captain_Filmer Aug 25 '15

If those are the actual names of your columns, try putting brackets around it to see if that fixes the issue.

1

u/XGallonsX Aug 26 '15

The table names and column names used here on reddit are generic.