unit 5 seminar n.
Skip this Video
Download Presentation
Unit 5 Seminar

Loading in 2 Seconds...

play fullscreen
1 / 52

Unit 5 Seminar - PowerPoint PPT Presentation

  • Uploaded on

Unit 5 Seminar. Derived Table. A derived table is a virtual table that’s calculated on the fly from a select statement.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Unit 5 Seminar' - zasha

Download Now An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
derived table
Derived Table
  • A derived table is a virtual table that’s calculated on the fly from a select statement.
  • The biggest benefit of using derived tables over using temporary tables is that they require fewer steps, and everything happens in memory instead of a combination of memory and disk.
derived table1
Derived Table
  • The fewer the steps involved, along with less I/O, the faster the performance.
  • Problem:

Generate a report that shows off the total number of orders each customer placed in 1996

derived table2
Derived Table
  • SELECT C.CustomerID, C.CompanyName, COUNT(O.OrderID) AS TotalOrdersFROM Customers C LEFT OUTER JOIN Orders O ONC.CustomerID = O.CustomerIDWHERE YEAR(O.OrderDate) = 1996GROUP BY C.CustomerID, C.CompanyName
problem with previous query
Problem with previous query
  • But there’s something missing. Customers that didn’t place an order in 1996 aren’t showing up.
derived table cont
Derived Table (cont)
  • SELECT C.CustomerID, C.CompanyName,COUNT(O.OrderID) AS TotalOrdersFROM Customers C LEFT OUTER JOIN Orders O ONC.CustomerID = O.CustomerIDWHERE (YEAR(O.OrderDate) = 1996 OR O.OrderDate IS NULL)GROUP BY C.CustomerID, C.CompanyName
problem with is null version
Problem with is null version
  • If a customer has placed an order, but just not in the year 1996 they won’t show up. This is because the “is null” check finds customers that have never placed an order—it still doesn’t do anything to add customers who’ve placed an order, but just not in 1996.
derived table cont1
Derived Table (cont)
  • SELECT C.CustomerID, C.CompanyName,COUNT(dOrders.OrderID) AS TotalOrdersFROM Customers C LEFT OUTER JOIN/* start our derived table */(SELECT * FROM Orders WHERE YEAR(Orders.OrderDate) = 1996) AS dOrders/* end our derived table */ONC.CustomerID = dOrders.CustomerIDGROUP BY C.CustomerID, C.CompanyName
derived table cont2
Derived Table (cont)
  • You should now see a row returned for each Customer and the total number or orders placed in the year 1996—including the customers that didn’t place an order.
  • The reason this works is because the LEFT JOIN will include all matches or null values. If the LEFT JOIN has matches (like in our first query,) but non that match the criteria those rows are excluded.
common table expressions cte
Common Table Expressions (CTE)
  • A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.
cte cont
CTE (cont)
  • Common Table Expressions offer the same functionality as a view, but are ideal for one-off usages where you don't necessarily need a view defined for the system.
cte cont1
CTE (cont)
  • A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query.
  • A CTE can be self-referencing and can be referenced multiple times in the same query.
cte cont2
CTE (cont)
  • CTEs allow you to separate part of your T-SQL logic from your main query instead of using a view, correlated subquery, or temp table.
cte syntax
CTE Syntax
  • Start with the word WITH, followed by a name for your CTE. Follow the name of the CTE with the word AS and a set of parentheses. Inside the parentheses, type in a valid SELECT query. You can then use the CTE in your main query just as if the CTE was a table or view.
cte syntax1
CTE Syntax

WITH emp (SELECT columnname

FROM tablenname AS column alias

INNER JOIN tablename as column alias

ON table.column = table.column)

You then can use the CTE in a query

SELECT columnname

FROM CTE AS column alias


  • WITH emp AS (SELECT EmployeeID, FirstName, LastName, E.Title, ManagerIDFROM HumanResources.Employee AS E INNER JOIN Person.Contact AS C ON E.ContactID = C.ContactID )
query using cte
Query using CTE
  • SELECT A.EmployeeID, A.FirstName, A.LastName, A.Title,A.ManagerID, B.FirstName AS MgrFirstName, B.LastName AS MgrLastName, B.Title AS MgrTitleFROM emp AS A INNER JOIN emp AS B ON A.ManagerID = B.EmployeeID;
  • The query returns a list of the customers along with the products ordered on the most recent order.
  • WITH maxDate AS (SELECT MAX(OrderDate) AS MaxOrderDate, CustomerIDFROM Sales.SalesOrderHeaderGROUP BY CustomerID),orders AS (SELECT SalesOrderID, soh.CustomerID, OrderDate FROM Sales.SalesOrderHeader AS soh INNER JOIN maxDate ON soh.CustomerID = maxDate.CustomerID AND soh.OrderDate = maxDate.MaxOrderDate)SELECT CustomerID,ProductID, sod.SalesOrderID,OrderDate FROM orders INNER JOIN Sales.SalesOrderDetail AS sod ON sod.SalesOrderID = orders.salesOrderID;
cte s and recursion
CTE’s and Recursion
  • Recursion is the process of defining a solution to a problem in terms of itself.
  • For example, a teacher needs to sort a stack of tests alphabetically by the students' names. She could process the tests one at a time and, for each test, insert it into the appropriate spot to the left (called insertion sort).
recursive cte
Recursive CTE
  • 2 pieces:
  • The base case - what to do when you're done recursing. After dividing the tests into separate piles of say, eight elements per pile, the base case is to sort these piles via insertion sort.
  • The recursive step - the action to perform that involves plugging the input "back into" the system. For merge sort, the recursive step is the division of one pile into two. Then into four. Then into eight, and so on, until the base case is reached.
recursive cte1
Recursive CTE
  • Translation:

This translates into two SQL queries - one that gets the "initial" data UNIONed with one that performs the recursion.

recursive deconstructed
Recursive Deconstructed
  • The WITH clause is the definition of the CTE and it precedes the outer query, which refers back to the CTE. 
  • Within the WITH clause, the anchor member is a SELECT statement that acts as the seed for recursion. 
recursive deconstructed1
Recursive Deconstructed
  • It is merged using the UNION ALL operator to the recursive member, which is a SELECT statement that refers back to the CTE; hence it is recursive.
cte s and hierarchies
CTE’s and hierarchies
  • CTEs can also be used to recursively enumerate hierarchical data.
cte to examine hierarchies
CTE to examine Hierarchies
  • ;WITH cte_name (<column list>) AS
  • (
  • <query that defines the anchor member>
  • <query that is the recursive member, referencing cte_name>
  • )
  • query_statement_using_cte_name
hierarchy example
Hierarchy Example
  • Show the levels that directly report to the Product Development Manager
  • We create the anchor member as the record which is for the Product Development Manager. As part of this query, we create two pseudo columns. One for indicating the level (called OrgLevel) and for sorting the records in the right fashion (called SortKey). The sort key for us is the primary key of the table converted to a binary column.
  • After the anchor query, we now use this as the input and form the recursive query. Note that the recursive query increments the OrgLevel column and also builds the SortKey column.
  • Since we want only the people who directly report to the product development manager, we specify the condition OrgLevel < 1. What happens if we omit this condition? That is the next sample…

WITH SampleOrgChart (Level, Position, ReportingLevel, OrgLevel, SortKey)

AS ( -- Create the anchor query. This establishes the starting – point

SELECT a.LevelID, a.Position, a.ReportingLevelID, 0, CAST (a.LevelID AS VARBINARY(900))

FROM dbo.SampleOrg a

WHERE a.Position = 'Product Development Manager'

UNION ALL -- Create the recursive query. This query will be executed -- until it returns no more rows

SELECT a.LevelID, a.Position, a.ReportingLevelID, b.OrgLevel+1,

CAST (b.SortKey + CAST (a.LevelID AS BINARY(4))


FROM dbo.SampleOrg a

INNER JOIN SampleOrgChart b

ON a.ReportingLevelID = b.Level

WHERE b.OrgLevel < 1 )

SELECT * FROM SampleOrgChart ORDER BY SortKey

inline table valued functions tvfs
Inline Table-Valued Functions (TVFs)
  • An inline table-valued function can be viewed as a select statement with parameters.
  • To create an inline table-valued function, you need to use the "RETURNS TABLE" clause in the "CREATE FUNCTION" statement. There should be no function body, except for a RETURN statement with a SELECT subquery
inline table valued functions tvfs1
Inline Table-Valued Functions (TVFs)
  • Inline Table-Valued Functions return a resultset, as opposed to a single scalar value. A table valued function specifies the TABLE keyword in its RETURN clause.
  • CREATE FUNCTION [ owner_name. ] fn_name ( [ { @parameter [ AS ] type } [ ,...n ] ]) RETURNS TABLE [ AS ] RETURN [ ( ] select-statement [ ) ]
  • An Inline Table-Valued Function created by this command:

CREATE FUNCTION datesales (@deadline as datetime)

RETURNS TABLE AS RETURN ( SELECT * FROM sales WHERE ord_date > @deadline)

syntax info
Syntax info
  • A variable has a name that begins with the @ symbol and always must be given a data type.
call the function
Call the Function
  • USE PUBS GO select * from datesales('09/13/1994')
example 2
Example 2
  • USE PUBSGOCREATE FUNCTION getAuthorsByState(@state CHAR(2) )RETURNS TABLEASRETURN(SELECT au_fname + ' ' + au_lname AS aNameFROM authorsWHERE state = @state)
example 2 cont
Example 2 (cont)
  • UDF named "getAuthorsByState"
  • Objective: return a list of names of authors whose state field matches the value passed in through the input parameter, @state.
step through

1st: a basic SQL query to concatenate the values of the au_fname and au_lname fields with a space.

SELECT au_fname + ' ' + au_lname AS aNameFROM authorsWHERE state = @state

step through cont
Step-Through (cont)

2nd: In the where clause, we tell SQL Server to only return authors whose state matches the value of our @state input parameter.

WHERE state = @state

step through cont1
Step-Through (cont)

3rd: To test our new inline-table valued UDF, clear the code window in query analyzer and enter and execute the following code:


  • SQL Server 2005 introduced the APPLY operator, which is very much like a join clause and which allows joining between two table expressions i.e. joining a left/outer table expression with a right/inner table expression.
apply cont
Apply (cont)
  • The APPLY operator allows you to join two table expressions; the right table expression is processed every time for each row from the left table expression.
apply cont1
Apply (cont)
  • The APPLY operator comes in two variants, the CROSS APPLY and the OUTER APPLY.
  • The CROSS APPLY operator returns only those rows from left table expression (in its final output) if it matches with right table expression. In other words, the right table expression returns rows for left table expression match only. 
apply cont2
Apply (cont)
  • the OUTER APPLY operator returns all the rows from left table expression irrespective of its match with the right table expression.  For those rows for which there are no corresponding matches in right table expression, it contains NULL values in columns of right table expression.
apply cont3
Apply (cont)
  • the CROSS APPLY is semantically equivalent to INNER JOIN (or to be more precise its like a CROSS JOIN with a correlated sub-query) with a implicit join condition of 1=1 whereas OUTER APPLY is semantically equivalent to LEFT OUTER JOIN.
  • Cross Apply:

SELECT * FROM Department D CROSS APPLY    (    SELECT * FROM Employee E    WHERE E.DepartmentID = D.DepartmentID    ) A GO

  • Inner Join

SELECT * FROM Department D INNER JOIN Employee E ON D.DepartmentID = E.DepartmentID GO