0429 SQL Recursion
0429 SQL Recursion
Introduction to Databases
CompSci 316 Fall 2014
2
A motivating example
Parent (parent, child)
Ape
parent child
Abe
Homer Marge
Bart Lisa
Recursion in SQL
• SQL2 had no recursion
• You can find Bart’s parents, grandparents, great
grandparents, etc.
! " ! ! " "
#$% !& " ! '!& " ! (
) $ ! * !+! ( "
,-! ( * !+!. ./
• But you cannot find all his ancestors with a single query
• SQL3 introduces recursion
• )0 clause
• Implemented in PostgreSQL (common table
expressions)
6
Finding ancestors
parent child
• )0 !$ 1$ 02
" 3 " '! 4!
33 ! " '! * !#$% !& " 4
1,0%,
3 ! " '! (
#$% ! " '! " (
) $ ! !+! ( " 44
• Think of the definition as Ancestor = (Ancestor) anc desc
anc desc
anc desc
anc desc
10
Linear recursion
• With linear recursion, a recursive definition can make
only one reference to itself
• Non-linear
• )0 !$ 1$ 02 ! " 3 " '! 4!
33 ! " '! * !#$% !& " 4
1,0%,
3 ! " '! (
#$% ! " '! " (
) $ ! !+! ( " 44
• Linear
• )0 !$ 1$ 02 ! " 3 " '! 4!
33 ! " '! * !#$% !& " 4
1,0%,
3 ! " '! *
#$% ! " '!& "
) $ ! +! " 44
12
5 6
14
Semantics of )0
• )0 !$ 1$ 02 ! ! '!;'
$ 1$ 02 ! !
/
• and ,…, may refer to ,…,
• Semantics
1. ← ∅, … , ←∅
2. Evaluate , … , using the current contents of ,…, :
← ,…, ←
3. If ≠ for some
3.1. ← ,…, ←
3.2. Go to 2.
4. Compute using the current contents of , …
and output the result
16
)0 !$ 1$ 02 parent child
" 3 " '! 4!
33 ! " '! * !#$% !
& " 4
1,0%,
3 ! " '! (
#$% ! " '! " (
) $ ! !+! ( " 44
Summary
• SQL3 )0 recursive queries
• Solution to a recursive query (with no negation):
unique minimal fixed point
• Computing unique minimal fixed point: fixed-point
iteration starting from ∅
• Mixing negation and recursion is tricky
• Illegal mix: fixed-point iteration may not converge; there
may be multiple minimal fixed points
• Legal mix: stratified negation (compute by fixed-point
iteration stratum by stratum)