Sunday, March 11, 2012

Does 'Group By' affect the query speed?

i have a table such sa below:

Name1, Name2, Name3, Nam4, C1, C2,.., C100

and in this table, i have found index for Name1-Nam4,

i don't why sql below is very slow?

select
Name1, sum(C1), ...., Sum(C100)
from
(
select
Name1, Name2, sum(C1) as C1, ...., Sum(C100) as C100
from
(
select
Name1, Name2, Name3, sum(C1) as C1, ...., Sum(C100) as C100
from
(
select
Name1, Name2, Name3, Name4, C1, ...., C100
from
My_Table
group by Name1, Name2, Name3, Name4
) as T
group by Name1, Name2, Nam3
) as T
group by Name1, Name2
) as T
group by Name1

Does 'Group By' affect the speed of query?

Yes... It depends with your number of data...

I found your query is strange...

Why not, can you try the following query..

select
Name1, sum(C1), ...., Sum(C100)
from
My_Table
group by Name1

Bcs.. finally you are going to get only the Name1 data...

If you need kind of Rolling up data... use ROLLUP instead of multiple Subqueries...

No comments:

Post a Comment