Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
43 views

DBMS UNIT-3 Part-1 SQL

Uploaded by

Malothu Upendar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

DBMS UNIT-3 Part-1 SQL

Uploaded by

Malothu Upendar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

UNIT-3

• SQL
• SCHEMA REFINEMENT
UNIT-3 Syllabus
Text Book-1: Chapter 5 and 19
Text Book-2: Chapter 3 and 7

• SQL: QUERIES, CONSTRAINTS, TRIGGERS: form of basic SQL


query, UNION, INTERSECT, and EXCEPT, Nested Queries,
aggregation operators, NULL values, complex integrity
constraints in SQL, triggers and active data bases.

• Schema Refinement: Problems caused by redundancy,


decompositions, problems related to decomposition,
reasoning about functional dependencies, FIRST, SECOND,
THIRD normal forms, BCNF, lossless join decomposition,
multi-valued dependencies, FOURTH normal form, FIFTH
normal form.
UNIT-3 Part-1 Syllabus
Text Book-1: Chapter 5
Text Book-2: Chapter 3,4
• SQL: QUERIES, CONSTRAINTS, TRIGGERS:
– form of basic SQL query,
– UNION, INTERSECT, and EXCEPT,
– Nested Queries,
– aggregation operators,
– NULL values,
– complex integrity constraints in SQL,
– triggers and active data bases.

Form of Basic SQL Query
The SQL SELECT statement 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 result-sets.
• A typical SQL query has the form:

SELECT [DISTINCT] columnname1,columnname2… columnnameN


FROM tablename(s) [WHERE condition];
– The result of an SQL query is a relation.
• select A1, A2, ..., An from r1, r2, ..., rm where P
– Ai represents an attribute
– Ri represents a relation
– P is a predicate.

• This query is equivalent to the relational algebra expression.

• Extension form of SQL Select statement :

SELECT [DISTINCT] columnname1,columnname2… columnnameN


FROM tablename(s)
[WHERE condition]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause];
The select Clause
• The select clause list the attributes desired in the
result of a query
– corresponds to the projection operation of the
relational algebra
• Example: find the names of all branches in the loan
relation:
• select branch_name from loan
• In the relational algebra, the query would be:
∏branch_name (loan)
• NOTE: SQL names are case insensitive
(i.e., you may use upper- or lower-case letters.)
– E.g. Branch_Name ≡ BRANCH_NAME ≡ branch_name
The select Clause (Cont.)
• SQL allows duplicates in relations as well as
in query results.
• To force the elimination of duplicates,
insert the keyword distinct after select.
• Find the names of all branches in the loan
relations, and remove duplicates
select distinct branch_name
from loan

• The keyword all specifies that duplicates


not be removed.

select all branch_name


from loan

The select Clause (Cont.)
An asterisk in the select clause denotes “all
attributes”
select *
from loan
• The select clause can contain arithmetic
expressions involving the operation, +, –, *,
and /, and operating on constants or
attributes of tuples.
• The query:
select loan_number, branch_name,
amount * 100
from loan
would return a relation that is the same as the
loan relation, except that the value of the
attribute amount is multiplied by 100.
The where Clause
• The where clause specifies conditions that the result must satisfy
– Corresponds to the selection predicate of the relational algebra.

• To find all loan number for loans made at the Perryridge branch
with loan amounts greater than $1200.
select loan_number
from loan
where branch_name = 'Perryridge' and amount > 1200
• Comparison results can be combined using the logical connectives
and, or, and not.
• Comparisons can be applied to results of arithmetic Expressions.
The where Clause (Cont.)
• SQL includes a between comparison operator
• Example: Find the loan number of those loans with loan
amounts between $90,000 and $100,000 (that is, ≥
$90,000 and ≤ $100,000)

select loan_number
from loan
where amount between 90000 and 100000
The from Clause
• The from clause lists the relations involved in the query
– Corresponds to the Cartesian product operation of the
relational algebra.
• Find the Cartesian product borrower X loan
select *
from borrower, loan

● Find the name, loan number and loan amount of all customers having a
loan at the Perryridge branch.
●Cartesian product not very useful directly, but useful combined with
where-clause condition (selection operation in relational algebra).

select customer_name, borrower.loan_number, amount


from borrower, loan
where borrower.loan_number = loan.loan_number and
branch_name = 'Perryridge'
Cartesian Product
SELECT * FROM instructor, teaches;
instructor teaches
The Rename Operation
• The SQL allows renaming relations and
attributes using the as clause:
old-name as new-name
• Find the name, loan number and loan amount
of all customers; rename the column name
loan_number as loan_id.

select customer_name, borrower.loan_number as loan_id, amount


from borrower, loan
where borrower.loan_number = loan.loan_number
Tuple Variables(Range Variables)
• Tuple variables are defined in the from clause via the use of the as clause.
• Tuple(range) variables particularly useful when the same table name
appears more than once in the from clause.
• Find the customer names and their loan numbers for all customers having a
loan at some branch.
select customer_name, T.loan_number, S.amount
from borrower as T, loan as S
where T.loan_number = S.loan_number
● Find the names of all branches that have greater assets than
some branch located in Brooklyn.
select distinct T.branch_name
from branch as T, branch as S
where T.assets > S.assets and S.branch_city = 'Brooklyn'
●Keyword as is optional and may be omitted
borrower as T ≡ borrower T
SQL Operators
• An operator is a character/reserved word used in an expression to perform an
operation on the elements of the expression.
• Operator primarily used in SQL statement’s where clause to perform operations,
such as comparison and arithmetic operations. These operators are used to specify
conditions in an SQL statement and to serve as conjunctions for multiple conditions
in statement.
• If any operator receives a NULL, the result is always NULL. The only operator that
does not follow this rule is CONCAT.
• Operators of the same priority be evaluated from left to right.

• Classification of Operators:
Unary Operators
Binary Operators
SET Operators
SQL Operators
SQL Operators
UNARY Operators
• +(Unary) – Makes Operand Positive
• -(Unary) – Makes Operand Negative
Example:
SELECT +3 FROM DUAL;
SELECT -5 FROM DUAL;
SQL Operators
BINARY Operators
• Arithmetic Operators
• Concatenation Operator
• Relational Operators / Comparison Operators
• Other Relational Operators
• Logical Operators
SQL Operators
Arithmetic Operators

* - Multiplication (Priority1)
/ - Division (Priority1)
+ - Addition (Priority2)
--Subtraction (Priority2)
Examples:
• SELECT SAL / 10 FROM EMP;
• SELECT SAL * 5 FROM EMP;
• SELECT SAL + 200 FROM EMP;
• SELECT SAL - 100 FROM EMP;
SQL Operators
Concatenation Operator

|| - Concatenation

• For concatenation of two strings.

SELECT “oracle” || “server” FROM DUAL;


SQL Operators
Relational Operators
= Equals to
!=, <> Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
• All these operators can be used to compare with single value.
• These operators are also called as single row or single value
relational operators
SQL Operators
Other Relational Operators (Set Comparison Operators)
IN
ANY/SOME
ALL
LIKE
EXISTS
BETWEEN
• All these operators can be used to compare with multiple values.
• These operators are also called as Multiple row or Multiple
value relational operators or Set Comparison Operators.
SQL Operators
IN , NOT IN Operators
• Returns true if the value is equal to the any of the value in the list(values returned from sub
query).
• The IN operator allows you to specify multiple values in a WHERE clause.
• The IN operator is a shorthand for multiple OR conditions.
• Syntax:
– SELECT column_name(s) FROM tablename WHERE column_name IN(valu1,value2…);

– SELECT column_name(s) FROM tablename WHERE column_name NOT IN(valu1,value2…);

– SELECT column_name(s) FROM tablename WHERE column_name IN(SELECT statement);


Example:
• Display the eno, ename of employees who lives in ‘Hyderabad’ or ‘Secunderabad’
SELECT ENO,ENAME FROM EMPLOY WHERE CITY IN(‘HYD’,’SEC’);

• Displaying information of employees who doesn’t live in ‘Hyderabad’ or ‘Pune’


SELECT ENO,ENAME FROM EMPLOY WHERE CITY NOT IN(‘HYD’,’SEC’);

• Selects all customers that are from the same countries as the suppliers:
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
SQL Operators
ALL, ANY/SOME Operator
• ALL, ANY/SOME are key words, used with the WHERE/HAVING.
• ALL, ANY/SOME operates on sub queries that return multiple values.
• ALL, ANY/SOME operator Must be preceded by =, !=, >, <, <= , >=.
• ALL returns true if all of the values in the list/sub query values meet the condition
• ANY/SOME returns true if any or some of the values in the list/sub query values meet
the conditions.

– SELECT ename FROM employ WHERE sal >ALL(9000,10000,15000);


– SELECT ename FROM employ WHERE sal >ANY(9000,10000,15000);

• <ANY( ) : Returns true the value Less than Maximum value in the list.
• >ANY( ) : Greater than Minimum
• =ANY ( ) : Equivalent to IN
• > ALL( ) : Greater than Maximum
• < ALL( ): Less than Minimum
SQL Operators
ALL, ANY/SOME Operator
• Find the employ names whose salary is greater than
all employees in dept no 10.
SELECT ENAME,SAL FROM EMPLOY WHERE
SAL>ALL(SELECT SAL FROM EMPLOY WHERE
DNO=10)
• A Nested query is a query that has another query
embedded within it. The embedded query is called is
called a sub query.
• A query with in another query is called as sub query.
SQL Operators
EXISTS Operator
• The EXISTS operator is used to test for the existence of any record in a sub query.
• The EXISTS operator returns TRUE if the sub query returns one or more records.
• The NOT EXISTS operator returns TRUE if the sub query returns no records(tuples)

• EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Example 1:
SELECT * FROM employ WHERE EXISTS(SELECT sal FROM employ WHERE sal=9000);

Example2: Professor(Eid,Name)
Student(Sid,name,eid)
Get the eid and name of the professor who is an advisor for at least one student.

SELECT eid,name from professor p where exists(select sid from student s where s.eid =p.eid);
SQL Operators
Logical Operators
• AND
– Returns TRUE if both component conditions are TRUE. Returns FALSE if
either is FALSE; otherwise returns UNKNOWN.
– Displays row only if both conditions are true
SELECT * FROM EMP WHERE job='CLERK' AND deptno=10;

• OR
– Returns TRUE if either component condition is TRUE. Returns FALSE
if both are FALSE. Otherwise, returns UNKNOWN.
– Displays row even if one of the conditions is true
SELECT * FROM emp WHERE job='CLERK' OR deptno=10;

• NOT
– Returns TRUE if the following condition is FALSE. Returns FALSE if it is
TRUE. If it is UNKNOWN, it remains UNKNOWN.
– Displays row if the condition is false.

SELECT * FROM EMP WHERE NOT (job IS NULL);


SELECT * FROM EMP WHERE NOT (sal BETWEEN 1000 AND 2000);
LIKE operator -String Operations
• SQL includes a string-matching operator for
comparisons on character strings. The
operator “like” uses patterns that are
described using two special characters:
– percent (%). The % character matches any substring.
ZERO OR ANY NUMBER OF CHARACTERS
– underscore (_). The _ character matches any character.
• Find the names of all customers whose street
includes the substring “Main”.
select customer_name
from customer
where customer_street like '% Main%'
• Match the name “Main%”
like 'Main\%' escape '\'

• SQL supports a variety of string operations such


as
– concatenation (using “||”)
– converting from upper to lower case (and vice versa)
– finding string length, extracting substrings, etc.

DBMS UNIT-3 Assignment-1
Refer to the relation schema given below and answer the questions asked after schema description.
Schema:
Employee(Eno,Ename,City,Sal,Deptno,Phone No);
• Questions:

1. Display the names of employees who lives in ‘Hyderabad’ and salary is greater than 10000
2. Display the eno, ename of employees who lives in ‘Hyderabad’ or ‘Secunderabad’
3. Displaying information of employees whose mobile number is not available.
4. Displaying information of employees whose mobile number is not null.
5. Displaying information of employees who doesn’t live in ‘Hyderabad’ or ‘Pune’
6. Displaying information of employees whose mobile number is not available or salary is less than
10000
7. Write a query to display information of all employees whose name starts with ‘M’
8. Write a query to display information of all employees whose name has ‘o’ as second character.
9. Write a query to display information of all employees whose city ends with ‘I’
10. Write a query to display information of all employees whose city is 6 characters long.
11. Write a query to display information of all employees whose name contains character ‘i’
12. Write a query to display information of all employees whose name has character ‘i’ as third last
character
13. Write a query to display information of all employees whose name has minimum 6 characters
SET OPERATORS-
UNION,INTERSECT, EXCEPT(MINUS)
• Set operators are used to fetch the data
from multiple tables.
• Set operators are used to combine the
results from different SELECT statements
into one single result output.
• The SET operators available in Oracle are :
UNION
UNION ALL
INTERSECT
MINUS ( EXCEPT in SQL SERVER)
Business

Branch1 Branch2 Branch3

Cust_details Cust_details Cust_details


Trans_info Trans_info Trans_info
Product_info Product_info Product_info

DB1 DB2 DB3

Cust_details(cid,cname,gender,mobile,city)
SET OPERATORS-
• In order to explain the SET operators, the following two
lists will be referred to throughout this lesson:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
• Or in reality: two tables, one called A and one called B.
A_ID B_ID
A 1 4
B2 5
3 6
4 7
5 8

31
SET OPERATORS-
Rules to Remember
• There are a few rules to remember when using SET
operators:
– The number of columns and the data types of the columns
must be identical in all of the SELECT statements used in the
query.
– The order of the columns should be same in all of the SELECT
statements used in the query.
– The names of the columns need not be identical.
– Column names in the output are taken from the column
names in the first SELECT statement.
UNION operator
• The UNION set operator returns the combined results of the two (or more) SELECT
statements without duplicate records.
• The UNION operator returns all rows from both tables, after eliminating duplicates.
SELECT a_id A B
FROM a 1 6
UNION 4
2 5 7
SELECT b_id 3 8
FROM b;
• The result of listing all elements in A and B eliminating duplicates
is {1, 2, 3, 4, 5, 6, 7, 8}.

• If you joined A and B you would get only {4, 5}. You would have to perform
a full outer join to get the same list as above.
UNION ALL operator
• The UNION ALL set operator returns the combined results of the two (or more)
SELECT statements with duplicate records.
• The UNION ALL operator returns all rows from both tables, without eliminating
duplicates.
SELECT a_id A B
4
FROM a 1 5 6
UNION ALL 2 4 7
5
SELECT b_id 3 8
FROM b;

• The result of listing all elements in A and B without


eliminating duplicates is {1, 2, 3, 4, 5, 4, 5, 6, 7, 8}.
INTERSECT operator
• Intersect operator returns all the records(rows or tuples)
common to all the select statements.
• The INTERSECT operator returns all rows common to
both
SELECT tables.
a_id FROM a A B
INTERSECT 4
SELECT b_id FROM b; 5

• The result of listing all elements found in both A and B is


{4, 5}.
MINUS (EXCEPT)
• The MINUS(EXCEPT) operator returns all rows found in one
table but not the other.
SELECT a_id A B
FROM a 1
MINUS 2
SELECT b_id 3
FROM b;

• The result of listing all elements found in A but not B is


{1, 2, 3}.
• The result of B MINUS A would give {6, 7, 8}.
36
SET OPERATORS-
UNION,INTERSECT, EXCEPT(MINUS)
• The set operations union, intersect, and except operate on
relations and correspond to the relational algebra operations ∪,
∩, −.
• Each of the above operations automatically eliminates duplicates;
to retain all duplicates use the corresponding multi set versions
union all, intersect all and except all.
Suppose a tuple occurs m times in r and n times in s, then, it
occurs:
– m + n times in r union all s
– min(m,n) times in r intersect all s
– max(0, m – n) times in r except all s
Set Operations
• Find all customers who have a loan, an account, or both:
(select customer_name from depositor)
union
(select customer_name from borrower)
• Find all customers who have both a loan and an account.
(select customer_name from depositor)
intersect
(select customer_name from borrower)
• Find all customers who have an account but no loan.
(select customer_name from depositor)
except
(select customer_name from borrower)
SET OPERATORS-
• Cust_br1(cid,cname,gender,mobile,city)
Cust_br2(cid,cname,gender,mobile,city)
Cust_br3(cid,cname,gender,mobile,city)
1. Write a query to get the customer names
from all branches
2. Write a query to get the customer names
common to branch1 and branch2
3. Write a query to get the customer names
unique to branch1
SQL FUNCTIONS
• A function is used to perform specific task.
• SQL functions are pre defined functions.
• SQL functions are divided into two categories:
– Group/Aggregate Functions
• Group functions acts on set of values and generates single output value.
• Example: SUM(),AVG(),MAX(),MIN(),COUNT()
– Scalar/Single Row Functions
• Scalar functions acts on group of values but generate group of output values
• Example: length(),upper(),lower(),substr()…..
• SCALAR Functions and AGGREGATE Functions both return a single value result.
AGGREGATE Functions operate on many records while SCALAR Functions operate
on each record independently.
• Types of functions:
– Numeric Functions
– Date Functions
– String Functions
– Conversion Functions
Aggregate(Group) Functions
• Aggregate functions operate on the multi set of values of a column of a relation, and return a
value

AVG([distinct] A): The average of all (unique) values in the A column

SUM([distinct] A): The sum of all (unique) values in the A column

COUNT([distinct] A): The number of all (unique) values in the A column

MAX(A): The maximum value in the A column.

MIN(A): The minimum value in the A column.

• All the aggregate functions are used in Select statement.


Syntax −
SELECT <FUNCTION NAME> (<PARAMETER>) FROM <TABLE NAME>

• Example: Write a query to find out average salary from employee table.

SQL>Select AVG(salary) from Employee;


Aggregate Function- MIN

•This function has the syntax MIN(<x>), where x is an expression. This function
returns the lowest value in the expression x.
•If the expression x is a date data type, it returns a DATE. For dates, the minimum
is the earliest date.
•If the expression x is a numeric data type, it returns a NUMBER. For numbers, the
minimum is the smallest number.
•If the expression is a character data type, it returns a VARCHAR2. for character
strings, the minimum is the one that sorts lowest based on the database character
set.
Aggregate Function- MAX

This function has the syntax MAX( <x>), where x is an expression. This function returns
the highest value in the expression x.
•If the expression x is a date data type, it returns a DATE. For dates, the maximum is
the latest date.
•If the expression x is a numeric data type, it returns a NUMBER. For numbers, the
maximum is the largest number.
•If the expression is a character data type, it returns a VARCHAR2. for character strings,
the maximum is the one that sorts highest based on the database character set.
Aggregate Function- AVG
Aggregate Function- SUM
Aggregate Function- COUNT
Aggregate Functions (Cont.)
• Find the average account balance at the Perryridge branch.
select avg (balance)
from account
where branch_name = 'Perryridge'
● Find the number of tuples in the customer relation.
select count (*)
from customer
● Find the number of depositors in the bank.
select count (distinct customer_name)
from depositor
• GROUP BY:
GROUP BY clause
– GROUP BY clause is used to group rows based on one or more columns and calculate aggregates
like min, max ,sum, avg, count for each group.
– It is used to grouping the similar data based on the columns.
– Group by clause can be applied on multiple columns.
Syntax: SELECT column_name(s),group_function(column_name)
FROM table_name
[WHERE condition]
GROUP BY column_name(s)
[HAVING condition]
[ORDER BY column_name(s);]
GROUP BY clause
Aggregate Functions – Group By
• Find the number of depositors for each branch.
select branch_name, count (distinct customer_name)
from depositor, account
where depositor.account_number = account.account_number
group by branch_name

Note: Attributes in select clause outside of aggregate functions must


appear in group by list
HAVING clause
• HAVING clause always used with GROUP BY clause.
• Having clause is used to filter groups.
• Having clause is applied after group by clause
• Group functions cannot be used in the WHERE clause.
• A SQL statement can have both a WHERE clause and a
HAVING clause. WHERE filters data before grouping;
HAVING filters data after grouping.
• Syntax: SELECT column_name(s),group_function(column_name)
FROM table_name
[WHERE condition]
GROUP BY column_name(s)
HAVING condition
[ORDER BY column_name(s);]
Aggregate Functions – Having Clause
• Find the names of all branches where the average account balance is
more than $1,200.
select branch_name, avg (balance)
from account
group by branch_name
having avg (balance) > 1200

Note: predicates in the having clause are applied after the


formation of groups whereas predicates in the where
clause are applied before forming groups
•Write a query to find out the total salary of all employees in dept no 10,20 and
total salary should be greater than 50000
ORDER BY clause:Ordering the Display of Tuples
• The SQL ORDER BY clause is used to sort the data
in ascending or descending order, based on one or
more columns. Sort the query results in an
ascending order by default.
• Syntax
The basic syntax of the ORDER BY clause is as
follows-
SELECT column-list FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
ORDER BY clause:Ordering the Display of Tuples
• List in alphabetic order the names of all customers having a
loan in Perryridge branch
select distinct customer_name
from borrower, loan
where borrower loan_number = loan.loan_number and
branch_name = 'Perryridge'
order by customer_name
• We may specify desc for descending order or asc for
ascending order, for each attribute; ascending order is the
default.
– Example: order by customer_name desc
JOINS in SQL
• JOINS are used to retrieve the data from multiple tables.
• Types of joins:
ANSI format joins: join condition specified using “ON” key word
– INNER JOIN: Retrieve the data from multiple tables based on equality condition. Common
column is required
– OUTER JOIN
– LEFT OUTER JOIN
– RIGHT OUTR JOIN
– FULL OUTER JOIN
– NATURAL JOIN
Non ANSI format joins: join condition specified using “WHERE” key word
– Equi join
– Non equi join
– Self join
– Cross join
Self Join
• Joining a table with itself is called self join.
• Comparing values of a column with the values of same column itself or different column values of
the same table.
• Self Join Syntax
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

Example Queries:
• Display the employ details who is living in the city where RAJU is living.
select e2.* from emp e1,emp e2 where e1.ename=‘RAJU’ and e1.city=e2.city;

• Find the names of all branches that have greater assets than some branch located in
Brooklyn.
select distinct T.branch_name
from branch as T, branch as S
where T.assets > S.assets and S.branch_city = 'Brooklyn'
Nested Queries/Sub Queries
• A Nested query is a query that has another query embedded within it. The
embedded query is called a sub query.
• A query with in another query is called as sub query.
• A sub query is a SELECT statement that is nested within another SELECT statement
• Syntax:
SELECT *FROM TableName WHERE condition(SELECT * FROM …..(SELECT * from
…..))
• Execution Process is from inner most query to outer most query .
• Types of Sub Queries:
Based on the execution process of sub query, there are two types of sub queries:
1)Non correlated Sub Query:
• First inner query is executed later outer query will be executed.
• Outer query is always depends on the result of the inner query
2)Correlated Sub query
• First outer query is executed later inner query will be executed
• Inner query is always depends on the result of the outer query
Non correlated Subquery
Types of Non Correlated subqueries :
▪ Simple/Single row sub query
▪ Multiple rows sub query
Simple/Single row subquery:
If a sub query returns single value then it is called as simple subquery
Example: emp(eno,ename,sal,deptno)
dept(deptno,dname)
– Write a query to find the employ details who is getting highest salary in the company.
select * from emp where sal=(select max(sal) from emp);
– Write a query to find the employ details who is getting minimum salary in the company.
select * from emp where sal=(select min(sal) from emp);
– Write a Query to display the department name for the empno 1024.
select dname from dept where deptno=(select deptno from emp where eno=1024);
– Write a query to display the Accounting department employee details
select * from emp where deptno=(select deptno from dept where dname=‘Accounting’)
Non correlated Subquery(cont..)
Multiple rows sub query:
If a sub query returns multiple values then it is called as simple sub query.

Example: emp(eno,ename,sal,deptno)
dept(deptno,dname)
Write a query to get the employ details working under either Accounting or Research department
Select * from emp where dno in(select dno from dept where dname in(‘Accounting’,Research’));
Correlated Sub queries
• A correlated subquery is evaluated once for each row
processed by the outer query.
• First outer query is executed later inner query will be
executed
• Inner query is always depends on the result of the
outer query.
• EXISTS and NOT EXISTS operators are used between
outer query and inner query.
Correlated Sub queries
Examples: emp(eno,ename,sal,deptno) dept(deptno,dname)
• Write a query to get the department details if they have at least one employee with in it.
Select d.* from dept d
where exists(select eno from emp where e.deptno=d.deptno);
• Write a query to get the department details if they have no employees with in it.
Select d.* from dept d
where not exists(select eno from emp where e.deptno=d.deptno);
• Find the names of sailors who have reserved boat number 103.
select s.sname from sailor s
where exists(select * from reserves r where r.bid=103 and r.sid=s.sid).

• Example: Professor(Eid,Name) Student(Sid,name,eid)


Get the eid and name of the professor who is an advisor for at least one student.
SELECT eid,name from professor p where exists(select sid from student s where s.eid =p.eid);
Query to Get account types information if there is at least one
customer opted for that account
Query to Get account types information if there is at least one
customer opted for that account

Query to Get account types information if there is no


customer opted for that account
Null Values
• It is possible for tuples to have a null value, denoted by null, for some
of their attributes
• null signifies an unknown value or that a value does not exist.
• The predicate is null can be used to check for null values.
– Example: Find all loan number which appear in the loan relation with null
values for amount.
select loan_number
from loan
where amount is null
• The result of any arithmetic expression involving null is null
– Example: 5 + null returns null
• However, aggregate functions simply ignore nulls
– More on next slide
Null Values and Three Valued Logic
• Any comparison with null returns unknown
– Example: 5 < null or null <> null or null = null
• 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
– “P is unknown” evaluates to true if predicate P evaluates to unknown
• Result of where clause predicate is treated as false if it evaluates to
unknown
Null Values and Aggregates
• Total all loan amounts
select sum (amount )
from loan
– Above statement ignores null amounts
– Result is null if there is no non-null amount
• All aggregate operations except count(*)
ignore tuples with null values on the
aggregated attributes.
Complex Integrity Constraints
• An Integrity Constraints describes conditions that every legal instance of
a relation must satisfy.
• Inserts/deletes/updates that violate IC’s are disallowed.
• Can be used to ensure application semantics (e.g., sid is a key), or prevent
inconsistencies (e.g., sname has to be a string, age must be < 200)
• Types of IC’s:
– Domain constraints,
– primary key constraints,
– foreign key constraints,
– general constraints.
• Domain constraints: Field values must be of right type. Always enforced
Complex Integrity Constraints:
Constraints over a single Table
• Can Specify complex Constraints over a single Table using table constraints, which have the form
CHECK condition expression
• Can use queries to express constraint.
• Constraints can be named.
Example: To ensure that rating must be an integer in the range 1 to 10.
CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER,
age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10 )

Example: To enforce the constraint that Interlake boats can not be reserved
CREATE TABLE Reserves (sid INTEGER ,
bid INTEGER,
day DATE,
PRIMARY KEY (sid,bid,day),
FOREIGN KEY(sid) REFERENCES sailors(sid),
FOREIGN KEY(bid) REFERENCES Boats(bid),
CONSTRAINT noInterlakeRes CHECK (`Interlake’ <> ( SELECT B.bname FROM
Boats B WHERE B.bid=Reserves.bid)))
Complex Integrity Constraints:
Domain Constraints and Distinct Types
• A domain is essentially a data type with optional
constraints (restrictions on the allowed set of values).
• A user can define a new domain using the CREATE
DOMAIN statement. Which uses CHECK constraints.
• CREATE DOMAIN ratingval INTEGER DEFAULT 1
CHECK(VALUE >= 1 AND VALUE <= 10)
• Distinct Types:
CREATE TYPE ratingtype AS INTEGER;
Complex Integrity Constraints:
Assertions: Integrity Constraints over Several Tables
• An assertion is a predicate expressing a condition that we wish the
database always to satisfy.
• It is a statement in SQL that ensures a certain condition will always
exist in the database.
• SQL assertion is a CHECK constraint at the database level.

• Assertions are not associated with any tables.


• Assertions are checked only when UPDATE or INSERT actions are
performed against the table
• Syntax:
create assertion assertion_name CHECK predicate
Complex Integrity Constraints:
Assertions: Integrity Constraints over Several Tables
• CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10),
rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK (
(SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT
(B.bid) FROM Boats B) < 100 )
• Awkward and wrong! If Sailors is empty, the number of
Boats tuples can be anything!
• ASSERTION is the right solution; not associated with either
table.
• CREATE ASSERTION smallClub CHECK ( (SELECT COUNT
(S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM
Boats B) < 100
Complex Integrity Constraints:
Assertions: Integrity Constraints over Several Tables
• Example 1:
Sum of loans taken by a customer does not exceed 100,000
Create Assertion SumLoans Check( 100,000 >= ALL(Select Sum(amount)From borrower B , loan L
Where B.loan_number = L.loan_number Group By customer_name) );

• Example 2:
Number of accounts for each customer in a given branch is at most two
Create Assertion NumAccounts Check( 2 >= ALL(Select count(*)From account A , depositor D
Where A.account_number = D.account_number Group By customer_name, branch_name );

• Example 3:
Customer city is always not null
Create Assertion CityCheck Check( NOT EXISTS (Select *From customerWhere customer_city is null));

Assertion Example
Every loan has at least one borrower who maintains an account with a
minimum balance or $1000.00
create assertion balance_constraint check
(not exists (
select *
from loan
where not exists (
select *
from borrower, depositor, account
where loan.loan_number = borrower.loan_number
and borrower.customer_name = depositor.customer_name
and depositor.account_number = account.account_number
and account.balance >= 1000)))

Assertion Example
The sum of all loan amounts for each branch must be less
than the sum of all account balances at the branch.
create assertion sum_constraint check
(not exists (select *
from branch
where (select sum(amount )
from loan
where loan.branch_name =
branch.branch_name )
>= (select sum (amount )
from account
where loan.branch_name =
branch.branch_name )))
Triggers and Active Databases
• A trigger is a procedure that is automatically invoked by the
DBMS in response to specified changes to the databases.
• A database that has a set of associated triggers is called an
active database
• A trigger description contains three parts:
– Event: A change to the database that activates the trigger.
– Condition: A query or test that is run when the trigger is
activated
– Action: A procedure that is executed when the trigger is activated
and its condition is true
Triggers in PL/SQL
• PL/SQL is a combination of SQL along with the procedural features
of programming languages.
• PL/SQL has the following features :
– PL/SQL is tightly integrated with SQL.
– It offers extensive error checking.
– It offers numerous data types.
– It offers a variety of programming structures.
– It supports structured programming through functions and procedures.
– It supports object-oriented programming.
– It supports the development of web applications and server pages.
Triggers
• A trigger is a course of action to be taken when any DDL,DML event
occurs.
• It is a named PL/SQL block like a procedure.
• But it is executed implicitly by DBMS(Oracle Server)
• Types of triggers:
– DML Triggers(Table Level)
– DDL Triggers(Database Level)
• Triggers are created to :
– Control DML
– Integrity of data
– Implement complex business rule
– Implement complex validations
– For auditing
– Maintain replicas
Triggers
• General Syntax for Triggers:

CREATE [OR REPLACE ] TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF }


{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
[WHEN (condition)]
[DECLARE
Declaration-statements]
BEGIN
Executable-statements
[EXCEPTION
Exception-handling-statements]
END;
Triggers
• Before Trigger:
Before trigger is executed before executing a DML command.
Sequence:
– Trigger Execution
– DML Execution

• After Trigger:
After trigger is executed after executing a DML command.
Sequence:
– DML Execution
– Trigger Execution
Triggers
• DML Triggers:
– These triggers are executed automatically whenever user performs DML
operation on the table.
• Levels of DML Triggers:
– Statement Level Trigger(default): Executed only once for the statement
– Row Level Trigger: Executed once for each row affected by the DML
Triggers
• Statement Level Trigger(default):
Example:
create or replace trigger emptrg
before update on employ
begin
dbms_ouput.put_line(‘Record Updated’);
End;
/

• Row Level Trigger:


Example:
create or replace trigger emptrg1
before update on employ
for each row
begin
dbms_ouput.put_line(‘Record Updated’);
End;
/
Triggers
• DDL Triggers(Database level) :
These triggers are executed automatically whenever user performs DDL operation on the Database Schema.
Example:

SQL> CREATE OR REPLACE TRIGGER trg1


BEFORE DROP ON schema
BEGIN
Dbms_output.put_line(‘Dropped’);
End;
/
Triggers
• Bind variables(Row type Variables):
:old
:new
Triggers
Examples:
Create or replace TRIGGER increase_sal_trig before update of sal on employ
Begin
insert into sal_hist(increased,changedon)values('YES',SYSDATE);
end;
/
Triggers
Examples:
CREATE OR REPLACE TRIGGER STU_TRG BEFORE INSERT ON STUDENTS
For EACH ROW
BEGIN
UPDATE STUDENTS
SET tot=:new.m1+:new.m2+:new.m3,avg=(:new.m1+:new.m2+:new.m3)/3;
END;
/

You might also like