Tuesday, 16 July 2013

Concept of Derived tables in sqlserver


  • Derived tables, also known as subqueries, are defined in the FROM clause of an outer query. 
  • Their scope of existence is in the outer query, when the outer query is finished the derived table goes away. 
  • A derived table is defined in parenthesis followed by an AS clause to specify the derived table name. 


For e:g

SELECT LastName, EmployeeId
FROM
 (SELECT FROM Employee
  WHERE Country = 'Australia'AS EmployeeDerivedTable
WHERE DepartmentId = 33
ORDER BY LastName

Here EmployeeDerivedTable is the derived table name.

Difference between temporary table and derived table
  • In case of temporary table, first we have to create a temporary table,  insert the data into the table, select the data from the temporary table and then we have to drop the temporary table. 
  • But in case of derived table, SQL Server itself create and populate the table in the memory and we can directly use it. Also we don,t need to drop it. But it can only be referenced  by the outer Select query who created it.
  •  Also since it is reside in the memory itself, it is faster then Temporary tables which are created in the temp database.

Difference between subquery and derived table
  • derived tables are used in the FROM clause
  • subqueries are used in the WHERE clause

No comments:

Post a Comment