Reputation: 1131
I have a query (simplified), that computes C
:
SELECT A + B AS C FROM Foo
The query returns 0.5 million rows.
I need to select rows where C < 0.3. To do this I insert the results into a temporary table #Bar
INSERT INTO #Bar
SELECT A + B AS C FROM Foo
And apply the condition
SELECT *
FROM #Bar
WHERE C < 0.3
According to the execution plan Table Insert
costs 86%. Is there a better way to get C < 0.3
?
I've tried a nested query, and it's the same.
Upvotes: 0
Views: 82
Reputation: 2016
All solutions work fine above. I just added third option with common table expression that serves a view and it is a bit easier to read.
;WITH CTE_SELECT AS
(
SELECT A, B, C = A + B
FROM Foo
WHERE A + B < 0.3
)
SELECT * FROM CTE_SELECT
Upvotes: 1
Reputation: 77886
You can do it in a single query like
SELECT C FROM
(
SELECT A + B AS C FROM Foo
) bar
WHERE C < 0.3
(OR) Include the condition in WHERE
SELECT A + B AS C FROM Foo
WHERE A + B < 0.3
Upvotes: 0
Reputation: 460168
You don't need the temp table at all, just select what you want:
SELECT A, B, C = A + B
FROM Foo
WHERE A + B < 0.3
Upvotes: 4