SlideShare a Scribd company logo
1 of 84
Chapter 5: Other Relational
       Languages




         Database System Concepts, 1 st Ed.
 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 221002
         See www.vnsispl.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 – 1 st Ed.          5.2   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                    5.3   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                       5.4   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.            5.5   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                    5.6   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                  5.7   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                 5.8   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                  5.9   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                  5.10   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                       5.11   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                      5.12   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                       5.13   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                   5.14   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Safety of Expressions

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


              is safe if all of the following hold:
              n    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 ).
              n    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.
              n    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 – 1 st Ed.                           5.15   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.              5.16   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.              5.17   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
QBE Skeleton Tables for the Bank
                                      Example




Database System Concepts – 1 st Ed.     5.18   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
QBE Skeleton Tables (Cont.)




Database System Concepts – 1 st Ed.   5.19   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                        5.20   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                 5.21   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.             5.22   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.             5.23   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Queries on Several Relations

              s Find the names of all customers who have a loan from the
                   Perryridge branch.




Database System Concepts – 1 st Ed.            5.24   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.            5.25   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                5.26   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Negation in QBE (Cont.)

              s Find all customers who have at least two accounts.




                     ¬ means “not equal to”




Database System Concepts – 1 st Ed.             5.27   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                5.28   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Condition Box (Cont.)

              s QBE supports an interesting syntax for expressing alternative values




Database System Concepts – 1 st Ed.             5.29   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.               5.30   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Condition Box (Cont.)

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




Database System Concepts – 1 st Ed.              5.31   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                     5.32   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
The Result Relation (Cont.)

              s The resulting query is:




Database System Concepts – 1 st Ed.       5.33   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                5.34   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                5.35   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.             5.36   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.              5.37   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                    5.38   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Query Example (Cont.)




Database System Concepts – 1 st Ed.        5.39   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.               5.40   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                 5.41   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Deletion Query Examples (Cont.)

              s Delete all accounts at branches located in Brooklyn.




Database System Concepts – 1 st Ed.             5.42   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.               5.43   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.               5.44   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.               5.45   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                     5.46   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                5.47   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.             5.48   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                   5.49   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.            5.50   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                    5.51   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                   5.52   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                   5.53   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.              5.54   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                   5.55   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                       5.56     ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                          5.57   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                          5.58    ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                      5.59   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                     5.60   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                        5.61   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 I0 = set of facts stored in the database.

                       s Recursively define li+1 = li ∪ infer (ℜ i+1, li )

                       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
               Note: Can instead corresponding to the highest expansion like
                         of facts ln define semantics using view layer n.
               in relational algebra, but above definition is better for handling
               extensions such as recursion.




Database System Concepts – 1 st Ed.                    5.62   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                      5.63   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                          5.64   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                5.65   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                    5.66   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Example of Datalog-FixPoint
                                     Iteration




Database System Concepts – 1 st Ed.    5.67   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                   5.68   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                   5.69   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.             5.70   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                       5.71   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                    5.72   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
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 – 1 st Ed.                   5.73   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
End of Chapter 5




        Database System Concepts, 1 st Ed.
©VNS InfoSolutions Private Limited, Varanasi(UP), India 221002
        See www.vnsispl.com for conditions on re-use
Figure 5.1




Database System Concepts – 1 st Ed.      5.75   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Figure 5.2




Database System Concepts – 1 st Ed.      5.76   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Figure 5.5




Database System Concepts – 1 st Ed.      5.77   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Figure 5.6




Database System Concepts – 1 st Ed.      5.78   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Figure 5.9




Database System Concepts – 1 st Ed.      5.79   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Figure in-5.2




Database System Concepts – 1 st Ed.        5.80   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Figure in-5.15




Database System Concepts – 1 st Ed.        5.81   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Figure in-5.18




Database System Concepts – 1 st Ed.        5.82   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Figure in-5-31




Database System Concepts – 1 st Ed.        5.83   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
Figure in-5.36




Database System Concepts – 1 st Ed.        5.84   ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100

More Related Content

Viewers also liked

Viewers also liked (16)

VNSISPL_DBMS_Concepts_ch6
VNSISPL_DBMS_Concepts_ch6VNSISPL_DBMS_Concepts_ch6
VNSISPL_DBMS_Concepts_ch6
 
VNSISPL_DBMS_Concepts_ch11
VNSISPL_DBMS_Concepts_ch11VNSISPL_DBMS_Concepts_ch11
VNSISPL_DBMS_Concepts_ch11
 
VNSISPL_DBMS_Concepts_ch17
VNSISPL_DBMS_Concepts_ch17VNSISPL_DBMS_Concepts_ch17
VNSISPL_DBMS_Concepts_ch17
 
VNSISPL_DBMS_Concepts_ch14
VNSISPL_DBMS_Concepts_ch14VNSISPL_DBMS_Concepts_ch14
VNSISPL_DBMS_Concepts_ch14
 
ch3
ch3ch3
ch3
 
Introduction To DBMS
Introduction To DBMSIntroduction To DBMS
Introduction To DBMS
 
VNSISPL_DBMS_Concepts_appA
VNSISPL_DBMS_Concepts_appAVNSISPL_DBMS_Concepts_appA
VNSISPL_DBMS_Concepts_appA
 
VNSISPL_DBMS_Concepts_ch8
VNSISPL_DBMS_Concepts_ch8VNSISPL_DBMS_Concepts_ch8
VNSISPL_DBMS_Concepts_ch8
 
Relational Model
Relational ModelRelational Model
Relational Model
 
ch11
ch11ch11
ch11
 
VNSISPL_DBMS_Concepts_ch22
VNSISPL_DBMS_Concepts_ch22VNSISPL_DBMS_Concepts_ch22
VNSISPL_DBMS_Concepts_ch22
 
ch13
ch13ch13
ch13
 
ch6
ch6ch6
ch6
 
2 database system concepts and architecture
2 database system concepts and architecture2 database system concepts and architecture
2 database system concepts and architecture
 
Indexing and hashing
Indexing and hashingIndexing and hashing
Indexing and hashing
 
Computer Networks & mobile phone
Computer Networks & mobile phoneComputer Networks & mobile phone
Computer Networks & mobile phone
 

Similar to VNSISPL_DBMS_Concepts_ch5

VNSISPL_DBMS_Concepts_ch7
VNSISPL_DBMS_Concepts_ch7VNSISPL_DBMS_Concepts_ch7
VNSISPL_DBMS_Concepts_ch7sriprasoon
 
VNSISPL_DBMS_Concepts_ch2
VNSISPL_DBMS_Concepts_ch2VNSISPL_DBMS_Concepts_ch2
VNSISPL_DBMS_Concepts_ch2sriprasoon
 
VNSISPL_DBMS_Concepts_ch4
VNSISPL_DBMS_Concepts_ch4VNSISPL_DBMS_Concepts_ch4
VNSISPL_DBMS_Concepts_ch4sriprasoon
 
Vnsispl dbms concepts_ch3
Vnsispl dbms concepts_ch3Vnsispl dbms concepts_ch3
Vnsispl dbms concepts_ch3sriprasoon
 
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.pdfestorebackupr
 
VNSISPL_DBMS_Concepts_ch9
VNSISPL_DBMS_Concepts_ch9VNSISPL_DBMS_Concepts_ch9
VNSISPL_DBMS_Concepts_ch9sriprasoon
 
VNSISPL_DBMS_Concepts_ch18
VNSISPL_DBMS_Concepts_ch18VNSISPL_DBMS_Concepts_ch18
VNSISPL_DBMS_Concepts_ch18sriprasoon
 
Ch6 formal relational query languages
Ch6 formal relational query languages Ch6 formal relational query languages
Ch6 formal relational query languages uoitc
 
Database system by VISHAL PATIL
Database system by VISHAL PATILDatabase system by VISHAL PATIL
Database system by VISHAL PATILVishal Patil
 

Similar to VNSISPL_DBMS_Concepts_ch5 (15)

VNSISPL_DBMS_Concepts_ch7
VNSISPL_DBMS_Concepts_ch7VNSISPL_DBMS_Concepts_ch7
VNSISPL_DBMS_Concepts_ch7
 
VNSISPL_DBMS_Concepts_ch2
VNSISPL_DBMS_Concepts_ch2VNSISPL_DBMS_Concepts_ch2
VNSISPL_DBMS_Concepts_ch2
 
ch5
ch5ch5
ch5
 
VNSISPL_DBMS_Concepts_ch4
VNSISPL_DBMS_Concepts_ch4VNSISPL_DBMS_Concepts_ch4
VNSISPL_DBMS_Concepts_ch4
 
Dbms module ii
Dbms module iiDbms module ii
Dbms module ii
 
Vnsispl dbms concepts_ch3
Vnsispl dbms concepts_ch3Vnsispl dbms concepts_ch3
Vnsispl dbms concepts_ch3
 
DBMS ppt (1).pptx
DBMS ppt (1).pptxDBMS ppt (1).pptx
DBMS ppt (1).pptx
 
1643 y є r relational calculus-1
1643 y є r  relational calculus-11643 y є r  relational calculus-1
1643 y є r relational calculus-1
 
ch6.ppt
ch6.pptch6.ppt
ch6.ppt
 
Cs501 trc drc
Cs501 trc drcCs501 trc drc
Cs501 trc drc
 
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
 
VNSISPL_DBMS_Concepts_ch9
VNSISPL_DBMS_Concepts_ch9VNSISPL_DBMS_Concepts_ch9
VNSISPL_DBMS_Concepts_ch9
 
VNSISPL_DBMS_Concepts_ch18
VNSISPL_DBMS_Concepts_ch18VNSISPL_DBMS_Concepts_ch18
VNSISPL_DBMS_Concepts_ch18
 
Ch6 formal relational query languages
Ch6 formal relational query languages Ch6 formal relational query languages
Ch6 formal relational query languages
 
Database system by VISHAL PATIL
Database system by VISHAL PATILDatabase system by VISHAL PATIL
Database system by VISHAL PATIL
 

More from sriprasoon

VNSISPL_DBMS_Concepts_AppB
VNSISPL_DBMS_Concepts_AppBVNSISPL_DBMS_Concepts_AppB
VNSISPL_DBMS_Concepts_AppBsriprasoon
 
VNSISPL_DBMS_Concepts_AppC
VNSISPL_DBMS_Concepts_AppCVNSISPL_DBMS_Concepts_AppC
VNSISPL_DBMS_Concepts_AppCsriprasoon
 
VNSISPL_DBMS_Concepts_ch25
VNSISPL_DBMS_Concepts_ch25VNSISPL_DBMS_Concepts_ch25
VNSISPL_DBMS_Concepts_ch25sriprasoon
 
VNSISPL_DBMS_Concepts_ch24
VNSISPL_DBMS_Concepts_ch24VNSISPL_DBMS_Concepts_ch24
VNSISPL_DBMS_Concepts_ch24sriprasoon
 
VNSISPL_DBMS_Concepts_ch23
VNSISPL_DBMS_Concepts_ch23VNSISPL_DBMS_Concepts_ch23
VNSISPL_DBMS_Concepts_ch23sriprasoon
 
VNSISPL_DBMS_Concepts_ch21
VNSISPL_DBMS_Concepts_ch21VNSISPL_DBMS_Concepts_ch21
VNSISPL_DBMS_Concepts_ch21sriprasoon
 
VNSISPL_DBMS_Concepts_ch20
VNSISPL_DBMS_Concepts_ch20VNSISPL_DBMS_Concepts_ch20
VNSISPL_DBMS_Concepts_ch20sriprasoon
 
VNSISPL_DBMS_Concepts_ch19
VNSISPL_DBMS_Concepts_ch19VNSISPL_DBMS_Concepts_ch19
VNSISPL_DBMS_Concepts_ch19sriprasoon
 
VNSISPL_DBMS_Concepts_ch16
VNSISPL_DBMS_Concepts_ch16VNSISPL_DBMS_Concepts_ch16
VNSISPL_DBMS_Concepts_ch16sriprasoon
 
VNSISPL_DBMS_Concepts_ch15
VNSISPL_DBMS_Concepts_ch15VNSISPL_DBMS_Concepts_ch15
VNSISPL_DBMS_Concepts_ch15sriprasoon
 
VNSISPL_DBMS_Concepts_ch13
VNSISPL_DBMS_Concepts_ch13VNSISPL_DBMS_Concepts_ch13
VNSISPL_DBMS_Concepts_ch13sriprasoon
 
VNSISPL_DBMS_Concepts_ch12
VNSISPL_DBMS_Concepts_ch12VNSISPL_DBMS_Concepts_ch12
VNSISPL_DBMS_Concepts_ch12sriprasoon
 
VNSISPL_DBMS_Concepts_ch10
VNSISPL_DBMS_Concepts_ch10VNSISPL_DBMS_Concepts_ch10
VNSISPL_DBMS_Concepts_ch10sriprasoon
 
Vnsispl dbms concepts_ch1
Vnsispl dbms concepts_ch1Vnsispl dbms concepts_ch1
Vnsispl dbms concepts_ch1sriprasoon
 
Inventory Management
Inventory ManagementInventory Management
Inventory Managementsriprasoon
 

More from sriprasoon (15)

VNSISPL_DBMS_Concepts_AppB
VNSISPL_DBMS_Concepts_AppBVNSISPL_DBMS_Concepts_AppB
VNSISPL_DBMS_Concepts_AppB
 
VNSISPL_DBMS_Concepts_AppC
VNSISPL_DBMS_Concepts_AppCVNSISPL_DBMS_Concepts_AppC
VNSISPL_DBMS_Concepts_AppC
 
VNSISPL_DBMS_Concepts_ch25
VNSISPL_DBMS_Concepts_ch25VNSISPL_DBMS_Concepts_ch25
VNSISPL_DBMS_Concepts_ch25
 
VNSISPL_DBMS_Concepts_ch24
VNSISPL_DBMS_Concepts_ch24VNSISPL_DBMS_Concepts_ch24
VNSISPL_DBMS_Concepts_ch24
 
VNSISPL_DBMS_Concepts_ch23
VNSISPL_DBMS_Concepts_ch23VNSISPL_DBMS_Concepts_ch23
VNSISPL_DBMS_Concepts_ch23
 
VNSISPL_DBMS_Concepts_ch21
VNSISPL_DBMS_Concepts_ch21VNSISPL_DBMS_Concepts_ch21
VNSISPL_DBMS_Concepts_ch21
 
VNSISPL_DBMS_Concepts_ch20
VNSISPL_DBMS_Concepts_ch20VNSISPL_DBMS_Concepts_ch20
VNSISPL_DBMS_Concepts_ch20
 
VNSISPL_DBMS_Concepts_ch19
VNSISPL_DBMS_Concepts_ch19VNSISPL_DBMS_Concepts_ch19
VNSISPL_DBMS_Concepts_ch19
 
VNSISPL_DBMS_Concepts_ch16
VNSISPL_DBMS_Concepts_ch16VNSISPL_DBMS_Concepts_ch16
VNSISPL_DBMS_Concepts_ch16
 
VNSISPL_DBMS_Concepts_ch15
VNSISPL_DBMS_Concepts_ch15VNSISPL_DBMS_Concepts_ch15
VNSISPL_DBMS_Concepts_ch15
 
VNSISPL_DBMS_Concepts_ch13
VNSISPL_DBMS_Concepts_ch13VNSISPL_DBMS_Concepts_ch13
VNSISPL_DBMS_Concepts_ch13
 
VNSISPL_DBMS_Concepts_ch12
VNSISPL_DBMS_Concepts_ch12VNSISPL_DBMS_Concepts_ch12
VNSISPL_DBMS_Concepts_ch12
 
VNSISPL_DBMS_Concepts_ch10
VNSISPL_DBMS_Concepts_ch10VNSISPL_DBMS_Concepts_ch10
VNSISPL_DBMS_Concepts_ch10
 
Vnsispl dbms concepts_ch1
Vnsispl dbms concepts_ch1Vnsispl dbms concepts_ch1
Vnsispl dbms concepts_ch1
 
Inventory Management
Inventory ManagementInventory Management
Inventory Management
 

Recently uploaded

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 

Recently uploaded (20)

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 

VNSISPL_DBMS_Concepts_ch5

  • 1. Chapter 5: Other Relational Languages Database System Concepts, 1 st Ed. ©VNS InfoSolutions Private Limited, Varanasi(UP), India 221002 See www.vnsispl.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 – 1 st Ed. 5.2 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.3 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.4 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.5 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.6 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.7 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.8 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.9 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.10 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.11 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.12 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.13 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.14 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 15. Safety of Expressions The expression: { < x1, x2, … xn > | P (x1, x2, … xn )} , , is safe if all of the following hold: n 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 ). n 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. n 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 – 1 st Ed. 5.15 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.16 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.17 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 18. QBE Skeleton Tables for the Bank Example Database System Concepts – 1 st Ed. 5.18 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 19. QBE Skeleton Tables (Cont.) Database System Concepts – 1 st Ed. 5.19 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.20 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.21 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.22 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.23 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 24. Queries on Several Relations s Find the names of all customers who have a loan from the Perryridge branch. Database System Concepts – 1 st Ed. 5.24 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.25 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.26 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 27. Negation in QBE (Cont.) s Find all customers who have at least two accounts. ¬ means “not equal to” Database System Concepts – 1 st Ed. 5.27 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.28 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 29. Condition Box (Cont.) s QBE supports an interesting syntax for expressing alternative values Database System Concepts – 1 st Ed. 5.29 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.30 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.31 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.32 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 33. The Result Relation (Cont.) s The resulting query is: Database System Concepts – 1 st Ed. 5.33 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.34 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.35 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.36 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.37 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.38 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 39. Query Example (Cont.) Database System Concepts – 1 st Ed. 5.39 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.40 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.41 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 42. Deletion Query Examples (Cont.) s Delete all accounts at branches located in Brooklyn. Database System Concepts – 1 st Ed. 5.42 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 43. 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 – 1 st Ed. 5.43 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.44 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.45 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.46 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.47 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.48 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.49 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.50 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.51 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.52 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.53 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.54 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.55 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.56 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.57 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.58 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.59 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.60 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.61 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 I0 = set of facts stored in the database. s Recursively define li+1 = li ∪ infer (ℜ i+1, li ) 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 Note: Can instead corresponding to the highest expansion like of facts ln define semantics using view layer n. in relational algebra, but above definition is better for handling extensions such as recursion. Database System Concepts – 1 st Ed. 5.62 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.63 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.64 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.65 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.66 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 67. Example of Datalog-FixPoint Iteration Database System Concepts – 1 st Ed. 5.67 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.68 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.69 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.70 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.71 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.72 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 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 – 1 st Ed. 5.73 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 74. End of Chapter 5 Database System Concepts, 1 st Ed. ©VNS InfoSolutions Private Limited, Varanasi(UP), India 221002 See www.vnsispl.com for conditions on re-use
  • 75. Figure 5.1 Database System Concepts – 1 st Ed. 5.75 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 76. Figure 5.2 Database System Concepts – 1 st Ed. 5.76 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 77. Figure 5.5 Database System Concepts – 1 st Ed. 5.77 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 78. Figure 5.6 Database System Concepts – 1 st Ed. 5.78 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 79. Figure 5.9 Database System Concepts – 1 st Ed. 5.79 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 80. Figure in-5.2 Database System Concepts – 1 st Ed. 5.80 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 81. Figure in-5.15 Database System Concepts – 1 st Ed. 5.81 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 82. Figure in-5.18 Database System Concepts – 1 st Ed. 5.82 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 83. Figure in-5-31 Database System Concepts – 1 st Ed. 5.83 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100
  • 84. Figure in-5.36 Database System Concepts – 1 st Ed. 5.84 ©VNS InfoSolutions Private Limited, Varanasi(UP), India 22100