Yongwei Xing
Yongwei Xing

Reputation: 13441

Can I use the sub-query in the FROM in T-SQL?

Can I write the T-SQL like below

select *
 FROM (select * 
        from TableA 
       where FieldA = 1
       )
where FieldB > 10

which means I want to query from the results of another query.

Upvotes: 2

Views: 73

Answers (3)

Joe Swan
Joe Swan

Reputation: 200

If you want to separate out your sub-queries you can also use Common Table Expressions (CTE's) which help make your code more readable:

WITH Foo (FieldA, FieldB, FieldC) AS
(
    SELECT FieldA, FieldB, FieldC
    FROM TableA
    WHERE FieldA=1
)

SELECT *
FROM Foo
WHERE FieldB > 10

The downside is you will have to explicitly name your columns. However, this actually makes your code faster so it's not always a bad thing.

Upvotes: 0

Jose Chama
Jose Chama

Reputation: 2978

Yes, you can do that.

Upvotes: 1

Adriaan Stander
Adriaan Stander

Reputation: 166356

Yes you can

select * 
FROM  ( select * from TableA where FieldA=1 ) sub
where FieldB > 10

Just remember to give the sub select an alias.

Upvotes: 2

Related Questions