SlideShare una empresa de Scribd logo
1 de 84
Descargar para leer sin conexión
Chapter 5: Other Relational Languages 




         Database System Concepts, 5th Ed.
              ©Silberschatz, Korth and Sudarshan
         See www.db­book.com for conditions on re­use 
Chapter 5:  Other Relational Languages

             s Tuple Relational Calculus
             s Domain Relational Calculus
             s Query­by­Example (QBE)
             s Datalog




Database System Concepts , 5th Ed., Aug 2005   5.<number>   ©Silberschatz, Korth and Sudarshan
Tuple Relational Calculus

             s A nonprocedural query language, where each query is of the form
                                               {t | P (t ) }
             s It is the set of all tuples t such that predicate P is true for t
             s t is a tuple variable, t [A ] denotes the value of tuple t on attribute A
             s t ∈ r denotes that tuple t is in relation r
             s P is a formula similar to that of the predicate calculus




Database System Concepts , 5th Ed., Aug 2005            5.<number>           ©Silberschatz, Korth and Sudarshan
Predicate Calculus Formula

             1. Set of attributes and constants
             2. Set of comparison operators:  (e.g., <, ≤, =, ≠, >, ≥)
             3. Set of connectives:  and (∧), or (v)‚ not (¬)
             4. Implication (⇒): x ⇒ y, if x if true, then y is true
                                                x ⇒ y ≡ ¬x v y
             5. Set of quantifiers:
                         ∃ t ∈ r (Q (t )) ≡ ”there exists” a tuple in t in relation r
                                                 such that predicate Q (t ) is true
                         ∀t ∈ r (Q (t )) ≡ Q is true “for all” tuples t in relation r




Database System Concepts , 5th Ed., Aug 2005           5.<number>                   ©Silberschatz, Korth and Sudarshan
Banking Example

             s branch (branch_name, branch_city, assets ) 
             s customer (customer_name, customer_street, customer_city ) 
             s account (account_number, branch_name, balance ) 
             s loan (loan_number, branch_name, amount )
             s depositor (customer_name, account_number )
             s borrower (customer_name, loan_number )




Database System Concepts , 5th Ed., Aug 2005        5.<number>    ©Silberschatz, Korth and Sudarshan
Example Queries

             s Find the loan_number, branch_name, and amount for loans of over 
                   $1200

                                           {t | t ∈ loan ∧ t [amount ] > 1200}

             s  Find the loan number for each loan of an amount greater than $1200


                     {t | ∃ s ∈ loan (t [loan_number ] = s [loan_number ] ∧ s [amount ] > 1200)}


                  Notice that a relation on schema [loan_number ] is implicitly defined by            
                  the query




Database System Concepts , 5th Ed., Aug 2005             5.<number>              ©Silberschatz, Korth and Sudarshan
Example Queries

             s Find the names of all customers having a loan, an account, or both at 
                   the bank

                           {t | ∃s ∈ borrower ( t [customer_name ] = s [customer_name ])
                                ∨ ∃u ∈ depositor ( t [customer_name ] = u [customer_name ])



             s   Find the names of all customers who have a loan and an account 
                   at the bank

                        {t | ∃s ∈ borrower ( t [customer_name ] = s [customer_name ])
                              ∧ ∃u ∈ depositor ( t [customer_name ] = u [customer_name] )




Database System Concepts , 5th Ed., Aug 2005        5.<number>              ©Silberschatz, Korth and Sudarshan
Example Queries
             s Find the names of all customers having a loan at the Perryridge branch



                        {t | ∃s ∈ borrower (t [customer_name ] = s [customer_name ] 
                             ∧ ∃u ∈ loan (u [branch_name ] = “Perryridge”
                                                 ∧  u [loan_number ] = s [loan_number ]))}

             s  Find the names of all customers who have a loan at the 
                  Perryridge branch, but no account at any branch of the bank

                      {t | ∃s ∈ borrower (t [customer_name ] = s [customer_name ]
                             ∧ ∃u ∈ loan (u [branch_name ] = “Perryridge”
                                                 ∧  u [loan_number ] = s [loan_number ]))
                             ∧ not ∃v ∈ depositor (v [customer_name ] = 
                                                                            t [customer_name ])}




Database System Concepts , 5th Ed., Aug 2005            5.<number>                    ©Silberschatz, Korth and Sudarshan
Example Queries
             s Find the names of all customers having a loan from the Perryridge 
                   branch, and the cities in which they live


                   {t | ∃s ∈ loan (s [branch_name ] = “Perryridge”
                           ∧ ∃u ∈ borrower (u [loan_number ] = s [loan_number ]
                                    ∧  t [customer_name ] = u [customer_name ])
                               ∧ ∃ v ∈ customer (u [customer_name ] = v [customer_name ]
                                                                 ∧  t [customer_city ] = v [customer_city ])))}




Database System Concepts , 5th Ed., Aug 2005             5.<number>                     ©Silberschatz, Korth and Sudarshan
Example Queries
             s Find the names of all customers who have an account at all branches 
                   located in Brooklyn:

                  {t | ∃ r ∈ customer (t [customer_name ] = r [customer_name ]) ∧
                      ( ∀ u ∈ branch (u [branch_city ] = “Brooklyn” ⇒ 
                           ∃ s ∈ depositor (t [customer_name ] = s [customer_name ]
                            ∧ ∃ w ∈ account ( w[account_number ] = s [account_number ]
                            ∧ ( w [branch_name ] = u [branch_name ]))))}




Database System Concepts , 5th Ed., Aug 2005        5.<number>             ©Silberschatz, Korth and Sudarshan
Safety of Expressions

             s It is possible to write tuple calculus expressions that generate infinite 
                   relations.
             s For example, { t | ¬ t ∈ r } results in an infinite relation if the domain of 
                   any attribute of relation r is infinite
             s To guard against the problem, we restrict the set of allowable 
                   expressions to safe expressions.
             s An expression {t | P (t )} in the tuple relational calculus is safe if every 
                   component of t appears in one of the relations, tuples, or constants that 
                   appear in P
                     q   NOTE: this is more than just a syntax condition. 
                              E.g. { t | t [A] = 5 ∨ true } is not safe ­­­ it defines an infinite set 
                               with attribute values that do not appear in any relation or tuples 
                               or constants in P. 




Database System Concepts , 5th Ed., Aug 2005             5.<number>                  ©Silberschatz, Korth and Sudarshan
Domain Relational Calculus

             s A nonprocedural query language equivalent in power to the tuple 
                   relational calculus
             s Each query is an expression of the form:


                                          { < x1, x2, …, xn > | P (x1, x2, …, xn)}


                     q   x1, x2, …, xn  represent domain variables
                     q   P represents a formula similar to that of the predicate calculus




Database System Concepts , 5th Ed., Aug 2005               5.<number>                ©Silberschatz, Korth and Sudarshan
Example Queries
              s Find the loan_number, branch_name, and  amount for loans of over $1200



                                  {< l, b, a > | < l, b, a > ∈ loan ∧ a > 1200}

             s Find the names of all customers who have a loan of over $1200

                     {< c > | ∃ l, b, a (< c, l > ∈ borrower ∧ < l, b, a > ∈ loan ∧ a > 1200)}

             s Find the names of all customers who have a loan from the Perryridge branch 
                   and the loan amount:
                         {< c, a > | ∃ l (< c, l > ∈ borrower ∧ ∃b (< l, b, a > ∈ loan ∧ 
                   
                                                                                         b = “Perryridge”))}
                         {< c, a > | ∃ l (< c, l > ∈ borrower ∧ < l, “ Perryridge”, a > ∈ loan)}
                     



Database System Concepts , 5th Ed., Aug 2005                 5.<number>                         ©Silberschatz, Korth and Sudarshan
Example Queries

             s Find the names of all customers having a loan, an account, or both at 
                   the Perryridge branch:

                      {< c > | ∃ l ( < c, l > ∈ borrower 
                                       ∧ ∃ b,a (< l, b, a > ∈ loan ∧ b = “Perryridge”))
                             ∨ ∃ a (< c, a > ∈ depositor
                                       ∧ ∃ b,n (< a, b, n > ∈ account ∧ b = “Perryridge”))}


             s  Find the names of all customers who have an account at all 
                  branches located in Brooklyn:

                  {< c > | ∃ s,n (< c, s, n > ∈ customer) ∧
                              ∀ x,y,z (< x, y, z > ∈ branch ∧ y = “Brooklyn”) ⇒
                                  ∃ a,b (< x, y, z > ∈ account ∧ < c,a > ∈ depositor)} 




Database System Concepts , 5th Ed., Aug 2005          5.<number>                  ©Silberschatz, Korth and Sudarshan
Safety of Expressions

             The expression:
                                    { < x1, x2, …, xn > | P (x1, x2, …, xn )}


             is safe if all of the following hold:
             4. All values that appear in tuples of the expression are values 
                   from dom (P ) (that is, the values appear either in P or in a tuple of a 
                   relation mentioned in P ).
             5. For every “there exists” subformula of the form ∃ x (P1(x )), the 
                   subformula is true if and only if there is a value of x in dom (P1)
                   such that P1(x ) is true.
             6. For every “for all” subformula of the form ∀x (P1 (x )), the subformula is 
                   true if and only if P1(x ) is true for all values x  from dom (P1).




Database System Concepts , 5th Ed., Aug 2005              5.<number>            ©Silberschatz, Korth and Sudarshan
Query­by­Example (QBE)

             s Basic Structure
             s Queries on One Relation
             s Queries on Several Relations
             s The Condition Box
             s The Result Relation
             s Ordering the Display of Tuples
             s Aggregate Operations 
             s Modification of the Database




Database System Concepts , 5th Ed., Aug 2005   5.<number>   ©Silberschatz, Korth and Sudarshan
QBE — Basic Structure

             s A graphical query language which is based (roughly) on the domain 
                   relational calculus
             s Two dimensional syntax – system creates templates of relations that 
                   are requested by users
             s Queries are expressed “by example”




Database System Concepts , 5th Ed., Aug 2005   5.<number>           ©Silberschatz, Korth and Sudarshan
QBE Skeleton Tables for the Bank Example




Database System Concepts , 5th Ed., Aug 2005   5.<number>   ©Silberschatz, Korth and Sudarshan
QBE Skeleton Tables (Cont.)




Database System Concepts , 5th Ed., Aug 2005   5.<number>   ©Silberschatz, Korth and Sudarshan
Queries on One Relation
             s Find all loan numbers at the Perryridge branch.




                               q     _x is a variable (optional; can be omitted in above query)
                               q     P. means print (display)
                               q     duplicates are removed by default
                               q     To retain duplicates use P.ALL 




Database System Concepts , 5th Ed., Aug 2005            5.<number>               ©Silberschatz, Korth and Sudarshan
Queries on One Relation (Cont.)
             s Display full details of all loans


                   q    Method 1:



                                               P._x                P._y         P._z


                   q    Method 2: Shorthand notation




Database System Concepts , 5th Ed., Aug 2005          5.<number>          ©Silberschatz, Korth and Sudarshan
Queries on One Relation (Cont.)
              s Find the loan number of all loans with a loan amount of more than $700




             s Find names of all branches that are not located in Brooklyn




Database System Concepts , 5th Ed., Aug 2005   5.<number>             ©Silberschatz, Korth and Sudarshan
Queries on One Relation (Cont.)
             s Find the loan numbers of all loans made jointly to Smith and 
                   Jones.




             s Find all customers who live in the same city as Jones




Database System Concepts , 5th Ed., Aug 2005   5.<number>              ©Silberschatz, Korth and Sudarshan
Queries on Several Relations
             s Find the names of all customers who have a loan from the 
                   Perryridge branch.




Database System Concepts , 5th Ed., Aug 2005   5.<number>           ©Silberschatz, Korth and Sudarshan
Queries on Several Relations (Cont.)

             s Find the names of all customers who have both an account and a loan 
                   at the bank.




Database System Concepts , 5th Ed., Aug 2005   5.<number>           ©Silberschatz, Korth and Sudarshan
Negation in QBE

             s Find the names of all customers who have an account at the bank, 
                   but do not have a loan from the bank.




                       ¬ means “there does not exist”




Database System Concepts , 5th Ed., Aug 2005        5.<number>      ©Silberschatz, Korth and Sudarshan
Negation in QBE (Cont.)

             s Find all customers who have at least two accounts.




                     ¬ means “not equal to”




Database System Concepts , 5th Ed., Aug 2005   5.<number>           ©Silberschatz, Korth and Sudarshan
The Condition Box

             s Allows the expression of constraints on domain variables that are 
                   either inconvenient or impossible to express within the skeleton 
                   tables.
             s Complex conditions can be used in condition boxes
             s Example: Find the loan numbers of all loans made to Smith, to 
                   Jones, or to both jointly




Database System Concepts , 5th Ed., Aug 2005         5.<number>            ©Silberschatz, Korth and Sudarshan
Condition Box (Cont.)
             s QBE supports an interesting syntax for expressing alternative values




Database System Concepts , 5th Ed., Aug 2005     5.<number>          ©Silberschatz, Korth and Sudarshan
Condition Box (Cont.)
            s Find all account numbers with a balance greater than $1,300 and less than 
                 $1,500 




            s Find all account numbers with a balance greater than $1,300 and  less than 
                 $2,000 but not exactly $1,500.




Database System Concepts , 5th Ed., Aug 2005      5.<number>         ©Silberschatz, Korth and Sudarshan
Condition Box (Cont.)

             s Find all branches that have assets greater than those of at least one 
                   branch located in Brooklyn




Database System Concepts , 5th Ed., Aug 2005     5.<number>            ©Silberschatz, Korth and Sudarshan
The Result Relation

             s Find the customer_name, account_number, and balance for all 
                   customers who have an account at the Perryridge branch.
                     q   We need to:
                              Join depositor and account.
                              Project customer_name, account_number and balance.
                     q   To accomplish this we:
                              Create a skeleton table, called result, with attributes 
                               customer_name, account_number, and balance.
                              Write the query.




Database System Concepts , 5th Ed., Aug 2005           5.<number>                ©Silberschatz, Korth and Sudarshan
The Result Relation (Cont.)

             s The resulting query is: 




Database System Concepts , 5th Ed., Aug 2005   5.<number>   ©Silberschatz, Korth and Sudarshan
Ordering the Display of Tuples
             s AO = ascending order; DO = descending order.
             s Example: list in ascending alphabetical order all customers who have an 
                   account at the bank




             s When sorting on multiple attributes, the sorting order is specified by 
                   including with each sort operator (AO or DO) an integer surrounded by 
                   parentheses.
             s Example: List all account numbers at the Perryridge branch in ascending 
                   alphabetic order with their respective account balances in descending order.




Database System Concepts , 5th Ed., Aug 2005     5.<number>              ©Silberschatz, Korth and Sudarshan
Aggregate Operations

             s The aggregate operators are AVG, MAX, MIN, SUM, and CNT
             s The above operators must be postfixed with “ALL” (e.g., SUM.ALL. 
                   or AVG.ALL._x) to ensure that duplicates are not eliminated.
             s Example: Find the total balance of all the accounts maintained at 
                   the Perryridge branch.




Database System Concepts , 5th Ed., Aug 2005    5.<number>               ©Silberschatz, Korth and Sudarshan
Aggregate Operations (Cont.)
             s UNQ is used to specify that we want to eliminate duplicates 
             s Find the total number of customers having an account at the bank.




Database System Concepts , 5th Ed., Aug 2005   5.<number>             ©Silberschatz, Korth and Sudarshan
Query Examples
             s Find the average balance at each branch.




              s The “G” in “P.G” is analogous to SQL’s group by construct 
              s The “ALL” in the “P.AVG.ALL” entry in the balance column ensures that 
                   all balances are considered
              s To find the average account balance at only those branches where the 
                   average account balance is more than  $1,200, we simply add the 
                   condition box:




Database System Concepts , 5th Ed., Aug 2005       5.<number>          ©Silberschatz, Korth and Sudarshan
Query Example

             s Find all customers who have an account at all branches located in 
                   Brooklyn.  
                     q   Approach:  for each customer, find the number of branches in 
                         Brooklyn at which they have accounts, and compare with total 
                         number of branches in Brooklyn
                     q   QBE does not provide subquery functionality, so both above tasks 
                         have to be combined in a single query.  
                              Can be done for this query, but there are queries that require 
                               subqueries and cannot always be expressed in QBE.

             s In the query on the next page
                         CNT.UNQ.ALL._w specifies the number of distinct branches in 
                         Brooklyn.  Note: The variable _w is not connected to other variables 
                         in the query
                         CNT.UNQ.ALL._z specifies the number of distinct branches in 
                         Brooklyn at which customer x has an account.

Database System Concepts , 5th Ed., Aug 2005          5.<number>               ©Silberschatz, Korth and Sudarshan
Query Example (Cont.)




Database System Concepts , 5th Ed., Aug 2005    5.<number>   ©Silberschatz, Korth and Sudarshan
Modification of the Database – Deletion

             s Deletion of tuples from a relation is expressed by use of a D. command.  
                   In the case where we delete information in only some of the columns, 
                   null values, specified by –, are inserted.
             s Delete customer Smith




             s Delete the branch_city value of the branch whose name is “Perryridge”.




Database System Concepts , 5th Ed., Aug 2005    5.<number>               ©Silberschatz, Korth and Sudarshan
Deletion Query Examples
             s Delete all loans with a loan amount greater than $1300 and  less than 
                   $1500.
                     q   For consistency, we have to delete information from loan and 
                         borrower tables




Database System Concepts , 5th Ed., Aug 2005      5.<number>               ©Silberschatz, Korth and Sudarshan
Deletion Query Examples (Cont.)
             s Delete all accounts at branches located in Brooklyn.




Database System Concepts , 5th Ed., Aug 2005   5.<number>             ©Silberschatz, Korth and Sudarshan
Modification of the Database – Insertion

             s Insertion is done by placing the I. operator in the query 
                   expression. 
             s Insert the fact that account A­9732 at the Perryridge branch has 
                   a balance of $700.




Database System Concepts , 5th Ed., Aug 2005   5.<number>               ©Silberschatz, Korth and Sudarshan
Modification of the Database – Insertion (Cont.)

             s Provide as a gift for all loan customers of the Perryridge branch, a new 
                   $200 savings account for every loan account they have, with the loan 
                   number serving as the account number for the new savings account.  




Database System Concepts , 5th Ed., Aug 2005    5.<number>               ©Silberschatz, Korth and Sudarshan
Modification of the Database – Updates

             s Use the U. operator to change a value in a tuple without changing all  
                   values in the tuple. QBE does not allow users to update the primary key 
                   fields.
             s Update the asset value of the Perryridge branch to $10,000,000. 




             s Increase all balances by 5 percent.




Database System Concepts , 5th Ed., Aug 2005     5.<number>              ©Silberschatz, Korth and Sudarshan
Microsoft Access QBE

             s Microsoft Access supports a variant of QBE called Graphical Query By 
                   Example (GQBE)
             s GQBE differs from QBE in the following ways
                     q   Attributes of relations are listed vertically, one below the other, 
                         instead of horizontally
                     q   Instead of using variables, lines (links) between attributes are used 
                         to specify that their values should be the same.
                              Links are added automatically on the basis of attribute name,  
                               and the user can then add or delete links
                              By default, a link specifies an inner join, but can be modified to 
                               specify outer joins.
                     q   Conditions, values to be printed, as well as group by attributes are all 
                         specified together in a box called the design grid




Database System Concepts , 5th Ed., Aug 2005           5.<number>                ©Silberschatz, Korth and Sudarshan
An Example Query in Microsoft Access QBE

             s Example query: Find the customer_name, account_number and balance 
                   for all accounts at the Perryridge branch




Database System Concepts , 5th Ed., Aug 2005     5.<number>     ©Silberschatz, Korth and Sudarshan
An Aggregation Query in Access QBE

             s Find the name, street and city of all customers who have more than one 
                   account at the bank




Database System Concepts , 5th Ed., Aug 2005   5.<number>            ©Silberschatz, Korth and Sudarshan
Aggregation in Access QBE
             s The row labeled Total specifies 
                     q   which attributes are group by attributes
                     q   which attributes are to be aggregated upon (and the aggregate 
                         function).  
                     q   For attributes that are neither group by nor aggregated, we can 
                         still specify conditions by selecting where in the Total row and 
                         listing the conditions below
             s As in SQL, if group by is used, only group by attributes and aggregate 
                   results can be output




Database System Concepts , 5th Ed., Aug 2005       5.<number>                ©Silberschatz, Korth and Sudarshan
Datalog

             s Basic Structure 
             s Syntax of Datalog Rules
             s Semantics of Nonrecursive Datalog
             s Safety 
             s Relational Operations in Datalog
             s Recursion in Datalog
             s The Power of Recursion




Database System Concepts , 5th Ed., Aug 2005    5.<number>   ©Silberschatz, Korth and Sudarshan
Basic Structure

             s Prolog­like logic­based language that allows recursive queries; based on 
                   first­order logic.
             s A Datalog program consists of a set of rules that define views. 
             s Example:  define a view relation v1 containing account numbers and 
                   balances for accounts at the Perryridge branch with a balance of over 
                   $700.
                                v1 (A, B ) :– account (A, “Perryridge”, B ), B > 700.
             s Retrieve the balance of account number “A­217” in the view relation v1.
                                                ? v1 (“A­217”, B ).
             s To find account number and balance of all accounts in v1 that have a 
                   balance greater than 800
                                                   ? v1 (A,B ), B > 800




Database System Concepts , 5th Ed., Aug 2005              5.<number>             ©Silberschatz, Korth and Sudarshan
Example Queries
             s Each rule defines a set of tuples that a view relation must contain.
                     q   E.g.    v1 (A, B ) :– account (A, “ Perryridge”, B ), B > 700    is 
                         read as
                             for all A, B
                             if (A, “Perryridge”, B )  ∈ account and  B > 700
                             then (A, B )  ∈ v1
             s The set of tuples in a view relation is then defined as the union of all the 
                   sets of tuples defined by the rules for the view relation.
             s Example:
                            interest_rate (A, 5) :– account (A, N, B ) , B < 10000
                            interest_rate (A, 6) :– account (A, N, B ), B >= 10000




Database System Concepts , 5th Ed., Aug 2005         5.<number>                 ©Silberschatz, Korth and Sudarshan
Negation in Datalog
             s Define a view relation c that contains the names of all customers who 
                   have a deposit but no loan at the bank:
                            c(N) :– depositor (N, A), not is_borrower (N).
                            is_borrower (N) :–borrower (N,L).
             s NOTE: using  not borrower (N, L) in the first rule results in a different 
                   meaning, namely there is some loan L for which N is not a borrower.  
                     q   To prevent such confusion, we require all variables in negated 
                         “predicate” to also be present in non­negated predicates




Database System Concepts , 5th Ed., Aug 2005          5.<number>             ©Silberschatz, Korth and Sudarshan
Named Attribute Notation

      s Datalog rules use a positional notation that is convenient for relations with a 
            small number of attributes
      s It is easy to extend Datalog to support named attributes.  
              q   E.g.,  v1 can be defined using named attributes as 
                 v1 (account_number A, balance B ) :– 
                    account (account_number A, branch_name “ Perryridge”, balance B ),
                    B > 700.




Database System Concepts , 5th Ed., Aug 2005    5.<number>              ©Silberschatz, Korth and Sudarshan
Formal Syntax and Semantics of Datalog

             s     We formally define the syntax and semantics (meaning) of Datalog 
                   programs, in the following steps
                     1.   We define the syntax of predicates, and then the syntax of rules
                     2.   We define the semantics of individual rules
                     3.   We define the semantics of non­recursive programs, based on a 
                          layering of rules
                     4.   It is possible to write rules that can generate an infinite number of 
                          tuples in the view relation. To prevent this, we define what rules 
                          are “safe”.  Non­recursive programs containing only safe rules 
                          can only generate a finite number of answers.
                     5.   It is possible to write recursive programs whose meaning is 
                          unclear.  We define what recursive programs are acceptable, and 
                          define their meaning.




Database System Concepts , 5th Ed., Aug 2005         5.<number>                ©Silberschatz, Korth and Sudarshan
Syntax of Datalog Rules

             s A positive literal has the form
                                               p (t1, t2 ..., tn )
                     q   p is the name of a relation with n attributes
                     q   each ti is either a constant or variable
             s A negative literal has the form 
                                               not p (t1, t2 ..., tn )
             s Comparison operations are treated as positive predicates 
                     q   E.g.  X  > Y is treated as a predicate >(X,Y )
                     q   “>” is conceptually an (infinite) relation that contains all pairs of 
                         values such that the first value is greater than the second value
             s Arithmetic operations are also treated as predicates
                     q   E.g.  A = B + C  is treated as +(B, C, A), where the relation “+” 
                         contains all triples such that the third value is the
                         sum of the first two

Database System Concepts , 5th Ed., Aug 2005             5.<number>              ©Silberschatz, Korth and Sudarshan
Syntax of Datalog Rules (Cont.)

             s Rules are built out of literals and have the form:

                                          p (t1, t2, ..., tn ) :– L1, L2, ..., Lm.


                                                    head                   body
                     q   each Li  is a literal
                     q   head – the literal p (t1, t2, ..., tn ) 
                     q   body – the rest of the literals
             s A fact is a rule with an empty body, written in the form:

                                                    p (v1, v2, ..., vn ).
                     q   indicates tuple (v1, v2, ..., vn ) is in relation p
             s A Datalog program is a set of rules




Database System Concepts , 5th Ed., Aug 2005                   5.<number>            ©Silberschatz, Korth and Sudarshan
Semantics of a Rule
             s A ground instantiation of a rule (or simply instantiation) is the result 
                   of replacing each variable in the rule by some constant.
                     q   Eg. Rule defining v1
                               v1(A,B) :– account (A,“Perryridge”, B ), B > 700.
                     q   An instantiation above rule:
                             v1 (“A­217”, 750) :–account ( “A­217”, “Perryridge”, 750),
                                                            750 > 700.
             s The body of rule instantiation R’ is satisfied in a set of facts (database 
                   instance) l if
                     1. For each positive literal qi (vi,1, ..., vi,ni ) in the body of R’, l contains 
                         the fact qi (vi,1, ..., vi,ni ).
                     2. For each negative literal not qj (vj,1, ..., vj,nj ) in the body of R’, l 
                         does not contain the fact qj (vj,1, ..., vj,nj ).




Database System Concepts , 5th Ed., Aug 2005                 5.<number>             ©Silberschatz, Korth and Sudarshan
Semantics of a Rule (Cont.)

             s We define the set of facts that can be inferred from a given set of facts l 
                   using rule R as:
                          infer(R, l) = { p (t1, ..., tn) | there is a ground instantiation R’ of R
                                                             where p (t1, ..., tn ) is the head of R’, and 
                                                             the body of R’ is satisfied in l }
             s Given an set of rules ℜ = {R1, R2, ..., Rn}, we define

                          infer(ℜ, l) = infer (R1, l ) ∪ infer (R2, l ) ∪ ... ∪ infer (Rn, l )




Database System Concepts , 5th Ed., Aug 2005                   5.<number>                    ©Silberschatz, Korth and Sudarshan
Layering of Rules
             s     Define the interest on each account in Perryridge
                       interest(A, l) :– perryridge_account (A,B),
                                                interest_rate(A,R), l = B * R/100.
                       perryridge_account(A,B) :– account (A, “Perryridge”, B).
                       interest_rate (A,5) :– account (N, A, B), B < 10000.
                       interest_rate (A,6) :– account (N, A, B), B >= 10000.
             s     Layering of the view relations




Database System Concepts , 5th Ed., Aug 2005           5.<number>                    ©Silberschatz, Korth and Sudarshan
Layering Rules (Cont.)

             Formally:
             s A relation is a layer 1 if all relations used in the bodies of rules defining 
                  it are stored in the database.
             s A relation is a layer 2 if all relations used in the bodies of rules defining 
                  it are either stored in the database, or are in layer 1.
             s A relation p is in layer i + 1 if 
                    q   it is not in layers 1, 2, ..., i
                    q   all relations used in the bodies of rules defining a p are either 
                        stored in the database, or are in layers 1, 2, ..., i




Database System Concepts , 5th Ed., Aug 2005               5.<number>          ©Silberschatz, Korth and Sudarshan
Semantics of a Program

             Let the layers in a given program be 1, 2, ..., n.  Let ℜi denote the
             set of all rules defining view relations in layer i.

                        s Define I  = set of facts stored in the database.
                                  0

                        s Recursively define l  = l  ∪ infer (ℜ , l )
                                              i+1  i           i+1 i 
                        s The set of facts in the view relations defined by the program 
                             (also called the semantics of the program) is given by the set 
                        of facts ln corresponding to the highest layer n.
              Note:  Can instead define semantics using view expansion like
              in relational algebra, but above definition is better for handling
              extensions such as recursion.




Database System Concepts , 5th Ed., Aug 2005         5.<number>               ©Silberschatz, Korth and Sudarshan
Safety
             s It is possible to write rules that generate an infinite number of answers.
                                        gt(X, Y) :– X > Y
                                        not_in_loan (B, L) :– not loan (B, L)
                   To avoid this possibility Datalog rules must satisfy the following 
                   conditions.
                     q   Every variable that appears in the head of the rule also appears in 
                         a non­arithmetic positive literal in the body of the rule.
                              This condition can be weakened in special cases based on the 
                               semantics of arithmetic predicates, for example to permit the 
                               rule
                                     p (A )  :­  q (B ), A = B + 1
                     q   Every variable appearing in a negative literal in the body of the 
                         rule also appears in some positive literal in the body of the rule.




Database System Concepts , 5th Ed., Aug 2005             5.<number>             ©Silberschatz, Korth and Sudarshan
Relational Operations in Datalog

             s Project out attribute account_name from account.
                                           query (A) :–account (A, N, B ).
             s Cartesian product of relations r1 and r2.

                                  query (X1, X2, ..., Xn, Y1, Y1, Y2, ..., Ym ) :–
                                       r1 (X1, X2, ..., Xn ), r2 (Y1, Y2, ..., Ym ).
             s Union of relations r1 and r2.

                                   query (X1, X2, ..., Xn ) :–r1 (X1, X2, ..., Xn ), 
                                   query (X1, X2, ..., Xn ) :–r2 (X1, X2, ..., Xn ), 
             s Set difference of r1 and r2.

                                  query (X1, X2, ..., Xn ) :–r1(X1, X2, ..., Xn ), 
                                                                   not r2 (X1, X2, ..., Xn ), 




Database System Concepts , 5th Ed., Aug 2005                 5.<number>                          ©Silberschatz, Korth and Sudarshan
Recursion in Datalog

             s Suppose we are given a relation 
                        manager (X, Y )
                   containing pairs of names X, Y such that Y is a manager of X (or 
                   equivalently, X is a direct employee of Y).
             s  Each manager may have direct employees, as well as indirect 
                   employees
                     q   Indirect employees of a manager, say Jones, are employees of 
                         people who are direct employees of Jones, or recursively, 
                         employees of people who are indirect employees of Jones
             s Suppose we wish to find all (direct and indirect) employees of manager 
                   Jones.  We can write a recursive Datalog program.
                         empl_jones (X )  :­  manager (X, Jones ).
                         empl_jones (X )  :­  manager (X, Y ), empl_jones (Y ).




Database System Concepts , 5th Ed., Aug 2005       5.<number>               ©Silberschatz, Korth and Sudarshan
Semantics of Recursion in Datalog

             s Assumption (for now): program contains no negative literals
             s The view relations of a recursive program containing a set of rules ℜ are 
                   defined to contain exactly the set of facts l 
                   computed by the iterative procedure Datalog­Fixpoint
                                               procedure  Datalog­Fixpoint
                                                    l = set of facts in the database
                                                    repeat
                                                          Old_l = l
                                                          l = l  ∪ infer (ℜ, l )
                                                    until l = Old_l
             s At the end of the procedure, infer (ℜ, l ) ⊆  l
                     q   Infer (ℜ, l ) =  l  if we consider the database to be a set of facts that 
                         are part of the program
             s l is called a fixed point of the program.




Database System Concepts , 5th Ed., Aug 2005                 5.<number>                ©Silberschatz, Korth and Sudarshan
Example of Datalog­FixPoint Iteration




Database System Concepts , 5th Ed., Aug 2005   5.<number>   ©Silberschatz, Korth and Sudarshan
A More General View
             s Create a view relation empl that contains every tuple (X, Y ) such 
                   that X is directly or indirectly managed by Y.
                                empl (X, Y ) :– manager (X, Y ).
                                empl (X, Y ) :– manager (X, Z ), empl (Z, Y ) 
             s Find the direct and indirect employees of Jones.
                                               ? empl (X, “Jones”).
             s Can define the view empl in another way too:
                                empl (X, Y ) :– manager (X, Y ).
                                empl (X, Y ) :– empl (X, Z ), manager (Z, Y ). 




Database System Concepts , 5th Ed., Aug 2005          5.<number>                  ©Silberschatz, Korth and Sudarshan
The Power of Recursion

             s Recursive views make it possible to write queries, such as transitive 
                   closure queries, that cannot be written without recursion or iteration.
                     q   Intuition:  Without recursion, a non­recursive non­iterative program 
                         can perform only a fixed number of joins of manager with itself
                              This can give only a fixed number of levels of managers
                              Given a program we can construct a database with a greater 
                               number of levels of managers on which the program will not work




Database System Concepts , 5th Ed., Aug 2005         5.<number>              ©Silberschatz, Korth and Sudarshan
Recursion in SQL
             s Starting with SQL:1999, SQL permits recursive view definition
             s E.g. query to find all employee­manager pairs 

                       with recursive empl (emp, mgr ) as (
                                  select emp, mgr 
                                  from    manager
                           union
                                  select manager.emp, empl.mgr
                                  from   manager, empl
                                  where manager.mgr = empl.emp       )
                       select * 
                       from    empl




Database System Concepts , 5th Ed., Aug 2005        5.<number>           ©Silberschatz, Korth and Sudarshan
Monotonicity 
             s A view V is said to be monotonic if given any two sets of facts 
                   I1 and I2 such that l1 ⊆ I2, then Ev (I1)  ⊆ Ev (I2 ), where Ev is the expression 
                   used to define V.
             s A set of rules R is said to be monotonic if
                              l1 ⊆ I2  implies  infer (R, I1 ) ⊆ infer (R, I2 ), 
             s Relational algebra views defined using only the operations:  ∏, σ, ×, ∪, |
                   X|, ∩, and ρ (as well as operations like natural join defined in terms of 
                   these operations) are monotonic. 
             s Relational algebra views defined using set difference (–) may not be 
                   monotonic.
             s Similarly, Datalog programs without negation are monotonic, but 
                   Datalog programs with negation may not be monotonic.




Database System Concepts , 5th Ed., Aug 2005             5.<number>                 ©Silberschatz, Korth and Sudarshan
Non­Monotonicity
             s Procedure Datalog­Fixpoint is sound provided the rules in the program 
                   are monotonic.
                     q   Otherwise, it may make some inferences in an iteration that 
                         cannot be made in a later iteration.   E.g. given the rules
                               a :­  not b.
                               b :­  c.
                               c. 
                          Then a can be inferred initially, before b is inferred, but not later.
             s We can extend the procedure to handle negation so long as the 
                   program is “stratified”:  intuitively, so long as negation is not mixed 
                   with recursion




Database System Concepts , 5th Ed., Aug 2005         5.<number>                  ©Silberschatz, Korth and Sudarshan
Non­Monotonicity (Cont.)
             s There are useful queries that cannot be expressed by a stratified 
                   program
                     q   Example: given information about the number of each subpart in 
                         each part, in a part­subpart hierarchy, find the total number of 
                         subparts of each part.
                     q   A program to compute the above query would have to mix 
                         aggregation with recursion
                     q   However, so long as the underlying data (part­subpart) has no 
                         cycles, it is possible to write a program that mixes aggregation 
                         with recursion, yet has a clear meaning
                     q   There are ways to evaluate some such classes of non­stratified 
                         programs




Database System Concepts , 5th Ed., Aug 2005        5.<number>               ©Silberschatz, Korth and Sudarshan
End of Chapter 5




Database System Concepts, 5th Ed.
     ©Silberschatz, Korth and Sudarshan
See www.db­book.com for conditions on re­use 
Figure 5.1




Database System Concepts , 5th Ed., Aug 2005     5.<number>   ©Silberschatz, Korth and Sudarshan
Figure 5.2




Database System Concepts , 5th Ed., Aug 2005     5.<number>   ©Silberschatz, Korth and Sudarshan
Figure 5.5




Database System Concepts , 5th Ed., Aug 2005     5.<number>   ©Silberschatz, Korth and Sudarshan
Figure 5.6




Database System Concepts , 5th Ed., Aug 2005     5.<number>   ©Silberschatz, Korth and Sudarshan
Figure 5.9




Database System Concepts , 5th Ed., Aug 2005     5.<number>   ©Silberschatz, Korth and Sudarshan
Figure in­5.2




Database System Concepts , 5th Ed., Aug 2005      5.<number>   ©Silberschatz, Korth and Sudarshan
Figure in­5.15




Database System Concepts , 5th Ed., Aug 2005       5.<number>   ©Silberschatz, Korth and Sudarshan
Figure in­5.18




Database System Concepts , 5th Ed., Aug 2005       5.<number>   ©Silberschatz, Korth and Sudarshan
Figure in­5­31




Database System Concepts , 5th Ed., Aug 2005       5.<number>   ©Silberschatz, Korth and Sudarshan
Figure in­5.36




Database System Concepts , 5th Ed., Aug 2005       5.<number>   ©Silberschatz, Korth and Sudarshan

Más contenido relacionado

La actualidad más candente

Сергей Кольцов —НИУ ВШЭ —ICBDA 2015
Сергей Кольцов —НИУ ВШЭ —ICBDA 2015Сергей Кольцов —НИУ ВШЭ —ICBDA 2015
Сергей Кольцов —НИУ ВШЭ —ICBDA 2015rusbase
 
Discrete form of the riccati equation
Discrete form of the riccati equationDiscrete form of the riccati equation
Discrete form of the riccati equationAlberth Carantón
 
Probabilistic information retrieval models & systems
Probabilistic information retrieval models & systemsProbabilistic information retrieval models & systems
Probabilistic information retrieval models & systemsSelman Bozkır
 
Probabilistic Retrieval
Probabilistic RetrievalProbabilistic Retrieval
Probabilistic Retrievalotisg
 
13 multiplication and division of rational expressions
13 multiplication and division of rational expressions13 multiplication and division of rational expressions
13 multiplication and division of rational expressionselem-alg-sample
 
55 addition and subtraction of rational expressions
55 addition and subtraction of rational expressions 55 addition and subtraction of rational expressions
55 addition and subtraction of rational expressions alg1testreview
 
Week 8 (trees)
Week 8 (trees)Week 8 (trees)
Week 8 (trees)amna izzat
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)Trupti Agrawal
 

La actualidad más candente (10)

Сергей Кольцов —НИУ ВШЭ —ICBDA 2015
Сергей Кольцов —НИУ ВШЭ —ICBDA 2015Сергей Кольцов —НИУ ВШЭ —ICBDA 2015
Сергей Кольцов —НИУ ВШЭ —ICBDA 2015
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 
Discrete form of the riccati equation
Discrete form of the riccati equationDiscrete form of the riccati equation
Discrete form of the riccati equation
 
Probabilistic information retrieval models & systems
Probabilistic information retrieval models & systemsProbabilistic information retrieval models & systems
Probabilistic information retrieval models & systems
 
Pl vol1
Pl vol1Pl vol1
Pl vol1
 
Probabilistic Retrieval
Probabilistic RetrievalProbabilistic Retrieval
Probabilistic Retrieval
 
13 multiplication and division of rational expressions
13 multiplication and division of rational expressions13 multiplication and division of rational expressions
13 multiplication and division of rational expressions
 
55 addition and subtraction of rational expressions
55 addition and subtraction of rational expressions 55 addition and subtraction of rational expressions
55 addition and subtraction of rational expressions
 
Week 8 (trees)
Week 8 (trees)Week 8 (trees)
Week 8 (trees)
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 

Destacado (7)

Relational database concept
Relational database conceptRelational database concept
Relational database concept
 
Upgrading Oracle 9i To Oracle 11g
Upgrading Oracle 9i To Oracle 11gUpgrading Oracle 9i To Oracle 11g
Upgrading Oracle 9i To Oracle 11g
 
Ch3
Ch3Ch3
Ch3
 
Ch2
Ch2Ch2
Ch2
 
Ch14
Ch14Ch14
Ch14
 
Ch4
Ch4Ch4
Ch4
 
Indexing and hashing
Indexing and hashingIndexing and hashing
Indexing and hashing
 

Similar a Ch5

Similar a Ch5 (20)

Dbms module ii
Dbms module iiDbms module ii
Dbms module ii
 
Cs501 trc drc
Cs501 trc drcCs501 trc drc
Cs501 trc drc
 
Ch6 formal relational query languages
Ch6 formal relational query languages Ch6 formal relational query languages
Ch6 formal relational query languages
 
ch6.ppt
ch6.pptch6.ppt
ch6.ppt
 
DBMS ppt (1).pptx
DBMS ppt (1).pptxDBMS ppt (1).pptx
DBMS ppt (1).pptx
 
DBMS Formal Relational Query Languages Relational Calculus.pdf
DBMS Formal Relational Query Languages Relational Calculus.pdfDBMS Formal Relational Query Languages Relational Calculus.pdf
DBMS Formal Relational Query Languages Relational Calculus.pdf
 
Ch4
Ch4Ch4
Ch4
 
1643 y є r relational calculus-1
1643 y є r  relational calculus-11643 y є r  relational calculus-1
1643 y є r relational calculus-1
 
jhbuhbhujnhyubhbuybuybuybbuhyybuybuybuybybyubyubybybb
jhbuhbhujnhyubhbuybuybuybbuhyybuybuybuybybyubyubybybbjhbuhbhujnhyubhbuybuybuybbuhyybuybuybuybybyubyubybybb
jhbuhbhujnhyubhbuybuybuybbuhyybuybuybuybybyubyubybybb
 
ch2.ppt
ch2.pptch2.ppt
ch2.ppt
 
CHAPTER 2 DBMS IN EASY WAY BY MILAN PATEL
CHAPTER 2 DBMS IN EASY WAY BY  MILAN PATELCHAPTER 2 DBMS IN EASY WAY BY  MILAN PATEL
CHAPTER 2 DBMS IN EASY WAY BY MILAN PATEL
 
Database system by VISHAL PATIL
Database system by VISHAL PATILDatabase system by VISHAL PATIL
Database system by VISHAL PATIL
 
Relational Model
Relational ModelRelational Model
Relational Model
 
Ch4
Ch4Ch4
Ch4
 
03 Relational Databases.ppt
03 Relational Databases.ppt03 Relational Databases.ppt
03 Relational Databases.ppt
 
Ch3 a
Ch3 aCh3 a
Ch3 a
 
Ch3
Ch3Ch3
Ch3
 
Ch2
Ch2Ch2
Ch2
 
Ch3
Ch3Ch3
Ch3
 
relational algebra and calculus queries .ppt
relational algebra and calculus queries .pptrelational algebra and calculus queries .ppt
relational algebra and calculus queries .ppt
 

Más de Subhankar Chowdhury (15)

Ch20
Ch20Ch20
Ch20
 
Ch19
Ch19Ch19
Ch19
 
Ch17
Ch17Ch17
Ch17
 
Ch16
Ch16Ch16
Ch16
 
Ch15
Ch15Ch15
Ch15
 
Ch13
Ch13Ch13
Ch13
 
Ch12
Ch12Ch12
Ch12
 
Ch11
Ch11Ch11
Ch11
 
Ch10
Ch10Ch10
Ch10
 
Ch9
Ch9Ch9
Ch9
 
Ch8
Ch8Ch8
Ch8
 
Ch6
Ch6Ch6
Ch6
 
Ch1
Ch1Ch1
Ch1
 
Ch22
Ch22Ch22
Ch22
 
Ch21
Ch21Ch21
Ch21
 

Último

FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607dollysharma2066
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCRashishs7044
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesKeppelCorporation
 
Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfrichard876048
 
Fordham -How effective decision-making is within the IT department - Analysis...
Fordham -How effective decision-making is within the IT department - Analysis...Fordham -How effective decision-making is within the IT department - Analysis...
Fordham -How effective decision-making is within the IT department - Analysis...Peter Ward
 
Financial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptxFinancial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptxsaniyaimamuddin
 
Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy Verified Accounts
 
Guide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFGuide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFChandresh Chudasama
 
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Doge Mining Website
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Servicecallgirls2057
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessSeta Wicaksana
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607dollysharma2066
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Riya Pathan
 
Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Anamaria Contreras
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCRashishs7044
 
TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024Adnet Communications
 
Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524najka9823
 

Último (20)

FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation Slides
 
Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdf
 
Fordham -How effective decision-making is within the IT department - Analysis...
Fordham -How effective decision-making is within the IT department - Analysis...Fordham -How effective decision-making is within the IT department - Analysis...
Fordham -How effective decision-making is within the IT department - Analysis...
 
Financial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptxFinancial-Statement-Analysis-of-Coca-cola-Company.pptx
Financial-Statement-Analysis-of-Coca-cola-Company.pptx
 
Corporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information TechnologyCorporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information Technology
 
Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail Accounts
 
Guide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDFGuide Complete Set of Residential Architectural Drawings PDF
Guide Complete Set of Residential Architectural Drawings PDF
 
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
Unlocking the Future: Explore Web 3.0 Workshop to Start Earning Today!
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
 
Call Us ➥9319373153▻Call Girls In North Goa
Call Us ➥9319373153▻Call Girls In North GoaCall Us ➥9319373153▻Call Girls In North Goa
Call Us ➥9319373153▻Call Girls In North Goa
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful Business
 
No-1 Call Girls In Goa 93193 VIP 73153 Escort service In North Goa Panaji, Ca...
No-1 Call Girls In Goa 93193 VIP 73153 Escort service In North Goa Panaji, Ca...No-1 Call Girls In Goa 93193 VIP 73153 Escort service In North Goa Panaji, Ca...
No-1 Call Girls In Goa 93193 VIP 73153 Escort service In North Goa Panaji, Ca...
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
 
Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737Independent Call Girls Andheri Nightlaila 9967584737
Independent Call Girls Andheri Nightlaila 9967584737
 
Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.Traction part 2 - EOS Model JAX Bridges.
Traction part 2 - EOS Model JAX Bridges.
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
 
TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024TriStar Gold Corporate Presentation - April 2024
TriStar Gold Corporate Presentation - April 2024
 
Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524Call Girls Contact Number Andheri 9920874524
Call Girls Contact Number Andheri 9920874524
 

Ch5

  • 1. Chapter 5: Other Relational Languages  Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See www.db­book.com for conditions on re­use 
  • 2. Chapter 5:  Other Relational Languages s Tuple Relational Calculus s Domain Relational Calculus s Query­by­Example (QBE) s Datalog Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 3. Tuple Relational Calculus s A nonprocedural query language, where each query is of the form {t | P (t ) } s It is the set of all tuples t such that predicate P is true for t s t is a tuple variable, t [A ] denotes the value of tuple t on attribute A s t ∈ r denotes that tuple t is in relation r s P is a formula similar to that of the predicate calculus Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 4. Predicate Calculus Formula 1. Set of attributes and constants 2. Set of comparison operators:  (e.g., <, ≤, =, ≠, >, ≥) 3. Set of connectives:  and (∧), or (v)‚ not (¬) 4. Implication (⇒): x ⇒ y, if x if true, then y is true x ⇒ y ≡ ¬x v y 5. Set of quantifiers: ∃ t ∈ r (Q (t )) ≡ ”there exists” a tuple in t in relation r                         such that predicate Q (t ) is true ∀t ∈ r (Q (t )) ≡ Q is true “for all” tuples t in relation r Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 5. Banking Example s branch (branch_name, branch_city, assets )  s customer (customer_name, customer_street, customer_city )  s account (account_number, branch_name, balance )  s loan (loan_number, branch_name, amount ) s depositor (customer_name, account_number ) s borrower (customer_name, loan_number ) Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 6. Example Queries s Find the loan_number, branch_name, and amount for loans of over  $1200 {t | t ∈ loan ∧ t [amount ] > 1200} s  Find the loan number for each loan of an amount greater than $1200         {t | ∃ s ∈ loan (t [loan_number ] = s [loan_number ] ∧ s [amount ] > 1200)}      Notice that a relation on schema [loan_number ] is implicitly defined by                  the query Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 7. Example Queries s Find the names of all customers having a loan, an account, or both at  the bank {t | ∃s ∈ borrower ( t [customer_name ] = s [customer_name ])      ∨ ∃u ∈ depositor ( t [customer_name ] = u [customer_name ]) s   Find the names of all customers who have a loan and an account        at the bank {t | ∃s ∈ borrower ( t [customer_name ] = s [customer_name ])       ∧ ∃u ∈ depositor ( t [customer_name ] = u [customer_name] ) Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 8. Example Queries s Find the names of all customers having a loan at the Perryridge branch {t | ∃s ∈ borrower (t [customer_name ] = s [customer_name ]       ∧ ∃u ∈ loan (u [branch_name ] = “Perryridge”                          ∧  u [loan_number ] = s [loan_number ]))} s  Find the names of all customers who have a loan at the       Perryridge branch, but no account at any branch of the bank {t | ∃s ∈ borrower (t [customer_name ] = s [customer_name ]        ∧ ∃u ∈ loan (u [branch_name ] = “Perryridge”                            ∧  u [loan_number ] = s [loan_number ]))        ∧ not ∃v ∈ depositor (v [customer_name ] =                                                        t [customer_name ])} Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 9. Example Queries s Find the names of all customers having a loan from the Perryridge  branch, and the cities in which they live {t | ∃s ∈ loan (s [branch_name ] = “Perryridge”         ∧ ∃u ∈ borrower (u [loan_number ] = s [loan_number ]     ∧  t [customer_name ] = u [customer_name ])             ∧ ∃ v ∈ customer (u [customer_name ] = v [customer_name ]                                  ∧  t [customer_city ] = v [customer_city ])))} Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 10. Example Queries s Find the names of all customers who have an account at all branches  located in Brooklyn: {t | ∃ r ∈ customer (t [customer_name ] = r [customer_name ]) ∧     ( ∀ u ∈ branch (u [branch_city ] = “Brooklyn” ⇒           ∃ s ∈ depositor (t [customer_name ] = s [customer_name ]           ∧ ∃ w ∈ account ( w[account_number ] = s [account_number ]           ∧ ( w [branch_name ] = u [branch_name ]))))} Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 11. Safety of Expressions s It is possible to write tuple calculus expressions that generate infinite  relations. s For example, { t | ¬ t ∈ r } results in an infinite relation if the domain of  any attribute of relation r is infinite s To guard against the problem, we restrict the set of allowable  expressions to safe expressions. s An expression {t | P (t )} in the tuple relational calculus is safe if every  component of t appears in one of the relations, tuples, or constants that  appear in P q NOTE: this is more than just a syntax condition.   E.g. { t | t [A] = 5 ∨ true } is not safe ­­­ it defines an infinite set  with attribute values that do not appear in any relation or tuples  or constants in P.  Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 12. Domain Relational Calculus s A nonprocedural query language equivalent in power to the tuple  relational calculus s Each query is an expression of the form: { < x1, x2, …, xn > | P (x1, x2, …, xn)} q x1, x2, …, xn  represent domain variables q P represents a formula similar to that of the predicate calculus Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 13. Example Queries s Find the loan_number, branch_name, and  amount for loans of over $1200  {< l, b, a > | < l, b, a > ∈ loan ∧ a > 1200} s Find the names of all customers who have a loan of over $1200    {< c > | ∃ l, b, a (< c, l > ∈ borrower ∧ < l, b, a > ∈ loan ∧ a > 1200)} s Find the names of all customers who have a loan from the Perryridge branch  and the loan amount: {< c, a > | ∃ l (< c, l > ∈ borrower ∧ ∃b (< l, b, a > ∈ loan ∧                                                                                            b = “Perryridge”))} {< c, a > | ∃ l (< c, l > ∈ borrower ∧ < l, “ Perryridge”, a > ∈ loan)}          Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 14. Example Queries s Find the names of all customers having a loan, an account, or both at  the Perryridge branch: {< c > | ∃ l ( < c, l > ∈ borrower                   ∧ ∃ b,a (< l, b, a > ∈ loan ∧ b = “Perryridge”))        ∨ ∃ a (< c, a > ∈ depositor                  ∧ ∃ b,n (< a, b, n > ∈ account ∧ b = “Perryridge”))} s  Find the names of all customers who have an account at all       branches located in Brooklyn: {< c > | ∃ s,n (< c, s, n > ∈ customer) ∧             ∀ x,y,z (< x, y, z > ∈ branch ∧ y = “Brooklyn”) ⇒                 ∃ a,b (< x, y, z > ∈ account ∧ < c,a > ∈ depositor)}  Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 15. Safety of Expressions The expression: { < x1, x2, …, xn > | P (x1, x2, …, xn )} is safe if all of the following hold: 4. All values that appear in tuples of the expression are values  from dom (P ) (that is, the values appear either in P or in a tuple of a  relation mentioned in P ). 5. For every “there exists” subformula of the form ∃ x (P1(x )), the  subformula is true if and only if there is a value of x in dom (P1) such that P1(x ) is true. 6. For every “for all” subformula of the form ∀x (P1 (x )), the subformula is  true if and only if P1(x ) is true for all values x  from dom (P1). Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 16. Query­by­Example (QBE) s Basic Structure s Queries on One Relation s Queries on Several Relations s The Condition Box s The Result Relation s Ordering the Display of Tuples s Aggregate Operations  s Modification of the Database Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 17. QBE — Basic Structure s A graphical query language which is based (roughly) on the domain  relational calculus s Two dimensional syntax – system creates templates of relations that  are requested by users s Queries are expressed “by example” Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 20. Queries on One Relation s Find all loan numbers at the Perryridge branch. q   _x is a variable (optional; can be omitted in above query) q   P. means print (display) q   duplicates are removed by default q   To retain duplicates use P.ALL  Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 21. Queries on One Relation (Cont.) s Display full details of all loans q Method 1: P._x P._y P._z q Method 2: Shorthand notation Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 22. Queries on One Relation (Cont.) s Find the loan number of all loans with a loan amount of more than $700 s Find names of all branches that are not located in Brooklyn Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 23. Queries on One Relation (Cont.) s Find the loan numbers of all loans made jointly to Smith and  Jones. s Find all customers who live in the same city as Jones Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 24. Queries on Several Relations s Find the names of all customers who have a loan from the  Perryridge branch. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 25. Queries on Several Relations (Cont.) s Find the names of all customers who have both an account and a loan  at the bank. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 26. Negation in QBE s Find the names of all customers who have an account at the bank,  but do not have a loan from the bank. ¬ means “there does not exist” Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 27. Negation in QBE (Cont.) s Find all customers who have at least two accounts. ¬ means “not equal to” Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 28. The Condition Box s Allows the expression of constraints on domain variables that are  either inconvenient or impossible to express within the skeleton  tables. s Complex conditions can be used in condition boxes s Example: Find the loan numbers of all loans made to Smith, to  Jones, or to both jointly Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 29. Condition Box (Cont.) s QBE supports an interesting syntax for expressing alternative values Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 30. Condition Box (Cont.) s Find all account numbers with a balance greater than $1,300 and less than  $1,500  s Find all account numbers with a balance greater than $1,300 and  less than  $2,000 but not exactly $1,500. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 31. Condition Box (Cont.) s Find all branches that have assets greater than those of at least one  branch located in Brooklyn Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 32. The Result Relation s Find the customer_name, account_number, and balance for all  customers who have an account at the Perryridge branch. q We need to:  Join depositor and account.  Project customer_name, account_number and balance. q To accomplish this we:  Create a skeleton table, called result, with attributes  customer_name, account_number, and balance.  Write the query. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 33. The Result Relation (Cont.) s The resulting query is:  Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 34. Ordering the Display of Tuples s AO = ascending order; DO = descending order. s Example: list in ascending alphabetical order all customers who have an  account at the bank s When sorting on multiple attributes, the sorting order is specified by  including with each sort operator (AO or DO) an integer surrounded by  parentheses. s Example: List all account numbers at the Perryridge branch in ascending  alphabetic order with their respective account balances in descending order. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 35. Aggregate Operations s The aggregate operators are AVG, MAX, MIN, SUM, and CNT s The above operators must be postfixed with “ALL” (e.g., SUM.ALL.  or AVG.ALL._x) to ensure that duplicates are not eliminated. s Example: Find the total balance of all the accounts maintained at  the Perryridge branch. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 36. Aggregate Operations (Cont.) s UNQ is used to specify that we want to eliminate duplicates  s Find the total number of customers having an account at the bank. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 37. Query Examples s Find the average balance at each branch. s The “G” in “P.G” is analogous to SQL’s group by construct  s The “ALL” in the “P.AVG.ALL” entry in the balance column ensures that  all balances are considered s To find the average account balance at only those branches where the  average account balance is more than  $1,200, we simply add the  condition box: Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 38. Query Example s Find all customers who have an account at all branches located in  Brooklyn.   q Approach:  for each customer, find the number of branches in  Brooklyn at which they have accounts, and compare with total  number of branches in Brooklyn q QBE does not provide subquery functionality, so both above tasks  have to be combined in a single query.    Can be done for this query, but there are queries that require  subqueries and cannot always be expressed in QBE. s In the query on the next page CNT.UNQ.ALL._w specifies the number of distinct branches in  Brooklyn.  Note: The variable _w is not connected to other variables  in the query CNT.UNQ.ALL._z specifies the number of distinct branches in  Brooklyn at which customer x has an account. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 39. Query Example (Cont.) Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 40. Modification of the Database – Deletion s Deletion of tuples from a relation is expressed by use of a D. command.   In the case where we delete information in only some of the columns,  null values, specified by –, are inserted. s Delete customer Smith s Delete the branch_city value of the branch whose name is “Perryridge”. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 41. Deletion Query Examples s Delete all loans with a loan amount greater than $1300 and  less than  $1500. q For consistency, we have to delete information from loan and  borrower tables Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 42. Deletion Query Examples (Cont.) s Delete all accounts at branches located in Brooklyn. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 43. Modification of the Database – Insertion s Insertion is done by placing the I. operator in the query  expression.  s Insert the fact that account A­9732 at the Perryridge branch has  a balance of $700. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 44. Modification of the Database – Insertion (Cont.) s Provide as a gift for all loan customers of the Perryridge branch, a new  $200 savings account for every loan account they have, with the loan  number serving as the account number for the new savings account.   Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 45. Modification of the Database – Updates s Use the U. operator to change a value in a tuple without changing all   values in the tuple. QBE does not allow users to update the primary key  fields. s Update the asset value of the Perryridge branch to $10,000,000.  s Increase all balances by 5 percent. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 46. Microsoft Access QBE s Microsoft Access supports a variant of QBE called Graphical Query By  Example (GQBE) s GQBE differs from QBE in the following ways q Attributes of relations are listed vertically, one below the other,  instead of horizontally q Instead of using variables, lines (links) between attributes are used  to specify that their values should be the same.  Links are added automatically on the basis of attribute name,   and the user can then add or delete links  By default, a link specifies an inner join, but can be modified to  specify outer joins. q Conditions, values to be printed, as well as group by attributes are all  specified together in a box called the design grid Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 47. An Example Query in Microsoft Access QBE s Example query: Find the customer_name, account_number and balance  for all accounts at the Perryridge branch Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 48. An Aggregation Query in Access QBE s Find the name, street and city of all customers who have more than one  account at the bank Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 49. Aggregation in Access QBE s The row labeled Total specifies  q which attributes are group by attributes q which attributes are to be aggregated upon (and the aggregate  function).   q For attributes that are neither group by nor aggregated, we can  still specify conditions by selecting where in the Total row and  listing the conditions below s As in SQL, if group by is used, only group by attributes and aggregate  results can be output Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 50. Datalog s Basic Structure  s Syntax of Datalog Rules s Semantics of Nonrecursive Datalog s Safety  s Relational Operations in Datalog s Recursion in Datalog s The Power of Recursion Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 51. Basic Structure s Prolog­like logic­based language that allows recursive queries; based on  first­order logic. s A Datalog program consists of a set of rules that define views.  s Example:  define a view relation v1 containing account numbers and  balances for accounts at the Perryridge branch with a balance of over  $700. v1 (A, B ) :– account (A, “Perryridge”, B ), B > 700. s Retrieve the balance of account number “A­217” in the view relation v1. ? v1 (“A­217”, B ). s To find account number and balance of all accounts in v1 that have a  balance greater than 800                                 ? v1 (A,B ), B > 800 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 52. Example Queries s Each rule defines a set of tuples that a view relation must contain. q E.g.    v1 (A, B ) :– account (A, “ Perryridge”, B ), B > 700    is  read as         for all A, B         if (A, “Perryridge”, B )  ∈ account and  B > 700         then (A, B )  ∈ v1 s The set of tuples in a view relation is then defined as the union of all the  sets of tuples defined by the rules for the view relation. s Example: interest_rate (A, 5) :– account (A, N, B ) , B < 10000 interest_rate (A, 6) :– account (A, N, B ), B >= 10000 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 53. Negation in Datalog s Define a view relation c that contains the names of all customers who  have a deposit but no loan at the bank: c(N) :– depositor (N, A), not is_borrower (N). is_borrower (N) :–borrower (N,L). s NOTE: using  not borrower (N, L) in the first rule results in a different  meaning, namely there is some loan L for which N is not a borrower.   q To prevent such confusion, we require all variables in negated  “predicate” to also be present in non­negated predicates Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 54. Named Attribute Notation s Datalog rules use a positional notation that is convenient for relations with a  small number of attributes s It is easy to extend Datalog to support named attributes.   q E.g.,  v1 can be defined using named attributes as     v1 (account_number A, balance B ) :–    account (account_number A, branch_name “ Perryridge”, balance B ),   B > 700. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 55. Formal Syntax and Semantics of Datalog s We formally define the syntax and semantics (meaning) of Datalog  programs, in the following steps 1. We define the syntax of predicates, and then the syntax of rules 2. We define the semantics of individual rules 3. We define the semantics of non­recursive programs, based on a  layering of rules 4. It is possible to write rules that can generate an infinite number of  tuples in the view relation. To prevent this, we define what rules  are “safe”.  Non­recursive programs containing only safe rules  can only generate a finite number of answers. 5. It is possible to write recursive programs whose meaning is  unclear.  We define what recursive programs are acceptable, and  define their meaning. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 56. Syntax of Datalog Rules s A positive literal has the form p (t1, t2 ..., tn ) q p is the name of a relation with n attributes q each ti is either a constant or variable s A negative literal has the form  not p (t1, t2 ..., tn ) s Comparison operations are treated as positive predicates  q E.g.  X  > Y is treated as a predicate >(X,Y ) q “>” is conceptually an (infinite) relation that contains all pairs of  values such that the first value is greater than the second value s Arithmetic operations are also treated as predicates q E.g.  A = B + C  is treated as +(B, C, A), where the relation “+”  contains all triples such that the third value is the sum of the first two Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 57. Syntax of Datalog Rules (Cont.) s Rules are built out of literals and have the form: p (t1, t2, ..., tn ) :– L1, L2, ..., Lm.                          head                   body q each Li  is a literal q head – the literal p (t1, t2, ..., tn )  q body – the rest of the literals s A fact is a rule with an empty body, written in the form: p (v1, v2, ..., vn ). q indicates tuple (v1, v2, ..., vn ) is in relation p s A Datalog program is a set of rules Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 58. Semantics of a Rule s A ground instantiation of a rule (or simply instantiation) is the result  of replacing each variable in the rule by some constant. q Eg. Rule defining v1     v1(A,B) :– account (A,“Perryridge”, B ), B > 700. q An instantiation above rule:           v1 (“A­217”, 750) :–account ( “A­217”, “Perryridge”, 750), 750 > 700. s The body of rule instantiation R’ is satisfied in a set of facts (database  instance) l if 1. For each positive literal qi (vi,1, ..., vi,ni ) in the body of R’, l contains  the fact qi (vi,1, ..., vi,ni ). 2. For each negative literal not qj (vj,1, ..., vj,nj ) in the body of R’, l  does not contain the fact qj (vj,1, ..., vj,nj ). Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 59. Semantics of a Rule (Cont.) s We define the set of facts that can be inferred from a given set of facts l  using rule R as: infer(R, l) = { p (t1, ..., tn) | there is a ground instantiation R’ of R               where p (t1, ..., tn ) is the head of R’, and                the body of R’ is satisfied in l } s Given an set of rules ℜ = {R1, R2, ..., Rn}, we define infer(ℜ, l) = infer (R1, l ) ∪ infer (R2, l ) ∪ ... ∪ infer (Rn, l ) Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 60. Layering of Rules s Define the interest on each account in Perryridge interest(A, l) :– perryridge_account (A,B),                          interest_rate(A,R), l = B * R/100. perryridge_account(A,B) :– account (A, “Perryridge”, B). interest_rate (A,5) :– account (N, A, B), B < 10000. interest_rate (A,6) :– account (N, A, B), B >= 10000. s Layering of the view relations Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 61. Layering Rules (Cont.) Formally: s A relation is a layer 1 if all relations used in the bodies of rules defining  it are stored in the database. s A relation is a layer 2 if all relations used in the bodies of rules defining  it are either stored in the database, or are in layer 1. s A relation p is in layer i + 1 if  q it is not in layers 1, 2, ..., i q all relations used in the bodies of rules defining a p are either  stored in the database, or are in layers 1, 2, ..., i Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 62. Semantics of a Program Let the layers in a given program be 1, 2, ..., n.  Let ℜi denote the set of all rules defining view relations in layer i. s Define I  = set of facts stored in the database. 0 s Recursively define l  = l  ∪ infer (ℜ , l ) i+1 i i+1 i  s The set of facts in the view relations defined by the program  (also called the semantics of the program) is given by the set  of facts ln corresponding to the highest layer n. Note:  Can instead define semantics using view expansion like in relational algebra, but above definition is better for handling extensions such as recursion. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 63. Safety s It is possible to write rules that generate an infinite number of answers. gt(X, Y) :– X > Y not_in_loan (B, L) :– not loan (B, L) To avoid this possibility Datalog rules must satisfy the following  conditions. q Every variable that appears in the head of the rule also appears in  a non­arithmetic positive literal in the body of the rule.  This condition can be weakened in special cases based on the  semantics of arithmetic predicates, for example to permit the  rule p (A )  :­  q (B ), A = B + 1 q Every variable appearing in a negative literal in the body of the  rule also appears in some positive literal in the body of the rule. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 64. Relational Operations in Datalog s Project out attribute account_name from account. query (A) :–account (A, N, B ). s Cartesian product of relations r1 and r2. query (X1, X2, ..., Xn, Y1, Y1, Y2, ..., Ym ) :– r1 (X1, X2, ..., Xn ), r2 (Y1, Y2, ..., Ym ). s Union of relations r1 and r2.  query (X1, X2, ..., Xn ) :–r1 (X1, X2, ..., Xn ),   query (X1, X2, ..., Xn ) :–r2 (X1, X2, ..., Xn ),  s Set difference of r1 and r2. query (X1, X2, ..., Xn ) :–r1(X1, X2, ..., Xn ),                              not r2 (X1, X2, ..., Xn ),  Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 65. Recursion in Datalog s Suppose we are given a relation  manager (X, Y ) containing pairs of names X, Y such that Y is a manager of X (or  equivalently, X is a direct employee of Y). s  Each manager may have direct employees, as well as indirect  employees q Indirect employees of a manager, say Jones, are employees of  people who are direct employees of Jones, or recursively,  employees of people who are indirect employees of Jones s Suppose we wish to find all (direct and indirect) employees of manager  Jones.  We can write a recursive Datalog program.     empl_jones (X )  :­  manager (X, Jones ).     empl_jones (X )  :­  manager (X, Y ), empl_jones (Y ). Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 66. Semantics of Recursion in Datalog s Assumption (for now): program contains no negative literals s The view relations of a recursive program containing a set of rules ℜ are  defined to contain exactly the set of facts l  computed by the iterative procedure Datalog­Fixpoint procedure  Datalog­Fixpoint l = set of facts in the database repeat Old_l = l l = l  ∪ infer (ℜ, l ) until l = Old_l s At the end of the procedure, infer (ℜ, l ) ⊆  l q Infer (ℜ, l ) =  l  if we consider the database to be a set of facts that  are part of the program s l is called a fixed point of the program. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 68. A More General View s Create a view relation empl that contains every tuple (X, Y ) such  that X is directly or indirectly managed by Y. empl (X, Y ) :– manager (X, Y ). empl (X, Y ) :– manager (X, Z ), empl (Z, Y )  s Find the direct and indirect employees of Jones. ? empl (X, “Jones”). s Can define the view empl in another way too: empl (X, Y ) :– manager (X, Y ). empl (X, Y ) :– empl (X, Z ), manager (Z, Y ).  Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 69. The Power of Recursion s Recursive views make it possible to write queries, such as transitive  closure queries, that cannot be written without recursion or iteration. q Intuition:  Without recursion, a non­recursive non­iterative program  can perform only a fixed number of joins of manager with itself  This can give only a fixed number of levels of managers  Given a program we can construct a database with a greater  number of levels of managers on which the program will not work Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 70. Recursion in SQL s Starting with SQL:1999, SQL permits recursive view definition s E.g. query to find all employee­manager pairs      with recursive empl (emp, mgr ) as (                select emp, mgr                 from    manager         union                select manager.emp, empl.mgr                from   manager, empl                where manager.mgr = empl.emp       )     select *      from    empl Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 71. Monotonicity  s A view V is said to be monotonic if given any two sets of facts  I1 and I2 such that l1 ⊆ I2, then Ev (I1)  ⊆ Ev (I2 ), where Ev is the expression  used to define V. s A set of rules R is said to be monotonic if            l1 ⊆ I2  implies  infer (R, I1 ) ⊆ infer (R, I2 ),  s Relational algebra views defined using only the operations:  ∏, σ, ×, ∪, | X|, ∩, and ρ (as well as operations like natural join defined in terms of  these operations) are monotonic.  s Relational algebra views defined using set difference (–) may not be  monotonic. s Similarly, Datalog programs without negation are monotonic, but  Datalog programs with negation may not be monotonic. Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 72. Non­Monotonicity s Procedure Datalog­Fixpoint is sound provided the rules in the program  are monotonic. q Otherwise, it may make some inferences in an iteration that  cannot be made in a later iteration.   E.g. given the rules       a :­  not b.       b :­  c.       c.       Then a can be inferred initially, before b is inferred, but not later. s We can extend the procedure to handle negation so long as the  program is “stratified”:  intuitively, so long as negation is not mixed  with recursion Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 73. Non­Monotonicity (Cont.) s There are useful queries that cannot be expressed by a stratified  program q Example: given information about the number of each subpart in  each part, in a part­subpart hierarchy, find the total number of  subparts of each part. q A program to compute the above query would have to mix  aggregation with recursion q However, so long as the underlying data (part­subpart) has no  cycles, it is possible to write a program that mixes aggregation  with recursion, yet has a clear meaning q There are ways to evaluate some such classes of non­stratified  programs Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 74. End of Chapter 5 Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See www.db­book.com for conditions on re­use 
  • 75. Figure 5.1 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 76. Figure 5.2 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 77. Figure 5.5 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 78. Figure 5.6 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 79. Figure 5.9 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 80. Figure in­5.2 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 81. Figure in­5.15 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 82. Figure in­5.18 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 83. Figure in­5­31 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan
  • 84. Figure in­5.36 Database System Concepts , 5th Ed., Aug 2005 5.<number> ©Silberschatz, Korth and Sudarshan