You are on page 1of 54

1

CHAPTER 7

STRUCTURED QUERY LANGUAGE

Structured Query Language (SQL) is a Language used for


interaction with a Relational Database Management System
(RDBMS). It is not only a query language; but also used for
creation, update and maintenance of a database.

Characteristics of SQL

1. It is a non-procedural Language; wherein a Query has to only specify “what”


information is to be retrieved from the database, without specifying “how” the
information is to be retrieved.

2. Its syntax is “English-like”, which makes it very simple and user-friendly.

3. It is highly flexible. A Query in SQL may be written in a number of ways,


without affecting the end results. Also, there are no restrictions of starting a
Query at a particular column or to finish a Query in one line only.

4. SQL has a very small set of Commands, which makes it easy to learn.

5. Each SQL Query is parsed by RDBMS to check its syntax.

6. Each SQL Query is optimized, prior to execution.

Advantages of SQL

1. SQL, being a non-procedural language, provides a great degree of abstraction;


the user does not have to specify “how” the required information is to be
extracted from the database; this is taken care by the RDBMS.

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.

3. Since a query specifies only “what” information is to be extracted, not “how”


to extract it, a query in SQL would return same results, irrespective of the fact
whether is was optimized prior to its execution or not;

4. The expected results of a query are unambiguously defined.

P S Gill
2

5. It is not merely a query language used to retrieve information from database;


but also it is used to define schema, update database, insert new data, delete
defunct data, to define data integrity constraints and to define user access
rights etc.

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.

SQL Data Types & Literals

SQL supports the following Data Types:-

1. CHARACTER (n) Represents a fixed-length string of size n characters;


where “n” is an integer > 0. CHAR (n) is its abbreviation and CHAR is an
abbreviation for CHAR (1).

2. CHARACTER VARYING (n) Represents a varying-length string of


max size n characters; where “n” is an integer > 0. VARCHAR (n) is its
abbreviation.

3. BIT (n) Represents a fixed-length string of size n bits; where “n” is


an integer > 0.

4. BIT VARYING (n) Represents a varying-length string of max size n


bits; where “n” is an integer > 0.

5. NUMERIC (p, q) Represents a Decimal Number; having a total


number of “p” digits and sign, with “q” digits to the right of decimal point;
“q” must be <= “p”. NUMERIC (p) is abbreviation for NUMERIC (p,0).
NUMERIC is abbreviation for NUMERIC (p) where “p” is implementation-
defined.

6. DECIMAL (p, q) It is similar to NUMERIC (p, q). It represents a


Decimal Number; having a total number of “p” digits and sign, with “q” digits
to the right of decimal point; “q” must be <= “p”. DEC (p, q) is an
abbreviation for DECIMAL (p, q). DEC (p) is an abbreviation for DECIMAL
(p, 0). DEC is an abbreviation for DEC (p) where “p” is implementation-
defined.

7. INTEGER Represents a signed integer. INT is its abbreviation.

8. SMALLINT Represents a signed integer. INT is its abbreviation; its


precision will not increase that of INT.

P S Gill
3

9. FLOAT (p) Represents floating point number. FLOAT is an


abbreviation for FLOAT (p) where “p” is implementation defined. REAL is
alternative representation for FLOAT (s) where “s” is implementation-defined.
DOUBLE PRECISION is another representation for FLOAT (d) where “d” is
implementation-defined; but “d” > “s”.

10. BOOLEAN It can assume values TRUE or FALSE.

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.

13. TIMESTAMP It includes both DATE and TIME along with


minimum 6 digits representing decimal fraction of seconds ‘DD-MM-
YYYY HH:MM:SS mmmmmm’;for example ‘31-05-1950 01:02:05
567892’.

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.

The formats of DATE, TIME and TIMESTAMP are considered as special


type of String. So, string operators (say LIKE) can be applied to these
data types.

SQL supports the following Literal Types:-

1. Character String This is written as a sequence of characters enclosed


in single quotes; for example:-

‘DBMS’
‘Structured Query Language’

2. Bit String A bit string is written either as a sequence of 0s and 1s


enclosed in a single bracket and preceded by letter “B” or as a sequence of
Hexadecimal digits preceded by letter “X”; for example:-
B’1001001’
B’1’
B’0’
X’CA8’

P S Gill
4

3. Exact Numeric Written as signed or unsigned decimal number, may


be with a decimal point embedded in it. For example:-

77.00
+77.77
-69
900
0.9

4. Approximate Numeric Written as exact numeric, followed by letter


“E” and followed by signed/ unsigned integer; where mEn implies (m)n.

77.00E9
-7.7E8
+76.7E-4
+76.8E5

TYPES OF SQL COMMANDS

SQL Commands can be classified into the following categories:-

1. Data Definition Language (DDL)


2. Data Manipulation Language (DML)
3. Data Query Language (DQL)
4. Data Control Language (DCL)
5. Data Administrative Statements (DAS)
6. Transaction Control Statements (TCS)

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.

2. Data Manipulation Language (DML) The DML commands are used to


manipulate the information in the tables; like INSERT, UPDATE or DELETE
commands.

3. Data Query Language (DQL) This refers to SELECT command, which is


used to extract information from Tables.
Syntax:-

SELECT < list of attributes and/or aggregate of attributes of tables listed


below>
FROM <list of tables>
WHERE <predicate involving attributes of tables listed above and literals>
GROUP BY <list of attributes>

P S Gill
5

HAVING <predicate involving aggregated values>


ORDER BY ASC/DESC < list of attributes of tables listed above>

4. Data Control Language (DCL) These are security-related commands, which


control user access to the database. Database administrator grants or revokes user
privileges by using GRANT and REVOKE commands.

5. Data Administrative Statement (DAS) These are basically Audit commands


used to analyze the system performance. There are two commands START
AUDIT and STOP AUDIT.

6. Transaction Control Statements (TCS) These commands are used to control


transactions; like SET TRANSACTION, SAVEPOINT, COMMIT and
ROLLBACK.

SQL Operators

1. Arithmetic Operators:- Unary operators like positive or negative expression


(+, -) and binary operators like multiplication ( * ), division ( / ) , addition ( + ) and
subtraction ( - ) .

2. Comparison Operators:- =, > , < , >=, <=, ( != , <> , = ) , IN, NOT IN, IS
NULL, IS NOT NULL, LIKE, ALL, (ANY , SOME), EXISTS, NOT EXISTS,
BETWEEN x AND y .

3. Logical Operators:- AND, OR, NOT.

4. Set Operators:- UNION, UNION ALL, INTERSECT, MINUS.

Operator Precedence

() Enclosing Sub Queries


‘‘ Enclosing Literals
() Overrides normal operator precedence
+, - Unary Operators
*, / Multiplication and division
+, - Addition and Subtraction

NOT |
AND | Logical Operators
OR |

UNION |
INTERSECT | Set Operators
MINUS |

P S Gill
6

Tables, Views & Indexes

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.

CREATE TABLE STUDENT


( REG_NO CHAR(10),
ROLL_NO CHAR (10),
S-NAME VARCHAR (25),
FATHERS_NAME VARCHAR (25),
BRANCH VARCHAR (05),
S_ADDRESS VARCHAR (50),
S_TELNO INT,
UNIQUE (ROLL_NO),
PRIMARY KEY (REG_NO));

Similarly, the following DDL Statements will add new Tables RESULT, EMPLOYEE
and DEPT to the DBMS Catalog.

CREATE TABLE RESULT


(ROLL_NO CHAR (10),
SUB_CODE CHAR (06),
MARKS INT,
CHECK (MARKS BETWEEN 0 AND 100),
PRIMARY KEY (ROLL_NO, SUB-CODE),
FOREIGN KEY (ROLL_NO) REFERENCES STUDENT (ROLL_NO));

CREATE TABLE DEPT


( DEPT_NO INT NOT NULL DEFAULT 1,
DEPT_NAME VARCHAR (30) NOT NULL,
DEPT_HEAD CHAR (8),
TOTAL_SAL INT,
PRIMARY KEY (DEPT_NO),
FOREIGN KEY (DEPT_HEAD) REFERENCES EMPLOYEE (EID));

CREATE TABLE EMPLOYEE


(EID CHAR (8) PRIMARY KEY,
ENAME VARCHAR (25),
DNO INT REFERENCES DEPT (DEPT_NO),
SALARY INT,
CHECK (SALARY BETWEEN 10000 AND 300000);

P S Gill
7

Altering an existing Table

The following DDL statement will add a new attribute STATUS of type INT to the
existing Table EMPLOYEE.

ALTER TABLE EMPLOYEE ADD STATUS INT;

Dropping an Existing Table

The following DDL statement will remove the existing Table RESULT from the DBMS
Catalog.

DROP TABLE RESULT;

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.

CREATE VIEW DEPT_TOTAL_SAL (D_NO, T_SAL)


AS SELECT DEPT_NO, TOTAL_SAL
FROM 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.

CREATE VIEW DEPT_AVG_SAL (D_NO, AVG_SAL)


AS SELECT DNO, AVG (SAL)
FROM EMPLOYEE
GROUP BY DNO;

Dropping an existing View

P S Gill
8

The following statement will remove definition of VIEW named DEPT_TOTAL_SAL


from the DBMS CATALOG.

DROP VIEW DEPT_TOTAL_SAL;

Creating Indexes

Creating a Composite Index

The following statement will create a unique Index on the primary key EID of Table
EMPLOYEE.

CREATE INDEX E_INDX1


ON EMPLOYEE (EID, DNO);

Creating a Unique Index

The following statement will create a unique Index on the primary key EID of Table
EMPLOYEE.

CREATE UNIQUE INDEX E_INDX2


ON EMPLOYEE (EID);

Dropping an Index

DROP INDEX E-INDX1;

Queries & Sub-queries

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.

SELECT DNO, AVG (SALARY) AS AVG_SAL


FROM EMPLOYEE
WHERE DNO > 3
GROUP BY DNO
HAVING COUNT (*) > 10
ORDER BY AVG_SAL DESC;

Query List Employee Names along with the Names of their respective Dept Heads.

SELECT E.ENAME AS EMP_NAME, K.E_NAME AS MGR_NAME

P S Gill
9

FROM EMPLOYEE E, DEPT D, EMPLOYEE K


WHERE E.DNO = D.DEPT_NO AND D.DEPT_HEAD = K.EID;

A Sub-query refers to a nested SELECT Statement as shown below:-

Query Get the name of Employee having highest salary.

SELECT DISTINCT ENAME


FROM EMPLOYEE
WHERE SALARY = ( SELECT MAX (SALARY)
FROM EMPLOYEE);

In the above query ( SELECT MAX (SALARY)


FROM EMPLOYEE) is a nested sub-query.

Aggregate Functions

Query Find Minimum, Maximum and Average Salary of the Employees.

SELECT MIN (SALARY), MAX (SALARY), AVG (SALARY)


FROM EMPLOYEE;

Query Find Average Salary of the Departments having at least 50 employees.

SELECT DNO, AVG (SALARY)


FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT (*) >= 50;

Query Find Average Marks and Total Marks obtained by each Student

SELECT ROLL_NO, AVG (MARKS), SUM (MARKS)


FROM RESULT
GROUP BY ROLL_NO;

Query Find Minimum, Maximum and Average Marks obtained in each Subject.

SELECT MIN (MARKS), MAX (MARKS), AVG (MARKS)


FROM RESULT
GROUP BY SUB_CODE;

Insert, Update & Delete Operations

P S Gill
10

Insert information of a new employee with EID: ‘0013325K’, NAME: ‘VIJAY


KUMAR SHARMA’, DNO: 10 and SALARY: 50000 in the EMPLOYEE Table.

INSERT INTO EMPLOYEE


VALUES (‘0013325K’, ‘VIJAY KUMAR SHARMA’, 10, 50000);

Update the Salary of employee with EID ‘0012240L’ to 55000

UPDATE EMPLOYEE
SET SALARY = 55000
WHERE EID = ‘0012240L’;

Increase the Salary of each employee by 10%.

UPDATE EMPLOYEE
SET SALARY = SALARY * 1.1;

Delete Employee with EID ‘0022343C’ from the EMPLOYEE Table.

DELETE FROM EMPLOYEE


WHERE EID = ‘0022343C’;

JOINS

Query Get the Names of Students, who have appeared for Subject ‘TCS501’

SELECT DISTINCT S_NAME


FROM STUDENT, RESULT
WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO
AND SUB_CODE = ‘TCS501’;

This Query involves a Natural Join of STUDENT and RESULT and in Relational
Algebra it can be written as:-

S_NAME (SUB_CODE = ‘TCS501’ (STUDENT * RESULT))

P S Gill
11

UNION, INTERSECT & MINUS

UNION

Query Get the Names of the Students, who have appeared for subject
‘TCS501’ or for ‘TCS503’ or for both.

(SELECT DISTINCT S_NAME


FROM STUDENT, RESULT
WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO
AND SUB_CODE = ‘TCS501’)

UNION

(SELECT DISTINCT S_NAME


FROM STUDENT, RESULT
WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO
AND SUB_CODE = ‘TCS503’);

This Query is equivalent to Relational Algebra query:-

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’.

(SELECT DISTINCT S_NAME


FROM STUDENT, RESULT
WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO
AND SUB_CODE = ‘TCS501’)

INTERSECT

(SELECT DISTINCT S_NAME


FROM STUDENT, RESULT
WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO
AND SUB_CODE = ‘TCS503’);

This Query is equivalent to Relational Algebra query:-

P S Gill
12

T1  STUDENT * RESULT
S_NAME (SUB_CODE= “TCS501” (T1))  S_NAME (SUB_CODE = “TCS503” (T1))

MINUS (SET DIFFERENCE)

Query Get the Names of the Students, who have appeared for subject
‘TCS501’ but not for ‘TCS503’.

(SELECT DISTINCT S_NAME


FROM STUDENT, RESULT
WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO
AND SUB_CODE = ‘TCS501’)

MINUS

(SELECT DISTINCT S_NAME


FROM STUDENT, RESULT
WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO
AND SUB_CODE = ‘TCS503’);

This Query is equivalent to Relational Algebra query:-

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

Navigating through SQL

DDL

Creation and Alteration of Tables

1. Create Tables to generate the following schema:-

Customer (C_Id, C_Name, C_Street, C_City)


Branch (B_Id, B_Name, B_City)
Account (AN, B_Id, Bal)
Loan (LN, B_Id, Amount)
Depositor (C_Id, AN)
Borrower (C_Id, LN)

CREATE TABLE Customer (C_Id Char(10) PRIMARY KEY,


C_Name Varchar (15) NOT NULL,
C_Street Varchar (15) NOT NULL,
C_City Varchar (15) NOT NULL);

CREATE TABLE Branch ( B_Id Char(10) PRIMARY KEY,


B_Name Varchar (15) NOT NULL,
B_City Varchar (15) NOT NULL);

CREATE TABLE Account ( AN Char(10) PRIMARY KEY,


B_Id Char (10) REFERENCES Branch (B_id),
Bal Number (10,2));

CREATE TABLE Loan ( LN Char(10) PRIMARY KEY,


B_Id Char (10) REFERENCES Branch (B_id),
Amount Number (10,2));

CREATE TABLE Depositor (C_Id Char(10) REFERENCES Customer (C_Id),


AN Char (10) REFERENCES Account (AN),
Primary Key (C_Id, AN));

CREATE TABLE Borrower ( C_Id Char(10) REFERENCES Customer (C_Id),


LN Char (10) REFERENCES Loan (LN),
Primary Key (C_Id, LN));

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);

2. Create Tables on the following schema:-

Supplier (S#, S_Name, S_City)


Part (P#, P_Name)
Project (J#, J_Name, J_City)
Order (S#, P#, J#, Qty)

CREATE TABLE Supplier ( S# Char (10) PRIMARY KEY,


S_Name Varchar (30) NOT NULL,
S_City Varchar (30) NOT NULL);

CREATE TABLE Part ( P# Char (12) PRIMARY KEY,


P_Name Varchar (30) NOT NULL);

CREATE TABLE Project ( J# Char (10) PRIMARY KEY,


J_Name Varchar (30) NOT NULL,
J_City Varchar (30) NOT NULL);

CREATE TABLE Supply_Order ( S# Char (10) REFERENCES Supplier (S#),


P# Char (12) REFERENCES Part (P#),
J# Char (10) REFERENCES Project (J#),
Qty INT NOT NULL,
PRIMARY KEY (S#, P#, J#));

3. Create Tables on the following schema:-

Student (Roll_No, S_Name, S_DOB, S_Address)


Course (C_Code, Title, Credits)
Teacher (T_Code, T_Name, Desig, D_Code)
Department (D_Code, D_Name, HOD)
Offers (T_Code, C_Code, Semester)
Result (Roll_No, C_Code, T_Code, Semester, Marks)

CREATE TABLE Student ( Roll_No Char (10) PRIMARY KEY,


S_Name Varchar (20) NOT NULL,
S_DOB DATE,
S_Address Varchar(30));

CREATE TABLE Course ( C_Code Char(7) PRIMARY KEY,


Title Varchar (20) NOT NULL,

P S Gill
16

Credits INT NOT NULL);

CREATE TABLE Department ( D_Code Char (3) PRIMARY KEY,


D_Name Varchar (20) NOT NULL,
CHECK (D_Code IN (‘CSE’,’IT’,’ECE’,’IC’,’EE’,’ME’,’MT’)),
HOD Varchar (30));

CREATE TABLE Teacher ( T_Code Char(3) PRIMARY KEY,


T_Name Varchar (30) NOT NULL,
Desig Char (10),
D_Code Char (3) REFERENCES Department (D_Code),
CHECK (Desig IN (‘Lect’, ‘Sr Lect’, ‘Asst Prof’, ‘Prof’)));

CREATE TABLE Offers ( T_Code Char(3) REFERENCES Teacher (T_CoDE),


C_Code Char (7) REFERENCES Course (C_Code),
Semester Char(5),
PRIMARY KEY (T_Code, C_Code, Semester),
CHECK (Semester IN (‘Odd’,’Even’)));

CREATE TABLE Result ( Roll_No Char (10) REFERENCES Student (Roll_No),


C_Code Char(7),
T_Code Char(3),
Semester Char (5),
FOREIGN KEY (C_Code, T_Code, Semester)
REFERENCES Offers (C_Code, T_Code, Semester),
MARKS INT,
CHECK (MARKS BETWEEN 0 AND 100));

4. Create Tables on the following schema:-

Emp (E#, E_Name, Salary, D#)


Dept (D#, D_Name, Total_Sal, Mgr#)

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

D# and if we first insert a tuple in Dept, it will attempt to reference a non-


existent tuple in Emp for Mgr#.

The above two problem situations can be handled as follows:-

Step 1: Create the tables without foreign key constraints:-

CREATE TABLE Emp ( E# Char(12) PRIMARY KEY,


E_Name Varchar (30) NOT NULL,
Salary NUMBER (10,2),
D# Char (12));

CREATE TABLE Dept ( D# Char(12) PRIMARY KEY,


D_Name Varchar (30) NOT NULL,
Total_Sal NUMBER (15,2),
Mgr# Char (12));

Step 2: Add foreign key constraints to the above tables:-

ALTER TABLE Emp ADD CONSTRAINT Emp_FK FOREIGN KEY (D#)


REFERENCES Dept (D#) INITIALLY DEFERRED DEFERRABLE;

ALTER TABLE Dept ADD CONSTRAINT Dept_FK FOREIGN KEY (Mgr#)


REFERENCES Emp (E#) INITIALLY DEFERRED DEFERRABLE;

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.

5. Create tables on the following schema:-

Class (Year, Branch, Section, Strength)

Subject (Sub_Code, Title, Credits)

Faculty (Fac_Code, Fac_Name, Dept_Code)

Class_Room (Bldg_No, Room_No, Floor, Capacity)

Time_Slot ( Day, Period)

Time_Table (Year, Branch, Section, Day, Period, Sub_Code, Fac_Code, Bldg_No,


Room_No)

P S Gill
18

The table Time_Table has following candidate keys:-

(Year, Branch, Section, Day, Period) Designated as Primary Key


(Fac_Code, Day, Period)
(Bldg_No, Room_No, Day, Period)

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));

CREATE TABLE Subject ( Sub_Code Char (7) PRIMARY KEY,


Title Varchar (20) NOT NULL,
Credits Int);

CREATE TABLE Faculty ( Fac_Code Char(3) PRIMARY KEY,


Fac_Name Varchar (3) NOT NULL,
Dept Char (4));

CREATE TABLE Class_Room ( Bldg_No Char(4), Room_No INT, Capacity INT,


PRIMARY KEY (Bldg_No, Room_No ));

CREATE TABLE Time_Slot ( Day Char (4), Period INT,


PRIMARY KEY (Day, Period),
CHECK (Day IN (‘Mon’, ’Tue’, ’Wed’, ’Thurs’, ‘Fri’, ‘Sat’)));

CREATE TABLE Time_Table


( Year INT, Branch Char(3), Section INT, Day Char(4), Period INT,
PRIMARY KEY (Day, Period, Year, Branch, Section),
Bldg_No Char(4) NOT NULL, Room_No INT NOT NULL,
Sub_Code Char (7) NOT NULL, Fac_Code Char(3) NOT NULL,
UNIQUE (Day, Period, Bldg_No, Room_No),
FOREIGN KEY (Year, Branch, Section)
REFERENCES Class (Year, Branch, Section),
FOREIGN KEY (Sub_Code) REFERENCES Subject (Sub_Code),
FOREIGN KEY (Fac_Code) REFERENCES Faculty (Fac_Code),
FOREIGN KEY (Bldg_No, Room_No)
REFERENCES Class_Room (Bldg_No, Room_No),
FOREIGN KEY (Day, Period) REFERENCES Time_Slot (Day, Period));

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.

CREATE INDEX Fac_Indx ON Time_Table (Day, Period, Fac_Code);

Dropping of Tables

DROP TABLE Student;

Dropping of Constraints

Drop Constraint Emp_FK;

Dropping of Columns

ALTER TABLE Student DROP Column S_Name;

Dropping of Indices

DROP INDEX Fac_Indx;

How to drop the tables that reference each other?

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:-

Step 1: First drop the constraints Emp_FK and Dept_FK.

DROP CONSTRAINT Emp_FK;


DROP CONSTRAINT Dept_FK;

Step 2:Now drop the tables.

DROP TABLE Emp;


DROP Table Dept;

P S Gill
20

DML

INSERTING INFORMATION INTO TABLES

1. Add a new customer to table Customer with C_Id = ‘C101’, C_Name = ‘Ajay’,
C_Street =’S-26’ and C_City = ‘Noida’.

INSERT INTO Customer VALUES (‘C101’,’Ajay’, ‘S-26’, ‘Noida’);

Entering a NULL value

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).

INSERT INTO Student VALUES (‘091010120’, ‘Vijay’, NULL, ‘S-27 Noida’);

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):-

INSERT INTO Student (S_Name, Roll_No, S_Address) VALUES (‘Vijay’,


(‘091010120’, ‘S-27 Noida’);

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.

RETRIEVING INFORMATION FROM TABLES

3. Get all rows of table Student.

SELECT *
FROM Student;

Restricting rows with a WHERE Clause

P S Gill
21

4. Get the information of those students who are born in 1995.


This query can be expressed in any of the following three forms:-

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’;

Restricting Attributes List

5. Get Roll_No and DOB of all students born before 01st Jan 1995.

SELECT Roll_No, S_DOB


FROM Student
WHERE S_DOB < ’01-JAN-1995’;

Use of Substitution Variables

Previous query can be recalled and re-executed by typing /. Suppose a query is to be


reused with different parameters then parameters can be specified by substitution
variables as follows:-

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.

Retrieving information from more than one tables

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.

SELECT DISTINCT S_Name

P S Gill
22

FROM Result, Student


WHERE Result.Roll_No = Student.Roll_No AND Marks > 90;

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:-

SELECT DISTINCT S_Name


FROM Result R, Student S
WHERE R.Roll_No = S.Roll_No AND Marks > 90;

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.

SELECT C_Name, D.AN


FROM Customer C, Depositor D, Account A, Branch B
WHERE C.C_Id = D.C_Id AND D.AN = A.AN AND A.B_Id = B.B_Id AND
C_City = ‘Noida’ AND B_City = ‘Delhi’ AND Bal > 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

10. SELECT C_Name AS Customer_Name, D.AN AS Account_Number


FROM Customer C, Depositor D
WHERE C.C_Id = D.C_Id;

Here, the Attributes in the resulting table will be named as Customer_Name and
Account_Number.

Using Concatenation in SELECT clause

P S Gill
23

11. SELECT C_Name|| ‘ has an account number ’ || D.AN


FROM Customer C, Depositor D
WHERE C.C_Id = D.C_Id;

Here each tuple output will be as follows:-

Ajay has an account number A101


Vijay has an account number A310

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 E_Id, Basic_Pay+ DA + HRA – Deduction AS Gross_Salary


FROM EMP;

Sorting the results

13. Get information in Result, ordered by Marks in Ascending Order.

SELECT *
FROM Result
ORDER BY Marks;

By default Order By clause will order in Ascending Order.

14. Get information in Result, ordered by Marks in Descending Order.

SELECT *
FROM Result
ORDER BY Marks DESC;

Use of special Attribute ROWNUM

15. Get information of top five employees Salary-wise.

SELECT ROWNUM, E#, E_Name, Salary


FROM ( SELECT E#, E_Name, Salary
FROM Emp
ORDER BY Salary DESC)
WHERE ROWNUM <= 5;

16. Get information of three accounts with highest balance.

P S Gill
24

SELECT ROWNUM, AN, Bal


FROM ( SELECT AN, Bal
FROM Account
ORDER BY Bal DESC)
WHERE ROWNUM <=3;

Performing Aggregate Functions on the data

17. Get Min, Max, Total and Avg Marks in Result.

SELECT MIN (Marks), Max (Marks), SUM (Marks), AVG (Marks)


FROM Result;

Performing Aggregate Functions on grouped rows

18. Get Min Balance, Max Balance and Total Balance at each branch.

SELECT B.B_Id, MIN (Bal), MAX(Bal), SUM(Bal)


FROM Account A, Branch B
WHERE A.B_Id = B.B_Id
GROUP BY B.B_Id;

Restricting the Grouped Information using HAVING clause

19. Get the names and Total Marks of those students who have scored Average Marks
more than 80%.

SELECT S_Name, SUM (Marks)


FROM Student S, Result R
Where S.Roll_No = R.Roll_No
GROUP BY S.Roll_No
HAVING AVG (Marks) > 80;

This will display total marks of each student having average score > 80%.

Outer Join of Tables

20. Perform Left Outer join of tables Depositor & Borrower

SELECT D.C_ID, AN, LN


FROM Depositor D, Borrower B
WHERE D.C_Id = B.C_Id (+);

P S Gill
25

All tuples of Depositor will appear in the result. Wherever, LN is not defined, it
will be indicated by NULL.

21. Perform Right Outer join of tables Depositor & Borrower

SELECT B.C_ID, AN, LN


FROM Depositor D, Borrower B
WHERE D.C_Id (+) = B.C_Id;

All tuples of Borrower will appear in the result. Wherever, AN is not defined, it
will be indicated by NULL.

Nested Queries with Independent sub-queries

22. Get the Customer Id and name of those customers who have both account and
loan from the bank.

SELECT C.C_Id, C_Name


FROM Custmer C, Depositor D
WHERE C.C_Id = D.C_Id AND C_Id IN ( SELECT C_Id
FROM Borrower);

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.

SELECT B.B_Id, B_Name


FROM Account A, Branch B
WHERE A.B_Id = B.B_Id
GROUP BY B.B_Id
HAVING AVG (Bal) = ( SELECT MAX(AVG(Bal))
FROM Account
GROUP BY B_Id);

Nested Queries with Correlated Sub-queries

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

WHERE A.AN = D.AN AND D.C_Id = C.C_Id));


Here the inner query is evaluated for each tuple C of table Customer being processed in
the outer query. The inner sub query produces the set difference of the set of B_Id of
branches in Noida and the set of B_Id where customer C.C_Id has accounts. If this set
produced by the inner sub query is an empty set then the predicate NOT EXISTS of the
outer sub query will be true and the customer name will appear in the result.

Updating of tables

P S Gill
27

26. UPDATE Account


SET Bal = &newbal
WHERE AN = &an;

Deletion of tuples from Tables

26. DELETE Account WHERE AN = &an;

Creation of Views

27. CREATE VIEW AN_BN


AS SELECT AN, B.B_Name
FROM Account A, Branch B
WHERE A.B_Id = B.B_Id;

Retrieving information from Views

28. SELECT B_Name FROM AN_BN;

Dropping of Views

29. DROP VIEW AN_BN;

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.

Structure of a PL/SQL Program

DECLARE

Declarations of Variables & Cursors

BEGIN

PL and SQL statements

EXCEPTION

Exception handlers

END;

Control Constructs Supported by PL/SQL

IF….THEN…END IF;

IF….THEN….ELSE…END IF;

IF….THEN….ELSIF…ELSIF…ELSE…END IF;

LOOP….EXIT WHEN….END LOOP;

WHILE…LOOP….END LOOP;

P S Gill
29

FOR…….LOOP….END LOOP;

GOTO…..;

Print Statement in PL/SQL

DBMS_OUTPUT.PUT_LINE (‘This is the message’);

Some sample programs in PL/SQL

1. Write a program in PL to print squares of numbers up to 99

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;

2. Write a program in PL/SQL to update balance in Account.


SET SERVEROUTPUT ON
DECLARE

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;

3. Write a program in PL/SQL to create a new account in the following


schema.

Customer (C_Id, C_Name, C_Street, C_City)


Branch (B_Id, B_Name, B_City)
Account (AN, B_Id, Bal)
Loan (LN, B_Id, Amount)
Depositor (C_Id, AN)
Borrower (C_Id, LN)

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

A trigger is a set of statements that are executed as a side effect of a


modification to the database, to ensure database integrity. Once, a trigger is
entered into the database, it becomes the responsibility to execute the trigger
whenever due to database modification the specified pre-conditions for the
execution of trigger are satisfied. In a trigger, following needs to be specified:-

(a) Conditions for execution of trigger.


(b) Actions when trigger is executed.

Consider the following schema:-

EMP (E#, E_NAME, SALARY, D#)


DEPT (D_NUMB, D_NAME, TOTAL_SAL)
Where TOTAL-SAL represents the total salary of all employees in a department.

Create a Trigger to automatically update TOTAL_SAL when an employee is


transferred from one Department to another one.

Trigger:

CREATE OR REPLACE TRIGGER adj_sal1 AFTER UPDATE OF D# ON EMP


FOR EACH ROW
BEGIN
IF :OLD.D# IS NOT NULL
THEN
BEGIN
UPDATE DEPT
SET TOTAL_SAL = TOTAL_SAL - :OLD.SALARY
WHERE DEPT.D_NUMB = :OLD.D#;
END;
END IF;

IF :NEW.D# IS NOT NULL

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

A Cursor is a pointer associated with a work area in a PL/SQL program. It has


four phases:-

(i) Declaration of a Cursor:- A cursor is declared associated with a


SQL statement in the DECLARE section of PL/SQL. The general
syntax of declaration is:-

DECLARE
CURSOR cursor-name IS SELECT statement;

At this stage, the SELECT statement is not executed.

(ii) Opening a Cursor:- The general syntax is:-

OPEN cursor-name;

When a cursor is opened, its SELECT statement is executed. The data,


retrieved by the SELECT statement, is brought into the cursor or the work
area. The data stored in the work area is called active data set. The cursor
points to the first row in the active set.

(iii) Fetching Data from a Cursor: A Fetch statement in PL/SQL is


used to fetch the row currently being pointed by the cursor. Its general
syntax is:-
FETCH cursor-name INTO local-variables;

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.

1. Consider the following schema:-

Emp (E#, E_Name, Salary, D#)


Dept (D#, D_Name, Total_Sal, Mgr#)

Write a Cursor to increase the salary by 50%

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

An assertion is a predicate, expressing a condition that must always be satisfied


by the database. The Domain constraint and referential integrity constraint are
special cases of assertions expressing simpler constraints. However, we need to
express complex constraints in the form of assertions. Once, an assertion is
entered, it is checked for its validity and then maintained permanently in the
database till it is modified or deleted. Whenever, database is modified, assertion
is checked for compliance.

1. Consider the following schema:-

EMPLOYEE (E_ID, E_NAME, SALARY, D_NO)


DEPARTMENT (D_NO, D_NAME, MGR_ID)

Create an assertion to impose the constraint that no employee should draw a


salary more than his/her manager, it can be expressed by an Assertion, as
follows:-

CREATE ASSERTION check_max_salary_1 CHECK


(NOT EXISTS ( SELECT *
FROM EMPLOYEE E
WHERE E.SALARY >
(SELECT K.SALARY
FROM DEPARTMENT D, EMPLOYEE K
WHERE D.D_NO = E.D_NO
AND D.MGR_ID = K.E_ID)));

2. Consider the following schema:-

EMP (E#, E_Name, Mgr#, Salary)


Where Mgr# is the E# of Employee’s Manager.

Impose a constraint on the database that no employee should draw a


salary more than its manager.

P S Gill
35

CREATE ASSERTION check_max_salary_2 CHECK


(NOT EXISTS ( SELECT *
FROM EMP E
WHERE E.SALARY >
(SELECT K.SALARY
FROM EMP K
WHERE K.E# = E. Mgr#)));

Referential Integrity Constraints in Database


Modification

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

SOME SOLVED PROBLEMS


Problem 7.1 Let there be Schemas R (A, B, C) & S (D, E, F) and relations r(R) &
s (S). Give expressions in Tuple Relational Calculus (TRC) equivalent to the
following expressions in Relational Algebra (RA).

(a)  A (r)

{ t  u  r ( t[A]= u[A]) }

(b)  B=17 (r)

{ t t r  t[B]= 17 }

(c) r s

{ t  u  r ( t[A]= u[A]  t[B]= u[B]  t[C]= u[C] 


 v  s ( t[D]= v[D]  t[E]= v[E]  t[F]= v[F] )) }

(d)  A,F (C=D (r  s))

{ t  u  r ( t[A]= u[A]   v  s (v[D]= u[C]  t[F]= v[F]))}

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)  B=17 (r1)

{ <a,b,c> <a,b,c>  r1  b = 17 }

P S Gill
37

(c) r1  r2

{ <a,b,c> <a,b,c>  r1  <a,b,c>  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)

{ <a, b, c>  c1 ( <a,b,c1 >  r1   a2 (<a2 ,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)  a   b ( a, b  r  b = 17 ) 

 A ( B=17 (r))

(b)  a, b, c  a, b  r  a, c  s ) 

r*s

Problem 7.4 Consider the schema:- given below,


EMPLOYEE (E-NAME, STREET, CITY)
WORKS-FOR (E-NAME, COMPANY-NAME, SALARY)
COMPANY (COMPANY-NAME, CITY)
MANAGES (E-NAME, MANAGER-NAME)

Express the following queries in relational algebra and SQL:-

(a) Find names of employees working for Infosys.

RA:  E-NAME ( COMPANY-NAME = “Infosys” (works-for))

SQL: SELECT E-NAME


FROM works-for
WHERE COMPAY-NAME = ‘Infosys’;

TRC: { t   u  works-for ( t[E-NAME] = u [E-NAME]  u[COMPANY-NAME] = “Infosys” )}

P S Gill
38

DRC: { < en >   sal ( < en , “Infosys” , sal>  works-for) }

(b) Find the names and the cities of residence of employees working for TCS

RA:  E-NAME, CITY ( COMPANY-NAME = “TCS” (works_for * employee))

SQL: SELECT E.E-NAME, CITY


FROM works-for W, employee E
WHERE W. E-NAME = E. E-NAME AND COMPAY-NAME = ‘TCS’;

TRC: { t   u  works-for ( t[E-NAME] = u [E-NAME]  u[COMPANY-NAME] = “TCS”


  v  employee ( v[E-NAME] = u [E-NAME]  t[CITY] = v [CITY] ))}

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))

SQL: SELECT E.E-NAME, STREET, CITY


FROM works-for W, employee E
WHERE W.E-NAME = E. E-NAME AND COMPAY-NAME = ‘Infosys’
AND SALARY > 20000;

TRC: { t   u  works-for ( t[E-NAME] = u [E-NAME]  u[COMPANY-NAME] = “infosys”


 u[SALARY] > 20000
  v  employee ( v[E-NAME] = u [E-NAME]  t[STREET] = v [STREET] 
t[CITY] = v [CITY] ))}

DRC: { < en, st, city >  < en , st , city>  employee


  salary ( < en , “Infosys” , salary>  works-for  salary > 20000 ) }

(d) Find names of employees working in the same city where they live

RA:  e-name, city (employee * works-for * company)

SQL: SELECT E.E-NAME


FROM works-for W, employee E, company C
WHERE W. E-NAME = E. E-NAME
AND W. COMPANY-NAME = C. COMPAY-NAME
AND E. CITY = C. CITY;

P S Gill
39

TRC: { t   u  employee ( t[E-NAME] = u [E-NAME]


  v  works-for ( v[E-NAME] = u [E-NAME]
  w  company ( w[COMPANY-NAME] = v [COMPANY-NAME]
 w[CITY] = u [CITY] ))) }

DRC: { < en >  st, city ( < en , st , city>  employee


  cn, salary ( < en , cn , salary>  works-for
 < cn, city >  company ))}

(e) Find the names of employees, who are not working for WIPRO

RA:  e-name (employee) -  e-name ( company-name = “Wipro” (works-for))

SQL: SELECT E-NAME


FROM employee
MINUS
SELECT E-NAME
FROM works-for
WHERE COMPANY-NAME = ‘WIPRO’;

TRC: { t   u  employee ( t[E-NAME] = u [E-NAME])


   v  works-for ( t[E-NAME] = v [E-NAME]
 v[COMPANY-NAME] = “WIPRO” )}

DRC: { < en >  st, city ( < en , st , city>  employee )


   sal ( <en, “WIPRO”, sal>  works-for )}

(f) Find the Total and Average Salary Paid by each Company.

RA: Company-Name G MAX (SALARY), AVG (SALARY) (works-for)

SQL: SELECT COMPANY-NAME, SUM (SALARY), AVG (SALARY)


FROM works-for
GROUP BY COMPANY-NAME;

(g) Find the names of employees, who earn more than every employee of
TCS

RA: MAX-TCS  G MAX (SALARY) ( COMPANY-NAME = “TCS” (works-for))


 e-name( SALARY > MAX-TCS (works-for))

SQL: SELECT E-NAME


FROM works-for
WHERE SALARY > ( SELECT MAX (SALARY)

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

RA: emp  employee * manages


 emp.E-NAME ( emp.MANAGER-NAME= mgr.E-NAME  emp.CITY =mgr.CITY  emp.STREET

=mgr.STREET(emp x  mgr(emp)))

SQL: SELECT E.E-NAME


FROM employee E, manages K, employee M
WHERE E. E-NAME = K. E-NAME AND K. MANAGER-NAME = M. E-NAME
AND E. STREET = M. STREET AND E. CITY = M. CITY;

(i) Find the company with maximum number of employees.

RA: r  COMPANY-NAME G COUNT (E-NAME) AS NUMB (works-for)


Max-Numb  G MAX (NUMB) (r)
 COMPANY-NAME ( NUMB = MAX-NUMB (r))

SQL: SELECT COMPANY-NAME


FROM works-for
GROUP BY COMPANY-NAME
HAVING COUNT (E-NAME) = ( SELECT MAX (COUNT (E-NAME))
FROM works-for
GROUP BY COMPANY-NAME);

(j) Find the Company with the smallest total salary paid to employees.

RA: r  COMPANY-NAME G SUM (SALARY) AS TOTAL-SAL (works-for)


MIN-TOTAL  G MIN (TOTAL-SAL) (r)
 COMPANY-NAME ( TOTAL-SAL = MIN-TOTAL (r))

SQL: SELECT COMPANY-NAME


FROM works-for
GROUP BY COMPANY-NAME
HAVING SUM (SALARY) = ( SELECT MIN (SUM (SALARY))
FROM works-for
GROUP BY COMPANY-NAME);

(k) Find the company whose employees earn more salary on the average
than the average salary of TCS.

RA: r  COMPANY-NAME G AVG (SALARY) AS AVG-SAL (works-for)


AVG-TCS   AVG-SAL ( COMPANY-NAME = “TCS” (r))

P S Gill
41

 COMPANY-NAME ( AVG-SAL > AVG-TCS (r))

SQL: SELECT COMPANY-NAME


FROM works-for
GROUP BY COMPANY-NAME
HAVING AVG ( SALARY) >( SELECT AVG (SALARY)
FROM works-for
WHERE COMPANY-NAME = ‘TCS’);

Problem 7.5 Answer the following queries in RA, SQL, TRC and DRC for
the schema given below:-

CUSTOMER (CUSTOMER-NAME, CUSTOMER-STREET, CUSTOMER-CITY)


BRANCH (BRANCH-NAME, BRANCH-CITY, ASSETS)
ACCOUNT (ACCOUNT-NUMBER, BRANCH-NAME, BALANCE)
LOAN (LOAN-NUMBER, BRANCH-NAME, AMOUNT)
DEPOSITOR (CUSTOMER-NAME, ACCOUNT-NUMBER)
BORROWER (CUSTOMER-NAME, LOAN-NUMBER)

(a) Find the names & cities of customers having a loan from the bank.

RA:  CUSTOMER-NAME, CUSTOMER-CITY (customer * borrower)

SQL: SELECT C. CUSTOMER-NAME, CUSTMER-CITY


FROM customer C, borrower B
WHERE C. CUSTOMER-NAME = B. CUSTMER-NAME;

TRC: { t   u  customer ( t[CUSTOMER-NAME] = u [CUSTOMER-NAME] 


t[CUSTOMER-CITY] = u [CUSTOMER-CITY]
 v  borrower ( v[CUSTOMER-NAME] = u [CUSTMER-NAME] )) }

DRC: { < cn , cc >   cs ( < cn , cs , cc>  customer   ln ( < cn , ln > 


borrower )) }

(b) Find names of customers having account in all branches of “Noida”

RA:  CUSTOMER-NAME, BRANCH-NAME (depositor * account) BRANCH-NAME( BRANCH-CITY=”Noida” (branch))

SQL: SELECT D. CUSTOMER-NAME


FROM depositor D
WHERE NOT EXISTS
(( SELECT BRANCH-NAME
FROM branch
WHERE BRANCH-CITY = ‘NOIDA’)
MINUS
(SELECT A.BRANCH-NAME
FROM depositor K, account A
WHERE K.CUSTOMER_NAME = D.CUSTOMER_NAME
AND K.ACCOUNT_NUMBER = A.ACCOUNT_NUMBER));

P S Gill
42

(c) Find Average Balance at each branch

RA: BRANCH-NAME G AVG (BALANCE) AS AVG-BAL (account)

SQL: SELECT BRANCH-NAME, AVG (BALANCE)


FROM account
GROUP BY BRANCH-NAME;

(d) Find the accounts held by more than two customers.

RA: r ACCOUNT-NUMBER G COUNT DISTINCT (CUSTOMER-NAME) AS NO-OF-CUST (depositor)


 ACCOUNT-NUMBER ( NO-OF-CUST > 2 (r))

SQL: SELECT ACCOUNT-NUMBER


FROM depositor
GROUP BY ACCOUNT-NUMBER
HAVING COUNT(CUSTOMER-NAME) > 2;

Problem 7.6 Consider the schema shown in Problem # 4 and give relational
algebra expressions for the following:-

(a) Modify database so that Ajay now lives in Mumbai


RA: r   E-NAME = “Ajay” (employee)
employee  (employee – r)   E-NEME, STREET, CITY = “Mumbai” (r)
SQL: UPDATE employee
SET CITY = ‘Mumbai’
WHERE E-NAME = ‘Ajay’;
(b) Give all employees of TCS a 10% rise in salary
RA: r   COMPANY-NAME = “ TCS” (works-for)
works-for  (works-for – r)   E-NEME, COMPANY-NAME, SALARY*1.1 (r)

SQL: UPDATE works-for


SET SALARY = SALARY * 1.1
WHERE COMPANY-NAME = ‘TCS’;

(c) Give all managers a 10% rise in salary


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 (r)
SQL: UPDATE works-for
SET SALARY = SALARY * 1.1
WHERE E-Name in (SELECT MANAGER_NAME
FROM manages );

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))

SQL: UPDATE works-for


SET SALARY = CASE
WHEN SALARY >= 10000 THEN SALARY * 1.03
ELSE SALARY * 1.1
END
WHERE E-NAME IN ( SELECT MANAGER-NAME
FROM manages);

(e) Delete all tuples of works-for for employees working for TCS
RA: works-for  works-for –  company-name= “TCS” (works-for)

SQL: DELETE works-for


WHERE COMPANY-NAME = ‘TCS’;

(f) Find the company with max number of employees amongst all the
companies.

RA: r COMPANY-NAME G COUNT (E-NAME) AS NO-OF-EMP (works-for)


Max-Emp  G MAX (NO-OF-EMP) (r)
 COMPANY-NAME ( NO-OF-EMP = Max-Emp (r))

SQL: SELECT COMPANY-NAME


FROM works-for
GROUP BY COMPANY-NAME
HAVING COUNT (E-NAME) >= ALL (SELECT COUNT (E-NAME)
FROM works-for
GROUP BY COMPANY-NAME);

(g) Find the company with the smallest pay-roll.

RA: r COMPANY-NAME G SUM (SALARY) AS TOTAL-SAL (works-for)


Min-Sal  G MIN (TOTAL-SAL) (r)
 COMPANY-NAME ( TOTAL-SAL= Min-Sal (r))

P S Gill
44

SQL: SELECT COMPANY-NAME


FROM works-for
GROUP BY COMPANY-NAME
HAVING SUM (SALARY) <= ALL (SELECT SUM( SALARY)
FROM works-for
GROUP BY COMPANY-NAME);

(h) Find the company, whose employees earn more salary, on the
average, than the average salary of TCS employees.

RA: r COMPANY-NAME G AVG (SALARY) AS AVG-SAL (works-for)


Avg-TCS   AVG-SAL ( COMPANY-NAME =”TCS” (r))
 COMPANY-NAME ( AVG-SAL > Avg-TCS (r))

SQL: SELECT COMPANY-NAME


FROM works-for
GROUP BY COMPANY-NAME
HAVING AVG (SALARY) > (SELECT AVG ( SALARY)
FROM works-for
WHERE COMPANY-NAME = ‘TCS’ );

Problem 7.7 Consider the following schema:-

STUDENT (Roll_No, S_Name, S_Address, S_Age)


DEPTT (D_Name, Sub_Code, Faculty)
Time_Table (Sub_Code, Sub_Name, Semester, Time, Room_No)
Performance (Roll_No, Sub_Code, Grade)

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))

TRC: { t   u  student ( t[S-NAME] = u [S-NAME]


 v  performance ( v[ROLL-NO] = u [ROLL_NO]  v[GRADE] = “A”
 w  deptt ( w[SUB-CODE] = v [SUB-CODE]  w[D-NAME] = “Comp-Sc”
 x  time-table ( x[SUB-CODE] = w [SUB-CODE]  x[SEMESTER] =
“Autumn” )))) }

P S Gill
45

DRC: { <s-name>   roll-no, s-address, s-age ( <roll-no, s-name, s-address, s-age> 


student   sub-code, grade ( <roll-no, sub-code, grade>  student  grade = “A”
  d-name, faculty( <d-name, sub-code, faculty>  deptt  d-name = “Comp-Sc”
  sub-name, semester, time, room-no ( <sub-code, sub-name, semester, time,
room-no>  time-table  semester = “Autumn” )))) }

SQL: SELECT S-NAME


FROM student S, performance P, deptt D, time-table T
WHERE S.ROLL-NO = P.ROLL-NO AND P.SUB-CODE = D.SUB-CODE
AND D.SUB-CODE = T.SUB-CODE AND GRADE = ‘A’ AND
D-NAME = ‘Comp-Sc’ AND SEMESTER = ‘Autumn’ ;

Problem 7.8 Consider the following schema:-

PROJECT (Proj#, Proj_Name, Chief_Architect)


EMP (Emp#, Emp_Name)
Assigned_To (Emp#, Proj#)

Write following Queries in RA, TRC, DRC & SQL:-

(a) Get Emp# of employees working on project no. Comp-101


RA:  EMP-# ( PROJ# = “Comp-101” (assigned-to))

TRC: { t  u  assigned-to ( t[EMP#] = u [EMP#]  u[PROJ#] = “Comp-101” ) }

DRC: {<emp#> | proj# ( <emp#, proj#>  assigned-to  proj# = “Comp-


101” ) }

SQL: SELECT EMP#


FROM assigned-to
WHERE PROJ# = ‘Comp-101’;

(b) Get details (Emp#, Emp_Name) of employees working on project no


Comp-201
RA:  EMP-#, EMP-NAME ( PROJ# = “Comp-201” ( emp * assigned-to))

TRC: { t  t  emp   u  assigned-to ( t[EMP#] = u [EMP#]


 u[PROJ#] = “Comp-201” )}

DRC: { <emp#, emp-name>  <emp#, emp-name>  emp 


 proj# ( <emp#, proj#>  assigned-to  proj# = “Comp-201” ) }

SQL: SELECT emp.EMP#, EMP-NAME


FROM emp, assigned-to
WHERE emp.EMP# = assigned-to.EMP# AND PROJ# = ‘Comp-201’;

P S Gill
46

(c) Get Emp# of employees working on all the projects

RA: assigned-to   PROJ# (project)

TRC: { t   u  project   v  assigned-to ( v[PROJ#] = u [PROJ#]


 t[EMP#] = v[EMP#] )}

DRC: { <emp#>  proj#, proj-name, chief-architect (<proj#, proj-name,


chief-architect>  project  <emp#, proj#>  assigned-to)}

SQL: SELECT R.EMP#


FROM assigned-to R
WHERE NOT EXISTS (( SELECT PROJ#
FROM project)
MINUS
( SELECT PROJ#
FROM assigned-to S
WHERE S.EMP# = R.EMP# ));

Problem 7.9Consider the following schema:-

SUPPLIER (S#, S_Name, S_City)


PART (P#, P_Name, Pcolor, Pweight)
PROJECT (J#, J_Name, J_City)
SPJ (S#, P#, J#, Qty)

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))

TRC: { t   u  project (u[JCITY] = “London”   v  spj ( v[J#] = u [J#]


 t[P#] = v[P#] ))}

DRC: { <p#>  j#, j-name, j-city ((<j#, j-name, j-city>  project  jcity =
“London”)   s#, qty (<s#, p#, j#, qty >  spj))}

SQL: SELECT P.P#


FROM Part P
WHERE NOT EXISTS (( SELECT J#
FROM project
WHERE JCITY = ‘London’ )
MINUS
( SELECT J#
FROM spj R

P S Gill
47

WHERE R.P# = P.P# ));

Problem 7.10 Consider the following schema:-

STUDENT (S#, S_Name)


COURSE (C#, Title, Teacher)
RESULT (S#, C#, Marks)
Assume a Course is offered only by one Teacher, but a teacher may be offering
many courses.

Write the following Queries in RA, TRC, DRC & SQL:-

(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)

TRC: { t   u  course (u[TEACHER] = “Rinkaj” 


 v  result ( v[C#] = u [C#]  v[MARKS]  60 
 w  student ( w[S#] = v [S#]  t[S-NAME]  w[S-NAME] )))}

DRC: { <s-name>  c#, title, teacher ((<c#, title, teacher>  course  teacher =
‘Rinkaj” )   s#, marks (<s#, c#, marks>  result  marks > 60 
<s#, s-name>  student)))}

SQL: SELECT S.S-NAME


FROM student S
WHERE NOT EXISTS (( SELECT C#
FROM course
WHERE TEACHER = ‘Rinkaj’ )
MINUS
( SELECT C#
FROM result K
WHERE K.S# = S.S# AND MARKS > 60 ));

(b) List the Subject Titles having max failures (Pass Marks = 40)

RA: r C#G COUNT (S#) AS NO-FAIL (result)


Max-Fail  G MAX (NO-FAIL) (r)
 TITLE ( NO-FAIL= Max-Fail (r)) * course)

TRC: Not feasible

DRC: Not feasible

P S Gill
48

SQL: SELECT C.TITLE


FROM result R, course C
WHERE R.C# = C.C# AND MARKS < 40
GROUP BY C.C#
HAVING COUNT (S#) = (SELECT MAX (COUNT (S#))
FROM result
WHERE MARKS < 40
GROUP BY C# );

Problem 7.11 Consider the following schema:-

PHYSICIAN (Reg_No, Name, Addr, Phone_No)


PATIENT (Pt_Name, Pt_Addr)
VISITS (Reg_No, Pt_Name, Date_Of_Visit)

Write the following Queries in RA, TRC, DRC & SQL:-

(a) List Names & Phone Numbers of Physicians, who have been
visited by at least one patient.

RA:  NAME, PHONE-NO (physician * visits)

TRC: { t   u  physician (t[NAME] = u[NAME]  t[PHONE-NO] = u[PHONE-NO] 


 v  visits (v[REG-NO] = u[REG-NO] )) }

DRC: { <name, phone-no>   reg-no, addr (<reg-no, name, addr, phone-no> 


physician   pt-name, date-of-visit (<reg-no, pt-name, date-of-visit>  visits)) }

SQL: SELECT NAME, PHONE-NO


FROM physician, visits
WHERE physician. REG-NO = visits. REG-NO;

(a) List the Name & Address of patients, who visited more than one
physician in May 2003

RA: r   REG-NO, PT-NAME (  DOV  01-MAY-2003  DOV <= 31-MAY-2003 (visits))


r1   r. PT-NAME (  r. PT-NAME, = temp. PT-NAME  r. REG-NO  temp . REG-NO (r x  temp (r)) )
r1 * patient

TRC: { t   u  patient ( t[PT-NAME] = u [PT-NAME]  t[PT-ADDR] = u[PT-ADDR]


 v  visits ( v[PT-NAME] = u [PT-NAME]  v[DOV] > 01-MAY-2003
 v[DOV] < 31-MAY-2003
 w  visits ( w[PT-NAME] = u [PT-NAME]  w[DOV] > 01-MAY-2003
 w[DOV] < 31-MAY-2003  w[REG-NO]  v [REG_NO] ))) }

DRC: { <pt-name, pt-addr>  <pt-name, pt-addr>  patient


  reg1, dov1 ( <reg1, pt-name, dov1>  visits  dov1 > 01-MAY-2003 

P S Gill
49

dov1 < 31-MAY-2003


  reg2, dov2 ( <reg2, pt-name, dov2>  visits  dov2 > 01-MAY-2003 
dov2 < 31-MAY-2003  reg1  reg2 ))) }

SQL: SELECT P. PT-NAME, PT-ADDR


FROM patient P, visits V, visits T
WHERE P. PT-NAME = V. PT-NAME AND P.PT-NAME= T. PT-NAME
AND V. DATE-OF-VISIT LIKE ‘%-MAY-2003’
AND T. DATE-OF-VISIT LIKE ‘%-MAY-2003’
AND V.REG-NO <> T.REG-NO;

Problem 7.12 Consider the following schema:-

EMP (Emp_No, Emp_Name, Salary, Dept_No)


DEPT (Dept_No, Dept_Name, Mgr_No)

Where Mgr_No is Emp_No of Manager.

Write the following Queries in RA, TRC, DRC & SQL:-

(a) List Employee Name & his/her Manager Name

RA: r   EMP-NO, EMP-NAME, MGR-NO ( emp * deptt)


 r. EMP-NAME , mgr. EMP-NAME ( r. MGR_NO = mgr. EMP-NO ( r x  mgr (r) ) )

TRC: { t   u  deptt  v  emp ( v[DEPT-NO] = u [DEPT-NO]


 t[EMP-NAME] = u [EMP-NAME]
 w  emp ( w[EMP-NO] = u [MGR-NO]  t[MGR-NAME] = w[EMP-NAME] )) }

DRC: { <emp-name, mgr-name>   dept-no, dept-name, mgr-no ( <dept-no, dept-name, mgr-


no>  dept   emp1, salary1 ( <emp1, emp-name, salary1, dept-no>  emp
  emp2, salary2, dpn( <emp2, mgr-name, salary2, dpn>  emp  emp2 = mgr-no )))}

SQL: SELECT E. EMP-NAME, M. EMP-NAME


FROM emp E, deptt D, emp M
WHERE E . DEPT-NO = D. DEPT-NO AND D.MGR-NO = M.EMP-NO ;

(b) List Dept_No with its Total, Max, Min & Average Salary

RA: DEPT-NOG SUM (SALARY), MAX (SALARY), MIN (SALARY), AVG (SALARY) (emp)

TRC: Not feasible

DRC: Not feasible

SQL: SELECT DEPT-NO, SUM (SALARY), MAX (SALARY)

P S Gill
50

MIN (SALARY), AVG (SALARY)


FROM emp
GROUP BY DEPT-NO;

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)  A ( r – s) &  A ( r ) -  A (s)


A ( r – s)
A
1
2
3

 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

(c) r   B (s) & s   B (r)


r   B (s)
A
2

s   B (r) =
A

(d) A GAVG (B) (r) & B GAVG (A) (r)


A GAVG (B) (r)
A AVG (B)
1 17/3
2 4
3 2

B GAVG (A) (r)


B AVG (A)
12 1
3 2
2 1
5 2

Exercises

P S Gill
52

Ex. 7.1 Consider the following Schema:-

Project (Project_No, Project_Name, Project_Manager)


Employee( Employee_No, Employee_Name)
Assigned_To (Project_No, Employee_No)

(i) Write SQL-DDL Statements to implement the database. The SQL


Statements should clearly indicate the Primary Keys & Foreign
Keys.

(ii) Write following queries in Relational Algebra & SQL:-

(a) Get the details of the employees working on both projects ‘P1’
and ‘P2’.

(b) Get names of employees working on ‘P1’ but not on ‘P2’.

(c) Delete the record of an employee with Employee_No ‘E1’.

(d) List the names of the employees who are working on a project
whose manager is ‘E1’.

Ex.7.2 Consider the following Schema:-

Dealer (Dealer_Id, Dealer_name, Dealer_address)


Part (Part_Id, Part_Name, Color)
Catalog (Dealer_Id, Part_Id, Cost)

Write the following queries in Relational Algebra and SQL:-

(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.

Ex.7.3 Consider the following Vehicle Insurance Schema:-

Person (Deriver_Id, Name, Address)


Car (License, Model, Year)
Accident (Report_Number, Date, Location)
Owns (Driver_Id, License)
Participated (Driver_Id, License, Report_Number, Damage_Amount)

P S Gill
53

Construct the following queries in SQL:-

(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.

(iii) Add a new Accident to the database with Report_Number =


‘AR101’, Date = ’10-Apr-2006’ and Location =’Noida’.

(iv) Delete the car Model ‘Santro’ belonging to ‘Mr Vijay’.

(v) Update the Damage_Amount for car with License ‘HR3000’ and
Report Number = ‘AR1000’ to Rs 35000.

Ex.7.4 Consider the following schema:-

S (S#, Sname, Scity, Turnover)


P (P#, Pweight, Pcolor, Cost, Selling_Price)
SP (S#, P#, Qty)

Write the following queries in Relational Algebra and SQL:-

(I) Get the details of the suppliers who operate from ‘Delhi’ with
Turnover 5000000.

(ii) Get the part numbers weighing between 25 and 50.

(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.

Ex.7.5 Consider the following schema:-

Employee (Employee_Name, Street, City)


Works (Employee_Name, Company_Name, Salary)
Company (Company_Name, City)
Manages( Employee_Name, Manager_Name)

P S Gill
54

(a) Give SQL-DDL definitions of the schema. Identify Referential


Integrity Constraints that should hold and include them in the
definition.

(b) Write following queries in Relational Algebra & SQL:-

(i) Find all the employees who work under manager ‘Vijay’.

(ii) Find cities of residence of the employees working under


manager ‘Ajay’.

(iii) Find all pairs of employees who have a manager in common.

(iv) Find the Company that has smallest payroll.

(v) Find all employees who earn more than the average salary
of their company.

P S Gill

You might also like