Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Database Management System: Dr. Pawan Singh Mehra, Department of CSE

Download as pdf or txt
Download as pdf or txt
You are on page 1of 124

Database Management System

By Dr. Pawan Singh Mehra

Course Code: CO-202


Module 2
Dr. Pawan Singh Mehra,
Department of CSE

1
Contents of Module-2
 Integrity constraints: Keys constraint, domain
By Dr. Pawan Singh Mehra

constraints, referential integrity constraint


 Relational algebra
 Relational calculus: domain and tuple calculus,
 SQL data definition queries and updates in SQL
 Assertions, triggers

2
Integrity Constraints
Constraints: It is the restriction imposed on the relation to
By Dr. Pawan Singh Mehra

ensure accuracy and consistency of the data.


Integrity Constraints are set of rules which the database is not
permitted to violate.
It ensures that the changes(Insert, update, delete) made in
database by authorized users do not result in a loss of data
consistency.
It guards against accidental damage to the database.

3
Types of Integrity Constraints

Entity Integrity Constraint


By Dr. Pawan Singh Mehra

Domain Integrity Constraint


Key Constraint
Referential Integrity Constraint

4
Entity Integrity Constraints
 It ensures that the Primary Key value should not be NULL.
By Dr. Pawan Singh Mehra

A table can contain a null value other than the primary key field.

Roll_No(PK) Name Aadhar_No Email_ID Roll_No Name Aadhar_No Email_ID


2K21CO01 Mohan 88213211 m@gmail.com 2K21CO01 Mohan 88213211 m@gmail.com
2K21EC02 Rohan 28341212 r@gmail.com 2K21EC02 Rohan 28341212 r@gmail.com
Abraham 65762231 a@gmail.com 2K21IT01 Abraham 65762231 a@gmail.com
2K21SW04 Vernika 98322212 v@gmail.com 2K21SW04 Vernika 98322212 v@gmail.com

NOT ALLOWED FOLLOWS ENTITY INTEGRITY CONSTRAINT

5
Domain Integrity Constraints
 It states that the domain or type for an attribute must be within
By Dr. Pawan Singh Mehra

its domain.
for example, integer types, character types, date/time types
Declaring an attribute to be of a particular domain acts as a
constraint on the values that it can take.
Roll_No(PK) Name Aadhar_No Email_ID Roll_No Name Aadhar_No Email_ID
2K21CO01 Mohan 88213211 m@gmail.com 2K21CO01 Mohan 88213211 m@gmail.com
2K21EC02 12345 28341212 r@gmail.com 2K21EC02 Rohan 28341212 r@gmail.com
Abraham ABC a@gmail.com 2K21IT01 Abraham 65762231 a@gmail.com
2K21SW04 Vernika 98322212 v@gmail.com 2K21SW04 Vernika 98322212 v@gmail.com
NOT ALLOWED FOLLOWS DOMAIN INTEGRITY CONSTRAINT

6
Key Constraints
 It ensures that every tuple in the relation should be unique
By Dr. Pawan Singh Mehra

 It specifies that in any relation


 Primary key must not be NULL
 All the values in Primary key attribute must be unique

Roll_No(PK) Name Aadhar_No Email_ID Roll_No Name Aadhar_No Email_ID


2K21CO01 Mohan 88213211 m@gmail.com 2K21CO01 Mohan 88213211 m@gmail.com
2K21CO01 Rohan 28341212 r@gmail.com 2K21EC02 Rohan 28341212 r@gmail.com
NULL Abraham 65762231 a@gmail.com 2K21IT01 Abraham 65762231 a@gmail.com
2K21CO01 Mohan 88213211 m@gmail.com 2K21SW04 Vernika 98322212 v@gmail.com
NOT ALLOWED FOLLOWS KEY CONSTRAINT

7
Referential Integrity Constraints
It is pertinent to Foreign Key.
By Dr. Pawan Singh Mehra

It is enforced when a Foreign Key references Primary Key of


another table.
Rules for referential integrity constraints
if a Foreign Key in Table 2 refers to the Primary Key of Table 1,
then either every value of the Foreign Key in Table 2 must be
available in Primary Key value of Table 1 or it must be NULL.
Record from Table 1 can’t be deleted if it exists in Table 2
A new value in FK in Table 2 cannot be added if it doesn’t exist
in Table 1. Instead NULL value can be added.
8
Referential Integrity Constraints
Roll_No(PK) Name Aadhar_No Email_ID Branch Course_ID Course_Name Roll_No(FK)
2K21CO01 Mohan 88213211 m@gmail.com CSE CO201 COA 2K21CO01
By Dr. Pawan Singh Mehra

2K21EC02 Rohan 28341212 r@gmail.com EC CO202 DBMS 2K21EC02


2K21IT03 Abraham 65762231 a@gmail.com IT CO203 OS 2K21ME03
2K21SW04 Vernika 98322212 v@gmail.com SWE CO204 DBMS NULL

Relation(Table 1): Student Relation(Table 2): Course

• 2K21ME03 does not exist in Table 1- NOT ALLOWED


• Deleting record of 2K21CO01- NOT ALLOWED
• Row 4 in Table 2 has NULL value- ALLOWED

9
Query Language
 It is language in which user requests information from the database.
 For example: SQL
By Dr. Pawan Singh Mehra

 Categories of languages
 Procedural
 User tells what data to be retrieved from DB and how to
retrieve it
 Non-procedural, or declarative
 User tells what data to be retrieved from DB and but does not
tell how to retrieve it.
 “Pure” languages: form underlying basis of query languages
 Relational Algebra
 Relational Calculus (Tuple relational calculus, Domain relational
calculus 10
Relational Algebra
 Procedural language
 Six basic operators
By Dr. Pawan Singh Mehra

 select: 
 project: 
 union: 
 set difference: –
 Cartesian product: x
 rename: 
 The operators take one or two relations as inputs and produce a new
relation as a result.
11
Select Operation()
 It selects tuples(rows) that satisfy the given condition from a relation
 Notation: (CONDITION)(name of relation).
By Dr. Pawan Singh Mehra

 The condition may use logic connectives like AND(˄), OR(˅) , NOT(!)
and relational operators like =, >, <, ≥, ≤, ≠ etc.

A B C D Query: select from r where A=B and D is greater than 5


  1 7
Expression: A=B ^ D > 5 (r)
  5 7 A B C D
  12 3
  23 10
Output:   1 7
  23 10
Relation r
12
Project Operation()
 A unary operation that returns its argument relation, with certain attributes
left out.
By Dr. Pawan Singh Mehra

 Notation:  A1,A2,A3 ….Ak (r)


where A1, A2, …, Ak are attribute names and r is a relation name.
 Duplicate rows removed from result, since relations are sets
A B C Query: select A,C from r A C A C
 10 1
Expression:  A,C (r)
 1  1
 20 1  1
Output:
 1
 30 1  1  2
 40 2  2
Relation r This will not be the output as
duplicate rows will be removed 13
Set Operations
 There are three set operations performed in relational algebra
 Union ()
By Dr. Pawan Singh Mehra

 Intersection (∩)
 Set Difference (-)
 Set operations are performed on two relations which are
compatible
 Two relations should be compatible if
 Both the relations should have same number of
attributes(columns)
 The attributes should have same domain(type)
 Duplicate tuples are removed automatically
Union Operation()
 Notation: r  s
 Defined as: r  s = {t | t  r or t  s}
By Dr. Pawan Singh Mehra

 For r  s to be valid.
 r, s must have the same arity (same number of attributes)
 The attribute domains must be compatible (example: 2nd column
of r deals with the same type of values as does the 2nd column of s)
A B
A B A B

 1  2 Expression:  A,B (r)   A,B (s)  1


Output:  2
 2  3
 1
 1
 3
Relation r Relation s 15
Set Difference Operation(–)
 Notation: r – s
 Defined as: r – s = {t | t  r and t  s}
By Dr. Pawan Singh Mehra

 For r – s to be valid.
 r, s must have the same arity (same number of attributes)
 The attribute domains must be compatible (example: 2nd column
of r deals with the same type of values as does the 2nd column of s)

A B A B
A B

 1  2 Expression:  A,B (r) -  A,B (s)  1


Output:
 2  3  1
 1

Relation r Relation s 16
Intersection Operation(∩)
 Notation: r ∩ s = r – (r – s)
 Defined as: r ∩ s = {t | t  r AND t  s}
By Dr. Pawan Singh Mehra

 For r ∩ s to be valid.
 r, s must have the same arity (same number of attributes)
 The attribute domains must be compatible (example: 2nd column
of r deals with the same type of values as does the 2nd column of s)

A B A B A B
Expression:  A,C (r) ∩  A,C (s) Output:
 1  2  2
 2  3
 1

Relation r Relation s 17
Cartesian Product Operation(×)
 Notation: r x s
By Dr. Pawan Singh Mehra

 Defined as: r x s = r x s = {t q | t  r and q  s}


 If attributes of r and s are not disjoint, then renaming must be
used

A B C D E
 1  10 a
A B C D E  1  10 a
Expression:  A,B,C,D,E (r x s)  1  20 b
 1  10 a  1  10 b
 2
 10 a Output:  2  10 a
 20 b  2  10 a
 10 b  2  20 b
18
Relation r Relation s  2  10 b
Rename Operation()
 Allows us to rename
By Dr. Pawan Singh Mehra

 Relation
 Attributes
 Relation and attributes both
 Notation:  x (E) returns the expression E under the name X
 Example 1: rename the relation Student as Male Student and the
attributes of Student – RollNo, SName as (Sno, Name)
ρMaleStudent(Sno,Name)πRollNo,SName(σCondition(Student))

19
Additional Operations
 Inner Join
 Theta Join
By Dr. Pawan Singh Mehra

 Equi-Join
 Natural Join
 Outer Join
 Left Outer Join
 Right Outer
 Full Outer Join
 Aggregate Functions
 Division

20
Join
 Notation:
 Join is an additional/derived operator which simplify the
By Dr. Pawan Singh Mehra

queries.
 It is a combination of a Cartesian Product followed by a
selection process
Join= Cartesian Product + Selection
 A join operation pairs two tuples from different relations, if
and only if the given condition is satisfied.
 A Condition B =  condition(A x B)

21
Inner Join
 An inner join includes only those tuples that satisfy the
By Dr. Pawan Singh Mehra

matching criteria, while the rest of the tuples are excluded.


 There are three types of inner joins
 Theta Join
 Equi Join
 Natural Join

22
Theta Join(Ɵ)
 It combines tuples from different relations provided they
satisfy the theta(Ɵ) condition.
By Dr. Pawan Singh Mehra

 It is a general case of join.


 It is used when we want to join two or more relation based
on some condition
 The join condition is denoted by the symbol Ɵ
 It uses all kinds of comparison operator like =, >, <, ≥, ≤, ≠ etc.
 Notation: A ƟB=  Ɵ(A x B)
Where Ɵ is a predicate/condition. It can use any comparison
operator like =, >, <, ≥, ≤, ≠ etc.

23
Theta Join(Ɵ)
A B C C D E
By Dr. Pawan Singh Mehra

 A 4 6  a
 B 3
r R.C>S.C s
2  b
 C 5 4 Ω c
Ω D 7 8  d

r s
A B r.C s.C D E
 A 4 2  b
 B 3 2  b
 C 5 2  b
 C 5 4 Ω c
Ω D 7 6  a
Ω D 7 2  b
Ω D 7 4 Ω c

Resultant table 24
Equi Join
 When a theta join uses only equivalence(=) condition, it is called Equi-
Join
By Dr. Pawan Singh Mehra

 It is a special case of theta join where condition contains equalities(=).


 Notation: A (equivalence condition) B =  equivalence condition (A x B)

25
Equi Join
A B C C D E
By Dr. Pawan Singh Mehra

 A 4 4  a
 B 3
r R.C=S.C s
2  b
 C 5 5 Ω c
Ω D 7 7  d
7  a
r
s
A B r.C s.C D E
 A 4 4  a
 C 5 5 Ω c
Ω D 7 7  d
Ω D 7 7  a

Resultant relation
26
Natural Join
 Notation: r s
 Let r and s be relations on schemas R and S respectively.
By Dr. Pawan Singh Mehra

Then, r s is a relation on schema R  S obtained as follows:


 Consider each pair of tuples tr from r and ts from s.
 If tr and ts have the same value on each of the attributes in R  S, add a
tuple t to the result, where
 t has the same value as tr on r
 t has the same value as ts on s
 Example:
 R = (A, B, C, D), S = (E, B, D)
 Resultant schema = (A, B, C, D, E)
 r s is defined as :r.A, r.B, r.C, r.D, s.E (r.B = s.B  r.D = s.D (r x s)) 27
Natural Join
By Dr. Pawan Singh Mehra

A B C D B D E A B C D E

 1  a 1 a   1  a 
 2  a 3 a  r s  1  a 
 4  b 1 a   1  a 
 1  a 2 b   1  a 
 2  b 3 b   2  b 

r s Resultant relation

28
Outer Join
An extension of the join operation that avoids loss of information.
By Dr. Pawan Singh Mehra

Computes the join and then adds tuples from one relation that does not
match tuples in the other relation to the result of the join.
Uses null values:
null signifies that the value is unknown or does not exist

29
Left Outer Join
Relation loan Relation borrower
loan_number branch_name amount customer_name loan_number
By Dr. Pawan Singh Mehra

L-170 Downtown 3000 Jones L-170


L-230 Redwood 4000 Smith L-230
L-260 Perryridge 1700 Hayes L-155

Left Outer Join


loan borrower
loan_number branch_name amount customer_name
L-170 Downtown 3000 Jones
L-230 Redwood 4000 Smith
L-260 Perryridge 1700 null 30
Right Outer Join
Relation loan Relation borrower
loan_number branch_name amount customer_name loan_number
By Dr. Pawan Singh Mehra

L-170 Downtown 3000 Jones L-170


L-230 Redwood 4000 Smith L-230
L-260 Perryridge 1700 Hayes L-155

Right Outer Join


loan borrower

loan_number branch_name amount customer_name

L-170 Downtown 3000 Jones


L-230 Redwood 4000 Smith
L-155 null null Hayes
31
Full Outer Join
Relation loan Relation borrower
loan_number branch_name amount customer_name loan_number
By Dr. Pawan Singh Mehra

L-170 Downtown 3000 Jones L-170


L-230 Redwood 4000 Smith L-230
L-260 Perryridge 1700 Hayes L-155

Full Outer Join


loan borrower
loan_number branch_name amount customer_name
L-170 Downtown 3000 Jones
L-230 Redwood 4000 Smith
L-260 Perryridge 1700 null
L-155 null null Hayes
32
Aggregate Function/Operation
Aggregation function takes a collection of values and returns a single
value as a result.
By Dr. Pawan Singh Mehra

avg: average value


min: minimum value
max: maximum value
sum: sum of values
count: number of values
Aggregate operation in relational algebra

G1 ,G 2 ,,G n
F ( A ),F
1 1 2 ( A2 ,,Fn ( An )
(E )
E is any relational-algebra expression
G1, G2 …, Gn is a list of attributes on which to group (can be empty)
Each Fi is an aggregate function
Each Ai is an attribute name 33
Aggregate Functions/Operation
Relation r
By Dr. Pawan Singh Mehra

A B C

  7 sum(c )
Expression: g sum(c) (r)
  7
27
  3
  10

34
Aggregate Functions/Operation
Relation account grouped by branch-name:
By Dr. Pawan Singh Mehra

branch_name account_number balance


Perryridge A-102 400
Perryridge A-201 900
Brighton A-217 750
Brighton A-215 750
Redwood A-222 700

branch_name sum(balance)
Perryridge 1300
Expression: branch_name g sum(balance) (account) Brighton 1500
Redwood 700
Relation account grouped by branch-name
35
Aggregate Functions/Operation
Result of aggregation does not have a name
Can use rename operation to give it a name
By Dr. Pawan Singh Mehra

For convenience, we permit renaming as part of aggregate


operation
branch_name g sum(balance) as sum_balance (account)

36
Division Operation
 Notation: r  s
By Dr. Pawan Singh Mehra

 Suited to queries that include the phrase “for all”, “for every”, at every, at all etc.
 Division operator can be applied if and only if “Attributes of B is proper
subset of Attributes of A”
 Let r and s be relations on schemas R and S respectively where
 R = (A1, …, Am , B1, …, Bn )
 S = (B1, …, Bn)
 The result of r  s is a relation on schema
 R – S = (A1, …, Am)
r  s = { t | t   R-S (r)   u  s ( tu  r ) }
Where tu means the concatenation of tuples t and u to produce a single tuple
37
Division Operation Example
A B
By Dr. Pawan Singh Mehra

 1
 2 B
 3 A
 1
rs
 1 1 
 1 2 
 3
 4 s
 6 Resultant relation
 1
 2

r
Division Operation Example

A B C D E D E
By Dr. Pawan Singh Mehra

 a  a 1 a 1
 a  a 1 b 1
 a  b 1
 a  a 1
s A B C

 a  b 3
rs  a 
 a 
 a  a 1
 a  b 1
 a  b 1
Resultant relation

39
Query Examples
branch (branch_name, branch_city, assets)
customer (customer_name, customer_street, customer_city)
account (account_number, branch_name, balance)
By Dr. Pawan Singh Mehra

loan (loan_number, branch_name, amount)


depositor (customer_name, account_number)
borrower (customer_name, loan_number)

Query: Find all loans of over $1200


Expression: amount > 1200 (loan)

Query: Find the loan number for each loan of an amount greater than $1200
Expression: loan_number (amount > 1200 (loan))

Query: Find the names of all customers who have a loan, an account, or both, from the
bank
Expression: customer_name (borrower)  customer_name (depositor)

40
Query Examples
branch (branch_name, branch_city, assets)
customer (customer_name, customer_street, customer_city)
account (account_number, branch_name, balance)
By Dr. Pawan Singh Mehra

loan (loan_number, branch_name, amount)


depositor (customer_name, account_number)
borrower (customer_name, loan_number)
Query: Find the names of all customers who have a loan at the Perryridge branch
Expression 1: customer_name (branch_name=“Perryridge”
(borrower.loan_number = loan.loan_number(borrower x loan)))
Expression 2: customer_name(loan.loan_number = borrower.loan_number (
(branch_name = “Perryridge” (loan)) x borrower))

Query: Find the names of all customers who have a loan at the Perryridge branch but do not have
an account at any branch of the bank.
Expression: customer_name (branch_name = “Perryridge”
(borrower.loan_number = loan.loan_number(borrower x loan))) – customer_name(depositor)
41
Relational Calculus
 It is a non procedural language/declarative language
 It tells what to do but no description about how to do
By Dr. Pawan Singh Mehra

 Relation algebra describes what to do and how to do


 Relational calculus types
 Tuple Relational Calculus(TRC)
 Proposed by Codd in 1972
 It works on tuples(rows)
 Domain Relational Calculus(DRC)
 Proposed by Lacroix and Pirotte in 1977
 It works on domain of attributes(columns)

42
Tuple Relational Calculus (TRC)
 It is used for selecting the tuples in a relation that satisfy the given
condition(or predicate).
By Dr. Pawan Singh Mehra

 The result of the relation can have one or more tuples


 The result of query is the set of all tuples t such that predicate P is true
for t.
 Expression: { t| P(t) }
 Where t denotes resulting tuple and P(t) denotes
predicate(condition) used to fetch tuple t.

43
Tuple Relational Calculus (TRC) Predicates
 Set of attributes and constants
 Set of comparison operators: =, >, <, ≥, ≤, ≠
By Dr. Pawan Singh Mehra

 Set of connectives: and (Ʌ), or (V), not(⌐)


 Implication: x →y, if x is true, then y is true x →y ≡ ⌐x v y
 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

 A variable is Free variable unless it is quantified by a Ǝ and Ɐ otherwise it


is called Bound variable

44
Tuple Relational Calculus (TRC)
branch (branch_name, branch_city, assets)
customer (customer_name, customer_street, customer_city)
account (account_number, branch_name, balance)
By Dr. Pawan Singh Mehra

loan (loan_number, branch_name, amount)


depositor (customer_name, account_number)
borrower (customer_name, loan_number)

Query: Find the loan-number, branch-name and amount for all loans of over >
$2000.
Sol: {t | t ϵ loan  t[amount]>2000 }

Query: Find the loan number for each loan of an amount greater than 2000
Sol: {t | Ǝs ϵ loan (t[loan-number]=s[loan-number] s[amount]>2000) }

45
Tuple Relational Calculus (TRC)
branch (branch_name, branch_city, assets)
customer (customer_name, customer_street, customer_city)
account (account_number, branch_name, balance)
By Dr. Pawan Singh Mehra

loan (loan_number, branch_name, amount)


depositor (customer_name, account_number)
borrower (customer_name, loan_number)
Query: Find the names of all customers who are having a loan at the
PERRYRIDGE branch.
Sol: {t |Ǝs ϵ borrower (t[customer-name]=s[customer-name]
 Ǝu ϵ loan (u[loan-number]=s[loan-number]
 u[branch-name]=“Perryridge”) )}
Query: Find the names of all customers having a loan, an account or both at
the bank.
Sol: {t | Ǝs ϵ borrower (t[customer-name]=s[customer-name])
˅ Ǝu ϵ depositor (t[customer-name]=u[customer-name] )} 46
Tuple Relational Calculus (TRC)
branch (branch_name, branch_city, assets)
customer (customer_name, customer_street, customer_city)
account (account_number, branch_name, balance)
By Dr. Pawan Singh Mehra

loan (loan_number, branch_name, amount)


depositor (customer_name, account_number)
borrower (customer_name, loan_number)
Query: Find the names of all customers having a loan and an account at the
bank.
Sol: {t | Ǝs ϵ borrower (t[customer-name]=s[customer-name])
 Ǝu ϵ depositor (t[customer-name]=u[customer-name] )}

47
TRC-Safety of Expression
 It is possible to write tuple calculus expressions that generate
infinite relations.
By Dr. Pawan Singh Mehra

 For example, { t |  t r } results in an infinite relation if the


domain of any attribute of relation r is infinite
 To guard against the problem, we restrict the set of allowable
expressions to safe expressions.
 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

48
Domain Relational Calculus (DRC)
 It is nonprocedural query language
By Dr. Pawan Singh Mehra

 It is equivalent in power to the tuple relational calculus


 The records are filtered on the basis of domains.
 It differs from TRC by selecting the attributes rather than selecting
whole tuples.
Expression:
{  x1, x2, …, xn  | P (x1, x2, …, xn)}
• x1, x2, …, xn represent domain variables
• P represents a formula similar to that of the predicate calculus
49
Domain Relational Calculus (DRC)
branch (branch_name, branch_city, assets)
customer (customer_name, customer_street, customer_city)
account (account_number, branch_name, balance)
By Dr. Pawan Singh Mehra

loan (loan_number, branch_name, amount)


depositor (customer_name, account_number)
borrower (customer_name, loan_number)

Query: Find the loan-number, branch-name and amount for all loans of over >
$2000.
Sol: { l, b, a  |  l, b, a   loan  a > 1200}

Query: Find the names of all customers who have a loan of over $1200
Sol: { c  |  l, b, a ( c, l   borrower   l, b, a   loan  a > 1200)}

50
Domain Relational Calculus (DRC)
branch (branch_name, branch_city, assets)
customer (customer_name, customer_street, customer_city)
account (account_number, branch_name, balance)
By Dr. Pawan Singh Mehra

loan (loan_number, branch_name, amount)


depositor (customer_name, account_number)
borrower (customer_name, loan_number)
Query: Find the names of all customers who have a loan from the Perryridge
branch and find the loan amount.
Sol:
{ c, a  |  l ( c, l   borrower  b ( l, b, a   loan  b = “Perryridge”))}
or
{ c, a  |  l ( c, l   borrower   l, “Perryridge”, a   loan)}

51
Domain Relational Calculus (DRC)
branch (branch_name, branch_city, assets)
customer (customer_name, customer_street, customer_city)
account (account_number, branch_name, balance)
By Dr. Pawan Singh Mehra

loan (loan_number, branch_name, amount)


depositor (customer_name, account_number)
borrower (customer_name, loan_number)
Query: Find the names of all customers having a loan, an account, or both at
the Perryridge branch.
Sol: { 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”))}

52
DRC-Safety of Expression
 It is possible to write domain relational calculus expressions that generate
infinite relations.
By Dr. Pawan Singh Mehra

 For example, { <l,b,a> |  (<l,b,a>) r } result is unsafe as it allows values


in the result that are not in the domain of the expression.
 A DRC expression is safe if all of the following hold:
1. All values that appear in tuples of the expression are values from
dom(P).
2. For every “there exists” subformula of the form x (P1(x)), the
subformula is true if and only if there is a value x in dom(P1) such that
P1(x) is true.
3. 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). 53
Structured Query Language (SQL)
 It is standard language for RDBMS which is declarative.
 It allows users to communicate with Relational Databases and
By Dr. Pawan Singh Mehra

insert/update/retrieve data from the database.


 IBM implemented the SQL language which was originally called
SEQUEL(Structured English Query Language) as a part of System R
project in early 1970s.
 It became a standard of ANSI in 1986 and ISO in 1987.
 Most of the commercial systems like Oracle, SQL Server, MS ACCESS
etc. offer most of the major features along with other varying features
as extension.
 SQL is based on Tuple Relational Calculus which is based on Relational
Algebra.
54
Types of SQL Commands
 Data Definition Language (DDL)
 Commands used to define the schema of the database
By Dr. Pawan Singh Mehra

 Create: to create a new database or table


 Alter: to alter the structure of the table
 Drop: to permanently delete a table from database
 Truncate: to delete all records from the table
 Data Manipulation Language (DML)
 Commands are used for accessing and manipulating the data stored in
the data
 Select: to retrieve data from the database
 Insert: to insert a new record/tuple/row into a table
 Update: to update existing row in a table
 Delete: to delete rows from a table
55
Types of SQL Commands
 Data Control Language (DCL)
 Commands to control the access of the data stored in the database
By Dr. Pawan Singh Mehra

 Grant: grant permission to user for database access.


 Revoke: take back granted permission from user.
 Transaction Control Language(TCL)
 Commands which are used to manage the changes made by the DML
statements.
 Commit: to permanently save the transaction
 Rollback: to undo the transaction under process
 Savepoint: to temporarily save a transaction so that user can rollback
to that point whenever necessary.

56
Commonly used Domain Types in SQL
 char(n) : Fixed length character string, with user-specified length
n.
By Dr. Pawan Singh Mehra

 varchar(n): Variable length character strings, with user-specified


maximum length n.
 int: Integer (a finite subset of the integers that is machine-
dependent).
 date: used for storing dates.
 numeric(p,d): Fixed point number, with user-specified precision of
p digits, with n digits to the right of decimal point.
 real, double precision: Floating point and double-precision
floating point numbers, with machine-dependent precision.
 float(n): Floating point number, with user-specified precision of at
least n digits.
57
DDL- CREATE COMMAND
Description: It is used to create a new database or table
By Dr. Pawan Singh Mehra

Syntax for creating DB: CREATE DATABASE <database name>;

Example:
CREATE DATABASE Test;

58
DDL- CREATE COMMAND
Syntax for creating table:
CREATE TABLE <TABLE_NAME>
By Dr. Pawan Singh Mehra

(
column_name1 datatype1,
column_name2 datatype2,
column_name3 datatype3,
column_name4 datatype4
);
Example:
CREATE TABLE branch
(
branch_name char(15),
branch_city char(30),
assets integer
); 59
DDL- CREATE COMMAND
Example
CREATE TABLE customer
By Dr. Pawan Singh Mehra

( customer_id NUMBER (4),


customer_name VARCHAR2(30),
customer_dob DATE,
customer_income NUMBER(8,2),
customer_type VARCHAR2(15)
);
Example with integrity constraints:
CREATE TABLE sales
( sales_id NUMBER (8) PRIMARY KEY,
sales_date DATE,
sales_type VARCHAR2(15),
customer_id NUMBER(4),
FOREIGN KEY customer_id REFERENCES customer (customer_id)
); 60
DDL- ALTER COMMAND
Description:
alter command is used for altering the table structure, such as,
By Dr. Pawan Singh Mehra

 to add a column to existing table


 to rename any existing column
 to change datatype of any column or to modify its size.
 to drop a column from the table.

61
DDL- ALTER COMMAND
Syntax to Alter a Table (Adding Columns):
ALTER TABLE <table name>
By Dr. Pawan Singh Mehra

ADD
(
{<column name> <data type> [(<size>)]
[DEFAULT <value>]
{[[CONSTRAINT <constraint name>] <constraint definition>]} [ … ]
}
[ , …]
[ , <table level constraints> ] [ … ]
);

62
DDL- ALTER COMMAND
Example to Alter a Table (Adding Columns):
ALTER TABLE customer
By Dr. Pawan Singh Mehra

ADD
( customer_phone VARCHAR2(30) NOT NULL,
customer_email VARCHAR2(30) UNIQUE
);

63
DDL- ALTER COMMAND
Syntax to Alter a Table (Modifying Columns):
ALTER TABLE <table name>
By Dr. Pawan Singh Mehra

MODIFY
(
{<column name> <data type> [(<size>)]
[DEFAULT <value>]
{[[CONSTRAINT <constraint name>] <constraint definition>]} [ … ]
}
[ , …]
);

64
DDL- ALTER COMMAND
Example to Alter a Table (Modifying Columns):
ALTER TABLE customer
By Dr. Pawan Singh Mehra

MODIFY
( customer_name VARCHAR2(40) NOT NULL,
customer_email VARCHAR2(50)
);

65
DDL- ALTER COMMAND
Syntax to Alter a Table (Dropping Columns):
ALTER TABLE <table name>
By Dr. Pawan Singh Mehra

DROP COLUMN <column name>;

Example:
ALTER TABLE customer
DROP COLUMN customer_email;

66
DDL- ALTER COMMAND
Syntax to Alter a Table (Renaming table):
ALTER TABLE <table name>
By Dr. Pawan Singh Mehra

RENAME TO < new_table _name >;

Example:
ALTER TABLE customer
RENAME TO customer_info;

67
DDL- ALTER COMMAND
Syntax to Alter a Table (Renaming Columns):
ALTER TABLE <table name>
By Dr. Pawan Singh Mehra

RENAME COLUMN
<old_column_name> TO < new_column_name >;

Example:
ALTER TABLE customer
RENAME COLUMN
customer_income TO cust_income;

68
DDL- DROP COMMAND
Description: DROP command completely removes a table from
the database. This command will also destroy the table structure
By Dr. Pawan Singh Mehra

and the data stored in it.

Syntax:
DROP TABLE <table name>;

Example:
DROP TABLE customer;

69
DDL- TRUNCATE COMMAND
Description: It removes all the records from a table. But this
command will not destroy the table's structure. When we use
By Dr. Pawan Singh Mehra

TRUNCATE command on a table its (auto-increment) primary key


is also initialized.

Syntax :
TRUNCATE TABLE <table name> ;

Example:
TRUNCATE TABLE customer;

70
DML-INSERT COMMAND
Description: It used to insert data into a table.
By Dr. Pawan Singh Mehra

Syntax to Insert Record:


INSERT INTO <table name> [(<column list>)]
{ VALUES (<value list>) | <query> };

Example:
INSERT INTO customer VALUES (1, ‘Mr. Ashok’, ‘01-Jan-1970’, 10000, ‘P’);

INSERT INTO customer (customer_id, customer_name) VALUES (2, ‘Mr.


Ramesh’);

Note: The columns which are not mentioned in Insert command will get
NULL values by default.
71
DML-SELECT COMMAND
Description: It is used to fetch the data from a database table which
returns this data in the form of a result table. These result tables are called
By Dr. Pawan Singh Mehra

result-sets.

Syntax :
SELECT column1, column2, columnN
FROM table_name;

Example:
SELECT * FROM customer;

SELECT customer_id, customer_name FROM customer;


72
DML-WHERE CLAUSE
Description: It is used to filter records. It is used to extract only those
records that fulfill a specified condition.
By Dr. Pawan Singh Mehra

Syntax :
SELECT column1, column2, columnN
FROM table_name
WHERE [condition];

Example:
SELECT customer_id, customer_name FROM customer WHERE
customer_id=1;

Note: The WHERE clause is not only used in SELECT statements, it is also
used in UPDATE, DELETE, etc.! 73
DML-UPDATE COMMAND
Description: it is used to update any record of data in a table.
Syntax to Update Record:
By Dr. Pawan Singh Mehra

UPDATE <table name>


SET { <column name> = { <value> | <query> }
[,…]
[ WHERE <filter condition> ];

74
DML-UPDATE COMMAND
Example:
UPDATE customer SET customer_income = 15000;
By Dr. Pawan Singh Mehra

UPDATE customer SET customer_income = 15000 WHERE customer_id = 1;

UPDATE customer
SET customer_income = customer_income * 1.1, customer_type = ‘P’
WHERE customer_id = 1;

UPDATE customer
SET customer_income = (SELECT customer_income * 1.1
FROM customer
WHERE customer_id = 1)
WHERE customer_id = 1;
75
DML-DELETE COMMAND
Description: It deletes rows in a table without deleting the table. This
means that the table structure, attributes, and indexes will be intact.
By Dr. Pawan Singh Mehra

Syntax to Delete Record:


DELETE [FROM] <table name>
[ WHERE <filter condition> ];

Example:
DELETE FROM customer;

DELETE customer;

DELETE FROM customer WHERE customer_id = 1;


76
DCL-GRANT COMMAND
Description: It used to provide access or privileges on the database
objects to the users.
By Dr. Pawan Singh Mehra

Syntax :
GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];

Example:
GRANT SELECT ON employee TO user1;

77
DCL-REVOKE COMMAND
Description: It removes user access rights or privileges to the database
objects
By Dr. Pawan Singh Mehra

Syntax :
REVOKE privilege_name
ON object_name
FROM {user_name |PUBLIC |role_name};

Example:
REVOKE SELECT ON employee FROM user1;

78
TCL-COMMIT COMMAND
Description: It is used to save the changes permanently into the database
By Dr. Pawan Singh Mehra

Syntax :
COMMIT;

Example:
DELETE FROM EMPLOYEES
WHERE AGE = 30;
COMMIT;

79
TCL-SAVEPOINT COMMAND
Description: It is is a point in a transaction when you can roll the
transaction back to a certain point without rolling back the entire
By Dr. Pawan Singh Mehra

transaction.

Syntax :
SAVEPOINT Savepoint_name;

Example:
INSERT INTO Teachers VALUES (4, 'CYPRESS', 'MICHEAL');
SAVEPOINT s;

80
TCL-ROLLBACK COMMAND
Description: It is used to undo transactions that have not already been saved to the
database. This command can only be used to undo transactions since the last COMMIT
By Dr. Pawan Singh Mehra

or ROLLBACK command was issued

Syntax :
ROLLBACK ;
or
ROLLBACK TO <savepoint_name>

Example:
INSERT INTO teachers VALUES (4, 'CYPRESS', 'MICHEAL');
SAVEPOINT s;
INSERT INTO teachers VALUES (5, 'PYTHON', 'STEVE');
INSERT INTO teachers VALUES (6, 'PYTEST', 'ARNOLD');
ROLLBACK TO s; 81
SQL- Distinct
Description: It is used with SELECT Command. Inside a table, a
column often contains many duplicate values; and sometimes
By Dr. Pawan Singh Mehra

you only want to list the different (distinct) values.

Syntax:
SELECT DISTINCT column1, column2, ...
FROM table_name;

Example:
SELECT DISTINCT Country FROM Customers;

82
SQL- Group By
Description: is used in collaboration with the SELECT statement to arrange
identical data into groups. This GROUP BY clause follows the WHERE clause
By Dr. Pawan Singh Mehra

in a SELECT statement and precedes the ORDER BY clause(if order by is to


be used)
Syntax:
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2[optional]
Example:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
83
SQL- Order by
Description: It is used to sort the result-set in ascending or descending
order. It sorts the records in ascending order by default.
By Dr. Pawan Singh Mehra

Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Example:
SELECT * FROM Customers ORDER BY Country;
SELECT * FROM Customers ORDER BY Country DESC;
SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC;
84
SQL- Having
Description: It enables you to specify conditions that filter which group results
appear in the results .
By Dr. Pawan Singh Mehra

 The WHERE clause places conditions on the selected columns, whereas the
HAVING clause places conditions on groups created by the GROUP BY clause.
 The HAVING clause must follow the GROUP BY clause in a query and must
also precede the ORDER BY clause if used.

Syntax:
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2
85
SQL- Having
Example:
SELECT COUNT(CustomerID), Country
By Dr. Pawan Singh Mehra

FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;
86
Aggregate Functions in SQL

These functions performs a calculation on integer values in a


By Dr. Pawan Singh Mehra

column of multiple rows and return a single value


 avg: average value
 min: minimum value
 max: maximum value
 sum: sum of values
 count: number of values

87
Aggregate Functions- avg()
Description: It returns the average value of a numeric column
By Dr. Pawan Singh Mehra

Syntax:
SELECT AVG(column_name)
FROM table_name
WHERE condition;

Example:
SELECT AVG(Price)
FROM Products;
88
Aggregate Functions- count()
Description: It returns the number of rows in a column or columns
By Dr. Pawan Singh Mehra

that matches a specified criterion.

Syntax:
SELECT COUNT (column_name) FROM table_name
WHERE condition;

Example:
SELECT COUNT(*)FROM Products;
SELECT COUNT(ProductID) FROM Products;
89
Aggregate Functions- sum ()
Description: It returns the total sum of a numeric column
By Dr. Pawan Singh Mehra

Syntax:
SELECT SUM (column_name)
FROM table_name
WHERE condition;

Example:
SELECT SUM(Quantity)
FROM OrderDetails;
90
Aggregate Functions- min ()
Description: It returns the smallest value of a numeric column
By Dr. Pawan Singh Mehra

Syntax:
SELECT MIN(column_name)
FROM table_name
WHERE condition;;

Example:
SELECT MIN(Price) FROM Products;
SELECT MIN(Price) AS SmallestPrice FROM Products
91
Aggregate Functions- max ()
Description: It returns the maximum value of a numeric column
By Dr. Pawan Singh Mehra

Syntax:
SELECT MAX(column_name)
FROM table_name
WHERE condition;

Example:
SELECT MAX(Price) FROM Products;
SELECT MAX(Price) AS LargestPrice FROM Products;
92
Set Operations in SQL

 Set operators are used to join the results of two (or more)
By Dr. Pawan Singh Mehra

SELECT statements. It removes duplicates from the


results(except UNION ALL).
 UNION ALL
 UNION
 INTERSECT
 MINUS

93
Set Operations – UNION ALL
Description: It gives the result set without removing duplication and
By Dr. Pawan Singh Mehra

sorting the data.

Syntax:
SELECT expression_1, expression_2, ... , expression_n FROM table_1
UNION ALL
SELECT expression_1, expression_2, ... , expression_n FROM table_2

Example:
SELECT * FROM comp1_employees
UNION ALL
SELECT * FROM comp2_employees;
94
Set Operations – UNION
Description: It combines the results of two or more SELECT statements.
The number of columns and the data type must be the same in both tables.
By Dr. Pawan Singh Mehra

The duplicate rows will be eliminated from the results.


Syntax:
SELECT expression_1, expression_2, ... , expression_n FROM table_1
UNION
SELECT expression_1, expression_2, ... , expression_n FROM table_2

Example:
SELECT * FROM comp1_employees
UNION
SELECT * FROM comp2_employees;
95
Set Operations – INTERSECT
Description: It allows us to find the results that exist in both queries.
By Dr. Pawan Singh Mehra

Syntax:
SELECT expression_1, expression_2, ... , expression_n FROM table_1
INTERSECT
SELECT expression_1, expression_2, ... , expression_n FROM table_2

Example:
SELECT * FROM comp1_employees
INTERSECT
SELECT * FROM comp2_employees;
96
Set Operations – MINUS/EXCEPT
Description: It returns all the rows of the first SELECT statement which
By Dr. Pawan Singh Mehra

are not common to the rows of the second SELECT statement.


Syntax:
SELECT expression_1, expression_2, ... , expression_n FROM table_1
MINUS/EXCEPT
SELECT expression_1, expression_2, ... , expression_n FROM table_2

Example:
SELECT * FROM comp1_employees
MINUS/EXCEPT
SELECT * FROM comp2_employees;
97
LIKE Operator
Description: It is used in a WHERE clause to search for a specified
pattern in a column.
By Dr. Pawan Singh Mehra

LIKE Operator Description


WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2
characters in length
WHERE CustomerName LIKE ‘a_ _%' Finds any values that start with "a" and are at least 3
characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
98
LIKE Operator
Example:
SELECT * FROM Customers WHERE CustomerName LIKE 'a%’;
By Dr. Pawan Singh Mehra

SELECT * FROM Customers WHERE CustomerName LIKE '%a’;

SELECT * FROM Customers WHERE CustomerName LIKE '%or%’;

SELECT * FROM Customers WHERE CustomerName LIKE '_r%’;

SELECT * FROM Customers WHERE CustomerName LIKE ’a_ _%’;

SELECT * FROM Customers WHERE ContactName LIKE 'a%o';.


99
IN Operation
Description: The IN operator allows you to specify multiple values
By Dr. Pawan Singh Mehra

in a WHERE clause. It is a shorthand for multiple OR conditions.

Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
100
IN Operation
Example :
By Dr. Pawan Singh Mehra

SELECT * FROM Customers


WHERE Country IN ('Germany', 'France', 'UK’);

SELECT * FROM Customers


WHERE Country IN (SELECT Country FROM Suppliers);

101
ANY Operation
Description: It returns a boolean value as a result. It returns TRUE if ANY
By Dr. Pawan Singh Mehra

of the subquery values meet the condition.


It means that the condition will be true if the operation is true for any of
the values in the range.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);

102
ANY Operation
Example:
By Dr. Pawan Singh Mehra

SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);

103
ALL Operation
Description: It returns a boolean value as a result. It returns TRUE if ALL
By Dr. Pawan Singh Mehra

of the subquery values meet the condition.


It means that the condition will be true if the operation is true for ALL of
the values in the range.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name OPERATOR ALL
(SELECT column_name
FROM table_name
WHERE condition);

104
ALL Operation
Example:
By Dr. Pawan Singh Mehra

SELECT ProductName
FROM Products
WHERE ProductID = ALL
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);

105
EXISTS Operation
Description: It is used to test for the existence of any record in a
By Dr. Pawan Singh Mehra

subquery. It returns TRUE if the subquery returns one or more


records.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);

106
EXISTS Operation
Example:
By Dr. Pawan Singh Mehra

SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE
Products.SupplierID = Suppliers.supplierID AND Price < 20);

NOTE: While using EXISTS we need to provide a sub-query whereas in IN


Operator, we can directly provide values for comparison

107
BETWEEN Operation
Description: It selects values within a given range. The values can be
By Dr. Pawan Singh Mehra

numbers, text, or dates. This operator is inclusive: begin and end


values are included.

Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
108
BETWEEN Operation
Example:
By Dr. Pawan Singh Mehra

SELECT * FROM Orders


WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;

Example of NOT BEWEEN:


SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

Example of NOT BEWEEN with IN:


SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3); 109
ALIASES Operation
Description: It is used to give a table, or a column in a table, a
By Dr. Pawan Singh Mehra

temporary name. It only exists for the duration of that query.

Syntax for Aliasing Column:


SELECT column_name AS alias_name
FROM table_name;

Syntax for Aliasing Table :


SELECT column_name(s)
FROM table_name AS alias_name;
110
ALIASES Operation
Example of Aliasing Column:
By Dr. Pawan Singh Mehra

SELECT CustomerID AS ID, CustomerName AS Customer


FROM Customers;

SELECT CustomerName, (Address || ', ' || PostalCode || ' ' || City || ', ' ||
Country) AS Address
FROM Customers;

Example of Aliasing Table :


SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND
c.CustomerID=o.CustomerID; 111
SQL JOIN-Inner Join
Description: It is the simplest and most common type of join. It is also known
as simple join. It returns all rows from multiple tables where the join condition
By Dr. Pawan Singh Mehra

is met.

Syntax:
SELECT columns
FROM table1 INNER JOIN table2
ON table1.column COMPARISON OPERATOR table2.column;

Example:
SELECT suppliers.supplier_id, suppliers.supplier_name, order.order_number
FROM suppliers INNER JOIN order
ON suppliers.supplier_id = order.supplier_id;
112
SQL JOIN-Left Outer Join
Description: It returns all rows from the left (first) table specified in the ON
condition and only those rows from the right (second) table where the join
By Dr. Pawan Singh Mehra

condition is met

Syntax:
SELECT columns
FROM table1 LEFT OUTER JOIN table2
ON table1.column = table2.column;

Example:
SELECT suppliers.supplier_id, suppliers.supplier_name, order.order_number
FROM suppliers LEFT OUTER JOIN order
ON suppliers.supplier_id = order.supplier_id;
113
SQL JOIN-Right Outer Join
Description: It returns all rows from the right-hand table specified in the ON
condition and only those rows from the other table where the join condition
By Dr. Pawan Singh Mehra

is met.

Syntax:
SELECT columns
FROM table1 RIGHT OUTER JOIN table2
ON table1.column = table2.column;

Example:
SELECT suppliers.supplier_id, suppliers.supplier_name, order.order_number
FROM suppliers RIGHT OUTER JOIN order
ON suppliers.supplier_id = order.supplier_id;
114
SQL JOIN-Full Outer Join
Description: It returns all rows from the left hand table and right hand table. It
places NULL where the join condition is not met.
By Dr. Pawan Singh Mehra

Syntax:
SELECT columns
FROM table1 FULL OUTER JOIN table2
ON table1.column = table2.column;

Example:
SELECT suppliers.supplier_id, suppliers.supplier_name, order.order_number
FROM suppliers FULL OUTER JOIN order
ON suppliers.supplier_id = order.supplier_id;
115
SQL JOIN-Equi Join
Description: It returns the matching column values of the associated tables. It
uses equal(=) comparison operator in the WHERE clause to refer equality.
By Dr. Pawan Singh Mehra

Syntax:
SELECT column_list
FROM table1, table2....
WHERE table1.column_name = table2.column_name;

Example:
SELECT agents.agent_city,customer.last_name,customer.first_name
FROM agents, customer
WHERE agents.agent_id=customer.customer_id;
116
SQL JOIN-Self Join
Description: In Self Join, a table is joined with itself (Unary relationship). A
self join simply specifies that each rows of a table is combined with itself
By Dr. Pawan Singh Mehra

and every other row of the table.

Syntax:
SELECT a.column_name, b.column_name
FROM table1 as a, table1 as b
WHERE a.common_filed = b.common_field;

Example:
SELECT a.name, b.age, a.SALARY
FROM CUSTOMERS as a, CUSTOMERS as b
WHERE a.SALARY < b.SALARY;
117
SQL JOIN-Cross Join
Description: It specifies that all rows from first table join with all of the
rows of second table. If there are "x" rows in table1 and "y" rows in table2
By Dr. Pawan Singh Mehra

then the cross join result set have x*y rows. It normally happens when no
matching join columns are specified.

Syntax:
SELECT * FROM table1 CROSS JOIN table2;
SELECT * FROM table1, table2

Example:
SELECT * FROM customer, supplier

118
NULL Values
It is possible for tuples to have a null value, denoted by null, for
By Dr. Pawan Singh Mehra

some of their attributes


null signifies an unknown value or that a value does not exist.
The result of any arithmetic expression involving null is null.
Aggregate functions simply ignore null values (as in SQL)
For duplicate elimination and grouping, null is treated like any
other value, and two nulls are assumed to be the same (as in
SQL)
119
NULL Values
Comparisons with null values return the special truth value:
By Dr. Pawan Singh Mehra

unknown
Three-valued logic using the truth value unknown:
OR: (unknown or true) = true,
(unknown or false) = unknown
(unknown or unknown) = unknown
AND: (true and unknown) = unknown,
(false and unknown) = false,
(unknown and unknown) = unknown
NOT: (not unknown) = unknown
Result of select predicate is treated as false if it evaluates to
unknown 120
Trigger
Description: It is a database object which fires when an event occurs in a
database.
By Dr. Pawan Singh Mehra

Syntax for Creating Trigger:


CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER }
{INSERT [OR] | UPDATE [OR] | DELETE}
ON table_name
[FOR EACH ROW]
WHEN (condition)
[trigger_body];
Syntax for Dropping Trigger:
DROP TRIGGER trigger_name;
121
Trigger
Example for Creating Trigger:
CREATE TRIGGER student_name
By Dr. Pawan Singh Mehra

AFTER
INSERT
ON
student
FOR EACH ROW
BEGIN
UPDATE student, set full_name = first_name || ' ' || last_name;
END;

Example for Dropping Trigger:


DROP TRIGGER student_name; 122
Assertion
Description: It is a statement that ensures that certain conditions are
always enforced in the database no matter what. Same as domain or other
By Dr. Pawan Singh Mehra

constraints, assertions differ in the way that they are defined separately
from table definitions. It is a named statement that defines a condition
that must be true for the data in the database. If the condition is not met,
the assertion will fail and the database will generate an error.

Syntax for Creating Assertion:


CREATE ASSERTION [ assertion_name ]
CHECK ( [ condition ] );

Syntax for Dropping Assertion:


DROP ASSERTION assertion_name;
123
Assertion
Example for Creating Assertion:
By Dr. Pawan Singh Mehra

CREATE ASSERTION salary_assertion


CHECK (salary <= 100000);

CREATE ASSERTION nomanager


CHECK( NOT EXISTS
( SELECT * FROM MANAGER
WHERE Department_id is NULL));

Example for Creating Assertion:


DROP ASSERTION salary_assertion;
DROP ASSERTION nomanager;
124

You might also like