views:

38

answers:

3

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.

+2  A: 

Yes you can

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

Just remember to give the sub select an alias.

astander
Not much point in the alias if you don't use it ;)
OMG Ponies
Morning Ponies. The query will not compile if you leave out the table alias... X-)
astander
I've only had that experience with MySQL - gonna test that tomorrow
OMG Ponies
Just did it on my PC... **Msg 156, Level 15, State 1, Line 12 Incorrect syntax near the keyword 'WHERE'.**
astander
Morning?! Ah, cuz you're in South Africa. It's 9ish PM here in Canada
OMG Ponies
Thanks, that why I always get an error.
Yongwei Xing
+1  A: 

Yes, you can do that.

Jose Chama
A: 

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.

Joe Swan