patternsqlMinor
SUM same column twice performance
Viewed 0 times
sametwicecolumnperformancesum
Problem
DBMS: SQL Server 2012 Express
I have an SQL Statement which looks something like this:
I was wondering does Adding the same column twice cause an impact on Performance? Meaning does SQL Server add the column twice? Or will it add the column once and use for both columns in the result set?
Or should I use a CTE with one
I have an SQL Statement which looks something like this:
SELECT
OverSpeedings = SUM(OverSpeeding),
OverspeedingPoints = SUM(OverSpeeding) * 5,
FROM
MyTable
GROUP BY
COLUMNS_HEREI was wondering does Adding the same column twice cause an impact on Performance? Meaning does SQL Server add the column twice? Or will it add the column once and use for both columns in the result set?
Or should I use a CTE with one
SUM like the following:SELECT
OverSpeedings,
OverspeedingPoints = OverSpeedings * 5,
FROM
(
SELECT
OverSpeedings = SUM(OverSpeeding)
FROM
MyTable
GROUP BY
COLUMNS_HERE
) ASolution
was wondering does Adding the same column twice cause an impact on Performance? Meaning does SQL Server add the column twice? Or will it add the column once and use for both columns in the result set?
Sum will be calculated once and result is used for multiple columns referring the same
Below is sample setup from my instance ,which will prove the same
execution plan:
In the above execution plan,highlighted computed scalar shows below
Where
should I use a CTE with one SUM like the following
CTE is just for readability,using a CTE won't help performance .
There are cases where materialzing CTE will help in improving the query.Look out this answer for more details:
Which are more performant, CTE or temporary tables?
Sum will be calculated once and result is used for multiple columns referring the same
sumBelow is sample setup from my instance ,which will prove the same
select
sum(empid) as empidsum,
sum(empid)*2 as empidsum,
sum(empid)*4 as empid4
from ordersexecution plan:
In the above execution plan,highlighted computed scalar shows below
Scalar Operator([Expr1003]*(2))
Scalar Operator([Expr1003]*(4))Where
Expr1003 is the sum calculated by previous compute scalarshould I use a CTE with one SUM like the following
CTE is just for readability,using a CTE won't help performance .
There are cases where materialzing CTE will help in improving the query.Look out this answer for more details:
Which are more performant, CTE or temporary tables?
Code Snippets
select
sum(empid) as empidsum,
sum(empid)*2 as empidsum,
sum(empid)*4 as empid4
from ordersScalar Operator([Expr1003]*(2))
Scalar Operator([Expr1003]*(4))Context
StackExchange Database Administrators Q#164667, answer score: 6
Revisions (0)
No revisions yet.