DBMS UNIT-3 Part-1 SQL
DBMS UNIT-3 Part-1 SQL
• SQL
• SCHEMA REFINEMENT
UNIT-3 Syllabus
Text Book-1: Chapter 5 and 19
Text Book-2: Chapter 3 and 7
• 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).
• 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
• 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.
• <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.
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
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;
• Example: Write a query to find out average salary from employee table.
•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
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: 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.
• 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:
• 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;
/