SQL Server > Query

Sub query (nested query) in SQL Server

How to use sub-query to return data from SQL Server database?


Sub query can be used to a get data from another database table along with current database table used in the main query.

SELECT FullName = (SELECT FirstName + ' ' + LastName FROM PersonalDetails WHERE PersonalDetailsId = 
ac.PersonalDetailsId)
, Salary, PPFDeduction, NetSalary FROM Accounts ac

Above query returns FullName from PersonalDetails table (combination of FirstName and LastName) and Salary, PPFDeduction and NetSalary from Accounts table. Notice the alias “ac” used for Accounts table.

In case, no records found in PersonalDetails table, null value would be returned for FullName column.

 Views: 1514 | Post Order: 48



Write for us