After completing this module, you will be able to ...dbmanagement.info/Books/MIX/Module03-Recursive_TeraData.pdf · ®Building Tables for Recursive Processing Suppose we want to find
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
® Recursive Queries
After completing this module, you will be able to:
• Identify the need for recursive derived table vs. (non-recursive) derived table.
• Discern the different parts of the recursive query structure.
• Prevent forms of continual looping through a hierarchy.
• Interpret the two-column result set derived by the recursive query.
• “Flatten” the vertical (two-column) result into a horizontal structure.
Recursive queries are queries that process the same data more than once.
These queries are useful for processing data that is hierarchical in nature, i.e.,
• Bill of materials• Corporate org charts• Airline flight plans
Each pass over the data can add new rows to the recursive table.
To process those new rows, another pass over the data is made.
Assume a table has all direct airline flights to Los Angeles for a particular airline:
You can see all direct flights from New York by reading through the table once.You can see all one-stopover flights from NY by reading through the table twice.You can see all two-stopover flights from NY by reading through the table three times.
Each iteration may require a temporary table to be built and a new query to be run.
® Building Tables for Recursive Processing
Suppose we want to find all routes originating from LAX having at most 3 stopovers.First, we begin with a Flights table that contains direct flights only and no stopovers.
CREATE TABLE Flights( Origin CHAR(3) NOT NULL,Destination CHAR(3) NOT NULL,Cost INT );
We may use a recursive derived table to solve this problem with a single query. The keyword RECURSIVE states that the All_Trips is a 'recursively' derived table.
WITH RECURSIVE All_Trips(Origin, Destination, Cost, Depth) AS (SELECT Origin, Destination, Cost, 0FROM Flights WHERE Origin = 'LAX'UNION ALLSELECT All_Trips.Origin,
In the query:• SFO is the initial origin.• Infinite looping occurs.• The origin changes to reflect the continuing cities.• Due to the condition on the Depth column, the recursion stopped at a depth of 8 otherwise it would continue indefinitely.
Origin Destination DepthOrigin Destination DepthOrigin Destination DepthOrigin Destination Depth------------------------ -------------------------------------------- --------------------SFO ORD 0SFO ORD 0SFO ORD 0SFO ORD 0ORD BOS 1ORD BOS 1ORD BOS 1ORD BOS 1BOS SFO 2BOS SFO 2BOS SFO 2BOS SFO 2SFO ORD 3SFO ORD 3SFO ORD 3SFO ORD 3ORD BOS 4ORD BOS 4ORD BOS 4ORD BOS 4BOS SFO 5BOS SFO 5BOS SFO 5BOS SFO 5SFO ORD 6SFO ORD 6SFO ORD 6SFO ORD 6ORD BOS 7ORD BOS 7ORD BOS 7ORD BOS 7BOS SFO 8BOS SFO 8BOS SFO 8BOS SFO 8
(Origin, Destination, Depth) AS (SELECT Origin, Destination, 0FROM Flights WHERE Origin = 'SFO'UNION ALLSELECT flights.origin,
Flights.Destination,All_Trips.Depth + 1
FROM All_Trips INNER JOIN FlightsON All_Trips.Destination = Flights.Origin WHERE All_Trips.Origin <> Flights.DestinationAND All_Trips.Depth < 8 )SELECT * FROM All_TripsORDER BY 3, 1, 2;
Was All_Trips.Origin
® Two-City Chain Recursion
WITH RECURSIVE All_Trips(Origin, Destination, Depth) AS (SELECT Origin, Destination, 0FROM Flights WHERE Origin = 'SFO'UNION ALLSELECT flights.origin,
Flights.Destination,All_Trips.Depth + 1
FROM All_Trips INNER JOIN FlightsON All_Trips.Destination = Flights.Origin WHERE All_Trips.Depth < 4AND All_Trips.Origin <> Flights.Destination)SELECT * FROM All_TripsORDER BY 3, 1, 2;
Origin Destination Origin Destination Origin Destination Origin Destination ------------------------------------ ----------------------------------------------------ATL BOS ATL BOS ATL BOS ATL BOS LAX BOS LAX BOS LAX BOS LAX BOS LAX ATL LAX ATL LAX ATL LAX ATL LAX SFO LAX SFO LAX SFO LAX SFO SFO ORD SFO ORD SFO ORD SFO ORD ORD SFO ORD SFO ORD SFO ORD SFO
FlightsTable
For the query:• Note the chain: SFO ���� ORD ���� SFO.• Infinite looping occurs within 2 cities.• The origin changes to reflect the continuing cities.• The <> condition prevents the origin, in All_Trips,
from connecting to a city that returns back to itself, in the Flights table.
Origin Destination DepthOrigin Destination DepthOrigin Destination DepthOrigin Destination Depth------------------------ -------------------------------------------- --------------------SFO ORD 0SFO ORD 0SFO ORD 0SFO ORD 0ORD SFO 1ORD SFO 1ORD SFO 1ORD SFO 1SFO ORD 2SFO ORD 2SFO ORD 2SFO ORD 2ORD SFO 3ORD SFO 3ORD SFO 3ORD SFO 3SFO ORD 4SFO ORD 4SFO ORD 4SFO ORD 4
Result without condition
Origin Destination DepthOrigin Destination DepthOrigin Destination DepthOrigin Destination Depth------------------------ -------------------------------------------- --------------------SFO ORD 0SFO ORD 0SFO ORD 0SFO ORD 0
Result with condition
Note
® Creating Recursive Views
A recursive view may be created for referencing. A view definition is seen here based upon the previous queries.
FROM All_Trips, FlightsWHERE All_Trips.Destination = Flights.Origin AND All_Trips.Depth < :indepth AND All_Trips.Origin <> Flights.Destination)SELECT * FROM All_TripsORDER BY 4, 1, 2;);
FROM All_Trips INNER JOIN FlightsON All_Trips.Dest = Flights.Origin AND all_trips.origin <> Flights.DestinationAND POSITION(flights.destination IN all_trips.desttree) = 0AND All_Trips.Depth < 8 )SELECT origin, desttree, depth FROM All_TripsORDER BY 3, 2;
Eliminates Two-City Recursion
Eliminates any destination already appearing as a stopover.
This is an attempt at displaying the actual path from origin to final destination.
®
WITH Derived Table Form without Recursive Logic
Multiple elements allowed in WITH list
Previouslyonly a single WITH list was allowed in a WITH clause, as seen here:
WITH list1(x1,y1) AS (SELECT * FROM t1) SELECT * FROM list1 ORDER BY x1, y1;
Nowmultiple WITH lists are allowed in a single WITH clause, as seen here:
WITH list1(x1,y1) AS (SELECT * FROM t1),list2(x2,y2) AS (SELECT * FROM t2)
SELECT * FROM with1,with2 ORDER BY x1, y1;
®
WITH Derived Table Form without Recursive Logic (continued)
Any Number of WITH Expressions in a Single DML StatementThis applies to both WITH and WITH RECURSIVE statements.
Previouslyonly a single WITH expression was permitted in a DML statement, as seen here:
WITH RECURSIVE list1(x1,y1) AS (SELECT * FROM T1) SELECT * FROM list1;
Nowmultiple WITH expressions are allowed in a single DML statement, as seen here:
WITH RECURSIVE list1(x1,y1) AS (SELECT * FROM T1 UNION ALL SELECT x1,b1 FROM t1, list1 WHERE a1=x1),
RECURSIVE list 2(x2,y2) AS (SELECT * FROM t2 UNION ALL SELECT x2,b2 FROM t2, list2 WHERE a2=x2)SEL * FROM list1, list2;
®
WITH Derived Table Form without Recursive Logic (continued)
Multiple Non-Recursive and Recursive WITH lists in the Same QueryMultiple WITH lists with both recursive and non-recursive processing in the same query is now possible.
WITH RECURSIVE list1(x1,y1) AS (SELECT * FROM t1 UNION ALL SELECT x1,b1 FROM t1, list1 WHERE a1=x1),
list2(x2,y2) AS (SEL * FROM T2)
SEL * FROM list1,list2;
® Limitations and Restrictions
The only set operator that can appear within a WITH RECURSIVE clause is UNION ALL. The following set operators cannot appear within a WITH RECURSIVE clause:
• UNION• INTERSECT - INTERSECT ALL• EXCEPT - EXCEPT ALL• MINUS - MINUS ALL
The following elements cannot appear within a WITH or WITH RECURSIVE clause:• WITH or WITH RECURSIVE clause• TOP N operator• User-defined functions• Columns with a UDT data type
The following elements cannot appear within a recursive statement in a WITH RECURSIVE clause:
• NOT IN or NOT EXISTS logical predicate• Aggregate functions• Ordered analytical functions• GROUP BY clause• HAVING clause• DISTINCT clause• Subqueries• Derived tables
® Module 3: Summary
Recursive Queries:
• Provide a relational method for iteratively querying hierarchal structures.
• Are built on a form of derived table syntax.
• Involve a “seed” query and an “iterative” query that are connected with the set operator UNION ALL.
• Can be made into views.
• Can be incorporated into macros.
® Module 3: Review Questions
False – only the WITH form can be used.
True
False – the user must provide this capability
False – they may “dead-end” on their own
True
False – only the recursive view has a special syntax
True
True or False:
1. Recursive queries may be written using either form of derived table.
2. Only the most recently added rows are available to the iterative portion.
3. The mechanism to prevent infinite recursion is automatically provided.
4. Without preventing infinite recursion, all recursive queries can loop indefinitely.
5. The WITH form for derived tables may be either recursive or non-recursive.
6. Both views and macros require a special syntax structure when referencing recursive queries.
7. The recursive query syntax for macros requires a final SELECT to return the rows.
® Module 3: Lab Exercise
1) Write a recursive query against the Employee table that show the manager-to-employee-to-manager relationships beginning with manager 801.
Does this relationship “dead-end” or loop continuously?