Chapter 7
Chapter 7
Chapter 7
CHAPTER 7
Characteristics of SQL
4. SQL has a very small set of Commands, which makes it easy to learn.
Advantages of SQL
2. Applications written in SQL can be easily ported from one system to another.
Such a need would arise when a system needs upgrade or change.
P S Gill
2
6. The language, while being very simple, flexible and easy to learn, it has very
powerful features, which enable it to perform very complex operations in a
DBMS.
P S Gill
3
11. DATE This data type has ten positions embedded in single quotes
i.e. ‘DD-MM-YYYY’; for example ‘31-05-1950’ implies 31st May 1950.
12. TIME This data type has at least 8 positions embedded in single quotes
‘HH:MM:SS’; For example ’11:07:05’ implies 11.07.05 AM and ’23:07:05’
implies 11.07.05 PM.
14. INTERVAL It specifies a time interval, a relative value that can be used
to increment or decrement an absolute value of DATE, TIME or
TIMESTAMP. The intervals are qualified either as YEAR/MONTH
intervals or DAY/TIME intervals.
‘DBMS’
‘Structured Query Language’
P S Gill
4
77.00
+77.77
-69
900
0.9
77.00E9
-7.7E8
+76.7E-4
+76.8E5
1. Data Definition Language (DDL) It is used for defining the database schema
i.e. to CREATE, ALATER & DROP Tables, Views and Indexes; like CREATE
TABLE, ALTER TABLE, DROP TABLE, CREATE VIEW, DROP VIEW,
CREATE INDEX, DROP INDEX.
P S Gill
5
SQL Operators
2. Comparison Operators:- =, > , < , >=, <=, ( != , <> , = ) , IN, NOT IN, IS
NULL, IS NOT NULL, LIKE, ALL, (ANY , SOME), EXISTS, NOT EXISTS,
BETWEEN x AND y .
Operator Precedence
NOT |
AND | Logical Operators
OR |
UNION |
INTERSECT | Set Operators
MINUS |
P S Gill
6
Creating a Table
The following DDL Statement will add a new Table STUDENT to the DBMS Catalog,
with the attributes and data types as explicitly clear from the statement. It indicates that
attribute REG_NO is primary key and attribute ROLL_NO is Unique, which implies that
ROLL_NO is a candidate key of STUDENT.
Similarly, the following DDL Statements will add new Tables RESULT, EMPLOYEE
and DEPT to the DBMS Catalog.
P S Gill
7
The following DDL statement will add a new attribute STATUS of type INT to the
existing Table EMPLOYEE.
The following DDL statement will remove the existing Table RESULT from the DBMS
Catalog.
Creating a View
The following statement will create a VIEW named DEPT_TOTAL_SAL with two
attributes D_NO and T_SAL by selecting DEPT_NO and TOTAL_SAL of existing Table
DEPT.
There will not be any table named DEPT_TOTAL_SAL; only its definition will be stored
in the DBMS Catalog. Whenever, a reference is made to DEPT_TOTAL_SAL in any
SQL Query, a table will be created with the help of the definition and the table will be
deleted after answering the query. For Example:-
SELECT DEPT_NO
FROM DEPT_TOTAL_SAL
WHERE T-SAL > 10000000;
The following SQL Statement will create VIEW named DEPT_AVG_SAL with attributes
D_NO and AVG_SAL from existing table EMPLOYEE. The attribute AVG_SAL is
computed by taking average of the salary of the employees of each department.
P S Gill
8
Creating Indexes
The following statement will create a unique Index on the primary key EID of Table
EMPLOYEE.
The following statement will create a unique Index on the primary key EID of Table
EMPLOYEE.
Dropping an Index
A Query refers to a SELECT Statement used to extract information from the Tables.
Query Get Department Number and Average Salary of the employees of Dept Number 3
or more and having more than 10 employees; and order the information in descending
order of Average Salary.
Query List Employee Names along with the Names of their respective Dept Heads.
P S Gill
9
Aggregate Functions
Query Find Average Marks and Total Marks obtained by each Student
Query Find Minimum, Maximum and Average Marks obtained in each Subject.
P S Gill
10
UPDATE EMPLOYEE
SET SALARY = 55000
WHERE EID = ‘0012240L’;
UPDATE EMPLOYEE
SET SALARY = SALARY * 1.1;
JOINS
Query Get the Names of Students, who have appeared for Subject ‘TCS501’
This Query involves a Natural Join of STUDENT and RESULT and in Relational
Algebra it can be written as:-
P S Gill
11
UNION
Query Get the Names of the Students, who have appeared for subject
‘TCS501’ or for ‘TCS503’ or for both.
UNION
T1 STUDENT * RESULT
S_NAME (SUB_CODE= “TCS501” (T1)) S_NAME (SUB_CODE = “TCS503” (T1))
INTERSECT
Query Get the Names of the Students, who have appeared both for
‘TCS501’ and ‘TCS503’.
INTERSECT
P S Gill
12
T1 STUDENT * RESULT
S_NAME (SUB_CODE= “TCS501” (T1)) S_NAME (SUB_CODE = “TCS503” (T1))
Query Get the Names of the Students, who have appeared for subject
‘TCS501’ but not for ‘TCS503’.
MINUS
T1 STUDENT * RESULT
S_NAME (SUB_CODE= “TCS501” (T1)) - S_NAME (SUB_CODE = “TCS503” (T1))
Cursors in SQL
Cursor is a Construct in PL/SQL that enables a user to earmark a private memory area to
hold an SQL Statement for accessing later on.
Example
Suppose Total Marks Scored by a Student are to be extracted from RESULT and to be
entered into Table TOTAL_MARKS (ROLL_NO, T_MARKS).
DECLARE
CURSOR C_Student IS
SELECT ROLL_NO, SUM (MARKS)
FROM RESULT
GROUP BY ROLL_NO;
C_NO CHAR (10);
P S Gill
13
C_TOTAL INT;
BEGIN
OPEN C_Student;
LOOP
FETCH C_Student INTO C_NO, C_TOTAL;
EXIT WHEN C_Student%NOTFOUND;
INSERT INTO TOTAL_MARKS
VALUES (C_NO, C_TOTAL);
END LOOP;
CLOSE C_Student;
COMMIT;
END;
P S Gill
14
DDL
P S Gill
15
Suppose there is a constraint that account balance should not be less than 1000,
it can be added to the table Account as follows:-
ALTER TABLE Account ADD CONSTRAINT Check_Bal CHECK (Bal >= 1000);
P S Gill
16
Here D# in Emp is a foreign key referencing D# of Dept, Mgr# in Dept is a foreign key
referencing E# of Emp and Total_Sal in Dept is total salary of all the employees working
in a department. The situation is little tricky here:-
(i) Both the tables are referencing each other. If we create the Emp table first and
declare D# as foreign key referencing Dept (D#), the system will generate
exception “table or view does not exist” since the table Dept is non-existent.
Similar situation will occur if we attempt to create Dept first and declare
Mgr# as foreign key referencing Emp (E#).
(j) Insertion of data into the tables will also face problem. If we attempt into
Emp first, it will attempt to reference a non-existent tuple in table Dept for
P S Gill
17
Note that the foreign key constraints added to the above tables are of type
“Initially deferred deferrable”. This implies that while inserting data, the check for
compliance of foreign key constraints will be deferred till the next COMMIT statement is
executed. This will enable data entry into the two tables in any sequence, as long as the
information in the two tables is compatible at the time of execution of next COMMIT
statement.
P S Gill
18
CREATE TABLE Class ( Year INT, Branch Char(3), Section INT, Strength INT,
PRIMARY KEY (Year, Branch, Section),
CHECK (Branch IN
(‘CSE’,’IT’,’ECE’,’IC’,’ME’,’EE’, ’MT’)),
CHECK (Year BETWEEN 1 AND 4),
CHECK (Section BETWEEN 1 AND 2));
Creation of Indices
P S Gill
19
Since (Day, Period, Fac_Code) is a candidate key of Time_Table, we can create on this
combination of the columns.
Dropping of Tables
Dropping of Constraints
Dropping of Columns
Dropping of Indices
Take the case of tables Emp and Dept. Suppose table Emp is to be dropped, the system
would not permit this, since the dropping of Emp would violate the foreign key constraint
Dept_FK of table Dept. Dropping of Emp and Dept is achieved as follows:-
P S Gill
20
DML
1. Add a new customer to table Customer with C_Id = ‘C101’, C_Name = ‘Ajay’,
C_Street =’S-26’ and C_City = ‘Noida’.
2. Add a new student to the Student Table with Roll_No = ‘091010120’, S_Name =
‘Vijay’, S_Address = ‘S-27 Noida’. (Note that information about S_DOB is missing. It is
not a NOT NULL attribute, so it can be assigned a NULL value).
The above NULL can also be inserted as follows (the attribute name S_DOB is omitted
from the attribute list specified with the table name):-
Since attribute name S_DOB is not listed in the list of attributes listed with the table
Student, NULL value will be assigned to this attribute. As indicated, the attributes can be
listed in any order. Then the values have to specified in the same order.
SELECT *
FROM Student;
P S Gill
21
SELECT *
FROM Student
WHERE S_DOB >= ’01-JAN-1995’ AND DOB <= ’31-DEC-1995’;
SELECT *
FROM Student
WHERE S_DOB BETWEEN ’01-JAN-1995’ AND ’31-DEC-1995’;
SELECT *
FROM Student
WHERE S_DOB LIKE ‘%95’;
5. Get Roll_No and DOB of all students born before 01st Jan 1995.
6. SELECT *
FROM Account
WHERE AN = &numb;
Here numb is a substitution variable, whose value will be accepted by the system by
displaying prompt ‘Enter Value for numb:’. Each time the query is executed, a different
value for numb can be entered like A101, A105 etc.
7. Get the names of students who got more than 90 marks in any subject.
Here, we perform natural join of Result and Student and pick up names of those
students who have scored more than 90 marks in any subject.
P S Gill
22
Since attribute name Roll_No appears in both the tables specified in the FROM
clause, we need to qualify by the table name, while using this attribute name in
subsequent clauses. However, this is not the problem with attribute Marks, since it
appears only in table Result.
The qualifier DISTINCT has been used in the SELECT clause to avoid duplicates
names from appearing in the result in the case of those students who have scored
more than 90 marks in more than one subjects.
The above query can be expressed more elegantly by declaring a tuple variable
say R on the table Result and another tuple variable S on the table Student, as
shown below:-
8. Get the customer and account number of those customers, who are living in Noida
but having account in Delhi and have Balance more than 100000.
9. Get the Roll_No of those students whose DOB is not specified in the Student
table.
SELECT Roll_No
FROM Student
WHERE S_DOB IS NULL;
Using Aliases
Here, the Attributes in the resulting table will be named as Customer_Name and
Account_Number.
P S Gill
23
Arithmetic Operations
12. Suppose there is a schema Emp (E_Id, E_Name, Basic_Pay, DA, HRA,
Deduction). We can have query to determine gross salary of each employee:-
SELECT *
FROM Result
ORDER BY Marks;
SELECT *
FROM Result
ORDER BY Marks DESC;
P S Gill
24
18. Get Min Balance, Max Balance and Total Balance at each branch.
19. Get the names and Total Marks of those students who have scored Average Marks
more than 80%.
This will display total marks of each student having average score > 80%.
P S Gill
25
All tuples of Depositor will appear in the result. Wherever, LN is not defined, it
will be indicated by NULL.
All tuples of Borrower will appear in the result. Wherever, AN is not defined, it
will be indicated by NULL.
22. Get the Customer Id and name of those customers who have both account and
loan from the bank.
Here (SELECT C_Id FROM Borrower) is called inner sub-query and the main query
SELECT C.C_Id, C_Name FROM Custmer C, Depositor D WHERE C.C_Id = D.C_Id
AND C_Id IN ( ) is called outer query. The inner query can be evaluated independent of
the outer query. Such a query is evaluated in two steps:-
(i) First evaluate the inner sub query and save its output.
(j) Now evaluate the outer sub query wrt the result produced by inner sub-
query.
Evaluation of inner sub-query will produce a set of C_Id of those customers who have a
loan from the bank. For each C_Id existing in the depositor table, the outer sub-query will
examine whether that C-Id exists in the set produced by inner sub-query. If the answer is
“Yes” then that C_Id belongs to a customer having both account and loan and the
customer’s name appears in the final output table.
23. Get names of the customers having joint account with customer Ajay.
SELECT CN
FROM Customer C, Depositor D
WHERE C.C_Id = D.C_Id AND CN <>’Ajay’
AND AN IN ( SELECT AN
FROM Customer K, Depositor P
WHERE K.C_Id = P.C_Id AND CN =’Ajay’);
P S Gill
26
The inner sub-query will produce set of Account Numbers held by custmer ‘Ajay’. The
outer sub-query will determine the other customers who are having an account held by
‘Ajay’.
24. Get Branch Id and Name of the branch having highest average balance amongst
all branches.
Here, the inner sub-query is not independent of the outer sub-query. So, inner sub-query
is evaluated for each tuple of the outer sub-query.
25. Get the names of the customers who have account in each branch located in
Noida.
SELECT C_Name
FROM Customer C
WHERE NOT EXISTS (( SELECT B_Id
FROM Branch
WHERE B_City = ‘Noida’)
MINUS
( SELECT B_Id
FROM Account A, Depositor D
Updating of tables
P S Gill
27
Creation of Views
Dropping of Views
P S Gill
28
PL/SQL
SQL does not support any control statements like WHILE… DO, IF…THEN… ELSE
etc. The programming language PL is a general-purpose programming language that
supports such control statements and also permits embedding of SQL statement in its
blocks. Thus, PL/SQL is a programming language that combines the processing power of
a general-purpose programming language like Pascal, C etc and the database handling
capabilities of SQL.
DECLARE
BEGIN
EXCEPTION
Exception handlers
END;
IF….THEN…END IF;
IF….THEN….ELSE…END IF;
IF….THEN….ELSIF…ELSIF…ELSE…END IF;
WHILE…LOOP….END LOOP;
P S Gill
29
FOR…….LOOP….END LOOP;
GOTO…..;
SET SERVEROUTPUT ON
DECLARE
X INT;
BEGIN
X := 0;
WHILE ( X <= 99)
LOOP
X := X+1;
DBMS_OUTPUT.PUT_LINE (TO_CHAR(X*X));
END LOOP;
END;
ANUMB Account.AN%TYPE;
Balance Account.Bal%TYPE;
Credit_Amount Account.Bal%TYPE;
Debit_Amount Account.Bal%TYPE;
BEGIN
ANUMB := &ANUMB;
SELECT Bal INTO Balance
FROM Account WHERE AN = ANUMB;
DBMS_OUTPUT.PUT_LINE (‘Balance of Account Number ‘ || ANUMB || ‘
before update was ‘|| TO_CHAR (Balance));
Credit_Amount := &Credit_Amount;
P S Gill
30
Debit_Amount := &Debit_Amount;
UPDATE Account
SET Bal = Bal + Credit_Amount –Debit_Amount
WHERE AN = ANUMB;
SELECT Bal INTO Balance
FROM Account WHERE AN = ANUMB;
DBMS_OUTPUT.PUT_LINE (‘Balance of Account Number ‘ || ANUMB || ‘
after update is ‘|| TO_CHAR (Balance));
END;
Program:
DECLARE
Cid Customer.C_Id%TYPE;
CN Customer.C_Name%TYPE;
CS Customer.C_Street%TYPE;
CC Customer.C_City%TYPE;
AN Account.AN%TYPE;
Bid Account.B_Id%TYPE;
Bal Account.Bal%TYPE;
BEGIN
Cid := &Cid; CN := &CN; CS := &CS; CC := &CC;
AN := &AN; Bid := &Bid; Bal := &Bal;
INSERT INTO Customer VALUES (Cid, CN, CS, CC);
INSERT INTO Account VALUES (AN, Bid, Bal);
INSERT INTO Depositor VALUES (Cid, AN);
END;
P S Gill
31
TRIGGERS
Trigger:
P S Gill
32
THEN
BEGIN
UPDATE DEPT
SET TOTAL_SAL = TOTAL_SAL + :NEW.SALARY
WHERE DEPT.D_NUMB = :NEW.D#;
END;
END IF;
END;
CURSORS
DECLARE
CURSOR cursor-name IS SELECT statement;
OPEN cursor-name;
Each time a Fetch statement is executed, the cursor moves to the next
row in the active set. After the last row, it returns cursor-name
%NOTFOUND to be true.
(iv) Closing a Cursor: After processing the data in the active set, a
cursor is close.
CLOSE cursor-name;
P S Gill
33
Since, there is max limit ob the number of cursors currently open, a cursor
should be closed when it is done with.
Cursor:-
DECLARE
CURSOR C1 IS SELECT E#, Salary FROM Emp WHERE salary > 40000;
eno Emp.E#%TYPE;
sal Emp.Salary%TYPE;
BEGIN
OPEN C1;
IF C1%ISOPEN THEN
LOOP
FETCH C1 into eno, sal;
EXIT WHEN C1%NOTFOUND;
UPDATE Emp SET Salary = Salary * 1.5 WHERE E# = eno;
END LOOP;
CLOSE C1;
END IF;
EXCEPTION
WHEN INVALID_CURSOR THEN
DBMS_OUTPUT. PUT_LINE (‘Invalid Cursor’);
END;
P S Gill
34
ASSERTIONS
P S Gill
35
Let r1 and r2 be two relations with K as primary key of R 1 and as such that
Foreign Key in R2 referencing K1 in R1.
Insert If a tuple t2 is inserted in r2, the system must ensure that there exists a
tuple t1 r1 such that t1 [K] = t1 [] that is, t2 [] K1(r1).
Delete If a tuple t1 is deleted from r1, the system must compute a set of
tuples in r1 that reference t1, that is set S = K1(r2)
If set S is not empty an empty set, then either the Delete Command should be
rejected as an error or all tuples that reference t 1 (directly or indirectly) must also
be deleted. As obvious, this would result in a cascading delete, since the tuples
relations may reference tuples in r2, that further reference t1 r1.
Update
Case I If a tuple t2 is updated in r2 such that the update effects the attribute set
and t2’ is the modified tuple, the system must ensure that there is a tuple t 1 r1
such that t1[K] = t2 [K] i.e. t2 [] K1(r1) must be satisfied.
Case II If a tuple t1 is modified in r1 such that the update effects the primary
key attributes K, the system must compute a set of tuple in r 2 that reference t1,
that is set S = K1(r2).
If this set S is not empty, then either the update command should be rejected as
an error or all tuples that reference t1 (directly or indirectly) must also be
updated. As obvious, this would result in a cascading update since the tuples
may reference tuples that reference t1.
P S Gill
36
(a) A (r)
{ t u r ( t[A]= u[A]) }
{ t t r t[B]= 17 }
(c) r s
Problem 7.2 Let there be Schema R (A,B,C) & and relations r 1 (R) & r2 (R). Give
expressions in Domain Relational Calculus (DRC) equivalent to the following
expressions in Relational Algebra (RA).
(a) A (r1)
{ <a,b,c> <a,b,c> r1 b = 17 }
P S Gill
37
(c) r1 r2
(d) r1 r2
{ <a, b, c> <a, b, c> r1 <a, b, c> r2 }
(e) r1 r2
{ <a, b, c> <a, b, c> r1 <a, b, c> r2 }
(f) A,B (r1) * B,C (r2)
Problem 7.3 Let there be Schemas R (A, B) & S (A, C) and relations r(R) & s(S).
Give Relational Algebra expressions equivalent to the following Domain
Relational Calculus (DRC) expressions.
A ( B=17 (r))
r*s
P S Gill
38
(b) Find the names and the cities of residence of employees working for TCS
DRC: { < en, city > sal ( < en , “TCS” , sal> works-for
st ( < en , st , city> employee )) }
(c) Find name, street and city of residence of employees working for
Infosys and earning more than 20,000
RA: E-NAME, STREET, CITY (COMPANY-NAME = “Infosys” SALARY > 20000 (works_for * employee))
(d) Find names of employees working in the same city where they live
P S Gill
39
(e) Find the names of employees, who are not working for WIPRO
(f) Find the Total and Average Salary Paid by each Company.
(g) Find the names of employees, who earn more than every employee of
TCS
P S Gill
40
FROM works-for
WHERE COMPANY-NAME = ‘TCS’);
(h) Find names of employees, who live in the same street and city as their
managers
=mgr.STREET(emp x mgr(emp)))
(j) Find the Company with the smallest total salary paid to employees.
(k) Find the company whose employees earn more salary on the average
than the average salary of TCS.
P S Gill
41
Problem 7.5 Answer the following queries in RA, SQL, TRC and DRC for
the schema given below:-
(a) Find the names & cities of customers having a loan from the bank.
P S Gill
42
Problem 7.6 Consider the schema shown in Problem # 4 and give relational
algebra expressions for the following:-
P S Gill
43
(d) Give all managers a 10% rise in salary unless salary is 100000 or more;
and in that case give a 3% rise.
RA: r works-for .E-NAME, COMPANY-NAME, SALARY ( works-for .E-NAME= MANAGER-NAME (works-
for X manages))
works-for (works-for – r) E-NEME, COMPANY-NAME, SALARY*1.1 ( SALARY < 10000 (r))
E-NEME, COMPANY-NAME, SALARY*1.03 ( SALARY 10000 (r))
(e) Delete all tuples of works-for for employees working for TCS
RA: works-for works-for – company-name= “TCS” (works-for)
(f) Find the company with max number of employees amongst all the
companies.
P S Gill
44
(h) Find the company, whose employees earn more salary, on the
average, than the average salary of TCS employees.
Write Queries in RA, TRC, DRC & SQL to get names of Students, who secured
‘A’ grade, in the courses offered by “Comp_Sc” department in the “Autumn”
semester.
RA: S-NAME ( GRADE = “A” D-NAME = “Comp-Sc” SEMESTER = “Autumn” (student * deptt *
time-table * performance))
P S Gill
45
P S Gill
46
Write a Query in RA, TRC, DRC & SQL to get part number of parts supplied to all
the projects in “London”
RA: P#, J# (spj) J# ( JCITY= “London” (project))
DRC: { <p#> j#, j-name, j-city ((<j#, j-name, j-city> project jcity =
“London”) s#, qty (<s#, p#, j#, qty > spj))}
P S Gill
47
(a) List all students who appeared in all the courses offered by “Rinkaj”
and scored more than 60 marks in all courses.
RA: r S#, C# ( MARKS > 60 (result)) C# ( TEACHER = “Rinkaj” (course ))
S-NAME (r * student)
DRC: { <s-name> c#, title, teacher ((<c#, title, teacher> course teacher =
‘Rinkaj” ) s#, marks (<s#, c#, marks> result marks > 60
<s#, s-name> student)))}
(b) List the Subject Titles having max failures (Pass Marks = 40)
P S Gill
48
(a) List Names & Phone Numbers of Physicians, who have been
visited by at least one patient.
(a) List the Name & Address of patients, who visited more than one
physician in May 2003
P S Gill
49
(b) List Dept_No with its Total, Max, Min & Average Salary
RA: DEPT-NOG SUM (SALARY), MAX (SALARY), MIN (SALARY), AVG (SALARY) (emp)
P S Gill
50
Problem 7.13
Consider the following relations:-
r
A B
1 12
3 3
1 2
2 5
2 3
1 3
3 1
s
A B
3 3
2 5
4 3
1 5
1 3
Now determine, how the results will differ in the following pairs of
operations:-
A ( r) - A(s) =
A
(b) r -s & s - r
P S Gill
51
r-s
A B
1 12
1 2
2 3
3 1
s-r
A B
4 3
1 5
s B (r) =
A
Exercises
P S Gill
52
(a) Get the details of the employees working on both projects ‘P1’
and ‘P2’.
(d) List the names of the employees who are working on a project
whose manager is ‘E1’.
(a) Find the names of the dealers who supply ‘Red’ parts.
(b) Find the names of the dealers who supply both ‘Yellow’ and ‘Green’
parts.
(c) Find the names of the dealers who supply all the parts.
P S Gill
53
(i) Find total number of persons who owned cars that met with
accidents in 2006.
(ii) Find the number of accidents in which the cars belonging to ‘Mr
Ajay’ were involved.
(v) Update the Damage_Amount for car with License ‘HR3000’ and
Report Number = ‘AR1000’ to Rs 35000.
(I) Get the details of the suppliers who operate from ‘Delhi’ with
Turnover 5000000.
(iii) Get the names of the suppliers whose name begins with ‘A’.
(iv) For each part being supplied, get part number and names of the
cities supplying it.
(v) Get the names of the suppliers who supply part number 2.
P S Gill
54
(i) Find all the employees who work under manager ‘Vijay’.
(v) Find all employees who earn more than the average salary
of their company.
P S Gill