SQL Server Select From Nested Select Statements

Sometimes rather than returning a table column its necessary to Select from nested Select statements. Below is a sample of using such a query:

                                        
 SELECT (
	SELECT COUNT(*)
	FROM usersTbl
	WHERE userName LIKE '%Dave%'
	) as 'Matching User Count',
	(
	SELECT TOP 1 firstName
	FROM usersTbl
	WHERE firstName LIKE 'D%'
	ORDER by firstName
	) as 'First User starting with "D"'

 Result:

 Matching User Count First User starting with "D"
 ------------------- ------------------------------
 2                   d

 (1 row(s) affected)

                                        

This type of query is useful in cases where you need to perform a unique Group function or filter on each of the returned columns to get the desired values. It's important to realize that when this method is used each of the nested Select statements must only return one row, otherwise an error will be returned.


© 2024 Embrs.net