18CSL58 - DBMS Lab Manual 2018 Scheme - KKS
18CSL58 - DBMS Lab Manual 2018 Scheme - KKS
18CSL58 - DBMS Lab Manual 2018 Scheme - KKS
LAB MANUAL
Programme : B.E
Prepared by:
Krupa K S
Assistant Professor
Dept. of ISE
TABLE OF CONTENTS
Sl. No. PARTICULARS Page No.
COURSE DETAILS
Course Objectives
4 6
Syllabus
Course Outcomes
5 Evaluation Process 11
7 Introduction 12
M3. Inculcate ethical values and environmental consciousness through holistic education
programs
VISION
To excel in teaching and research in the field of Information Science and Engineering to
meet emerging challenges of society
MISSION
M1: To inculcate strong academic foundation in the Information Technology domain
for successful career and lifelong learning.
M2: To strengthen research and development activities through interaction with industry.
M3: To instill professional ethics and social values with concern for environment.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader in a
team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
PSO2. Understand and analyze the system architecture, organization of computer communication
systems.
COURSE DETAILS
COURSE OBJECTIVES
This course will enable students to,
SYLLABUS
IA Marks : 40 Module Name : Information Retrieval
Subject Code : 18CSL58
and Networking
No. of Practical Hrs/ Week : 03 Exam Hours : 03 Module Coordinator: Jyoti Neeli
Exam Marks : 60 Course Coordinator: Krupa K S
Total No. of Practical Hrs : 40
Create Schema and insert at least 5 records for each table. Add appropriate database constraints.
Lab Experiments
Part A: SQL Programming
4. Calculate the FinalIA (average of best two test marks) and update the corresponding table for
all students.
5. Categorize students based on the following criterion:
If FinalIA = 17 to 20 then CAT = ‘Outstanding’
If FinalIA = 12 to 16 then CAT = ‘Average’
If FinalIA< 12 then CAT = ‘Weak’
Give these details only for 8th semester A, B, and C section students.
Make sure that the application should have five or more tables, at least one trigger and one stored
procedure, using suitable frontend tool.
Indicative areas include; health care, education, industry, transport, supply chain, etc.
COURSE OUTCOMES
CO – PO MAPPING
18CSL58.1 3 3 3 - - - - - 3 - - 2 3 - - 1
18CSL58.2 3 3 3 - 3 - - - 3 3 - 2 3 - - 1
3 3 3 - 3 - - - 3 3 - 2 3 - - 1
18CSL58.3
3
18CSL58.4 3 3 3 - 3 - - - 3 3 - 2 - - 1
18CSL58
3 3 3 - 3 - - - 3 2.75 - 2 3 - - 1
(AVG)
2 Record 10
TOTAL 20
2 Conduction 28
3 Viva Voce 6
TOTAL 40
2 Mini Project 16
CHAPTER 1 : INTRODUCTION
1.1 Introduction to ORACLE - RDBMS
Oracle is the first true relational database management systems developed by Oracle Corporation Inc.
(USA). This powerful RDBMS package is available in most of the popular software platforms like DOS,
Windows NT, Netware etc. It is portable, compatible and connectable with variety of front-ends.
Oracle is the most powerful RDBMs server which supports the front-ends like Visual Basic, Power
Builder, etc., using ODBC (Open Data Base Connectivity)
Advantages:
The database structure is easy to understand
It can be used to CREATE multiple relationship BETWEEN the tables.
Any sort of query can be applied easily using SQL.
The forms and tables can be easily visualized.
The SQL*plus provides the develops with direct interface, enable them to manipulate the
database directly.
Features of Oracle
Large database support
Data concurrence
Industry accepted standards
Portability
Enforced Integrity
Data security
Support for client/Server environment
Oracle Server
Oracle is the name of a database management system developed by Oracle Corporation. Oracle
server manages data in the database. Users access oracle server using SQL commands. So Oracle
Server receives SQL commands FROM users and executes them on the database.
Users of Oracle database use logical view of the data. Users are not aware of how the data is
actually stored on the disk by oracle Server. Users view the total data as a collection of tables
WHERE each table contains row and columns. That means physical structure of the database is
hidden FROM users. A user can access data without anything about the physical structure of the
data.
Personal Oracle
Client Application
In this Oracle Server and client both run on the same machine.
Oracle Server
Database
Introduction to SQL
SQL stands for Structured Query Language.SQL is a language that enables you to work with a database.
Using SQL, you can insert records, update records, and delete records. You can also CREATE new
database objects such as databases and tables. And you can drop (delete) them.
Although SQL is an ANSI (American National Standards Institute) standard, there are many different
versions of SQL. Different database vendors have their own variations of the language. Some common
relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server,
Access, Ingres, etc. Although most database systems use SQL, most of them also have their own
additional proprietary extensions that are usually only used on their system. However, the standard SQL
commands such as "SELECT", "Insert", "Update", "Delete", "CREATE", and "Drop" can be used to
accomplish almost everything that one needs to do with a database.
SQL is usually provided in two modes – interactive and embedded SQL.
Interactive SQL is used to operate directly on a database. The response to any SQL command can be
seen almost immediately on the same terminal. Embedded SQL consists of SQL commands used within
programs written in some other language like C, ASP, JSP, VB or Pascal.
Advantages of SQL
SQL is widely used on most RDBMS products. This means that end-users will not have a
major problem shifting FROM one RDBMS to the other.
Applications written in SQL can easily be ported across system.
SQL is independent of its internal implementation. The user will not have to bother about
how SQL goes about its job as long as results are consistent.
Even though SQL has been designed to be very simple and easy to learn, it can cope with
complex situation.
SQL is set oriented rather than record oriented. This allows a user to access entire sets of
data within a single command rather than accessing one record at a time.
Objectives:
Learn SELECT statement with important clauses.
Basic Query Block:
The SELECT statement is used to retrieve data stored in database tables and views. The data returned
by the SELECT statement is called a query result.
Syntax:
SELECT column_name,column_name,…. FROM table_name;
Table structure:
To see the schema of the table, the command is
DESCribe <tablename>;
DESC employees;
Column Aliases
Column alias give an alternative heading on output. Specify the alias after the column in the SELECT
list. By default, alias headings cannot contain blank spaces, unless the alias is enclosed in double
quotes(“ “).
SELECT employee_id,first_name employeename,salary FROM employees;
Concatenation operator
The concatenation operator (||) is used to link columns to other columns, arithmetic expressions or
literals to CREATE a character expression. Columns on either side of the operator are combined to
make one single column
SELECT first_name||last_name FROM employees;
If column taking part in an expression contains null, the result of that expression evaluates to null. To
produce the correct result, convert null values to zero by using an NVL function.
Note: Both distinct and ORDER BY clauses cannot be used with SELECT statement.
Syntax is :
SELECT column list FROM table name WHERE condition;
SELECT first_name,first_name,job_id FROM employees WHERE job_id='AD_VP';
Negating expressions
The following operators are used in negating expressions:
Operator Explanation
!= Not equal to
<> Not equal to
Not column name= Not equal to
Not BETWEEN Not BETWEEN two given values
Not in Not in given list of values
Not like Not matching pattern
Is not null Is not a null value
Compound conditions
The AND and OR operators may be used to make compound logical expressions.
The AND operator expects both conditions to be TRUE whereas the OR operator expects either
condition to be true.
Ex: To find all IT programmers who earn BETWEEN 4000 and 6000
SELECT job_id,salary FROM employees WHERE salary BETWEEN 4000 and 6000 and
job_id='IT_PROG'
Ex: To find all employees who are either IT programmers or all employees who earn BETWEEN
4000 and 6000
SELECT job_id,salary FROM employees WHERE salary BETWEEN 4000 and 6000 or
job_id='IT_PROG';
PRACTICE EXERCISES:
1. List the names of employees in the order of their date of joining.
2. Display all the job types
3. List following details of employees of department number 20 and 30 in alphabetic order of
names.
4. List all employees that have LA or LL in them.
5. Display names of all employees who joined in 1982.
6. Display the name and total remuneration for all employees.
7. Observe the structure of the following tables and write their schemas
a) employess b) Departments c) jobgrades
SELECT all information FROM the above tables
Objectives:
CREATE table structures
Understand the importance of integrity CONSTRAINTs.
Incorporate integrity CONSTRAINTs in table structures
Modify table structures
Delete table structures
Rename tables
Tables
In relational database systems (DBS) data are represented using tables (relations). A query issued against
the DBS also results in a table. A table has the following structure:
A table is uniquely identified by its name and consists of rows with each row containing exactly
one tuple (or record). A table can have one or more columns.A column is made up of a column name and
a data type, and it DESCribes an attribute of the tuple. The structure of a table, also called relation
schema, thus is defined by its attributes.
The type of information to be stored in a table is defined by the data types of the attributes at table
creation time.
SQL uses the terms table, row, and column for relation, tuple, and attribute, respectively
CREATE Table Syntax
The CREATE TABLE statement is used to CREATE a table in a database.
SQL CREATE TABLE Syntax
Data Types
Each column contains the datatype and size. Datatype of the column specifies what type of data can be
stored in a column.
A table can have up to 254 columns which may have different or same data types and sets of values
(domains), respectively. Possible domains are alphanumeric data (strings), numbers and date formats.
Oracle offers the following basic data types:
• char(n): Fixed-length character data (string), n characters long. The maximum size for
n is 255 bytes (2000 in Oracle8). Note that a string of type char is always padded on
right with blanks to full length of n. (+ can be memory consuming).
Example: char(40)
• varchar2(n): Variable-length character string. The maximum size for n is 2000 (4000 in
Oracle8). Only the bytes used for a string require storage. Example: varchar2(80)
• number(o, d): Numeric data type for integers and reals. o = overall number of digits, d
= number of digits to the right of the decimal point.
Maximum values: o =38, d= −84 to +127. Examples: number(8), number(5,2)
Note that, e.g., number(5,2) cannot contain anything larger than 999.99 without resulting
in an error. Data types derived FROM number are int[eger], dec[imal], smallint
and real.
• date: Date data type for storing date and time.
The default format for a date is: DD-MMM-YY. Examples: ’13-OCT-94’, ’07-JAN-98’
• long: Character data up to a length of 2GB. Only one long column is allowed per table.
Constraints
The definition of a table may include the specification of integrity CONSTRAINTs.
Integrity constraints help you to enforce business rules on data in your database. Once you specify an
integrity CONSTRAINT for a table, all data in the table always conforms to the rule specified by
integrity constraints.
Types of Integrity Constraints
Oracle provides the two types of integrity constraints:
Entity Integrity CONSTRAINT: These constraints ensure that each row in a table is unique or is
according to predefined rule. They enforce the business rules on the rows of a single table for which they
are specified.
Referential integrity CONSTRAINT: These constraints ensure that the values in a column of a table
match the values in a related column of another table. They enforce the business rules across more than
one table in a database.
Both entity and referential integrity constraints can be specified using CREATE TABLE or
ALTER TABLE command.
2. Not Null Integrity CONSTRAINT: If there is a column that must contain a value for all rows, the not
null integrity CONSTRAINT is used for that column.
Syntax:
CREATE table table_name
( column_name datatype(size) [default default_value][not null],….);
Ex: empno number(4) not null
3.Unique CONSTRAINT: When you want that a column or a set of columns should contain unique
values, you need to define the unique integrity CONSTRAINT for these columns. No two rows can have
the same values for the columns to which unique CONSTRAINT is attached. You can have the null
values if the unique key is based on a single column.
Syntax for column CONSTRAINT is:
CREATE table table_name(
Column_name datatype(size) [CONSTRAINT CONSTRAINT_name] [unique],…);
Syntax for table CONSTRAINT is:
CREATE table table_name(
Column_name datatype(size),….
[CONSTRAINT CONSTRAINT_name unique(column_name)]);
Ex: CREATE table empmas
(empno number(4),
Firstname varchar2(15),
secondname varchar2(15),
lastname varchar2(15),…..,
CONSTRAINT con_unq_name unique(firstname,secondname,lastname));
4.Check CONSTRAINT: is used to enforce rules that can be evaluated using logical expressions.
Syntax for column CONSTRAINT is
CREATE table table_name(
Column_name datatype(size) [CONSTRAINT CONSTRAINT_name] check(condition),….)
Syntax for table CONSTRAINT is:
2. FOREIGN KEY CONSTRAINT: A FOREIGN KEY is used in a relationship with either a primary
or unique key of the same table or another table.
Syntax for column CONSTRAINT is
CREATE table table_name(
Example: A complete example of creating Emp table using various integrity constraints is given below:
CREATE table emp
( empno number(4) CONSTRAINT con_pk_eno PRIMARY KEY,
ename varchar2(10) CONSTRAINT con_check_upper check(upper(ename)),
job varchar2(10),
mgr number(4) CONSTRAINT con_fk_mgr REFERENCES(empno),
hiredate date,
sal number(7,2),
PRACTICE EXERCISES:
1. CREATE the following tables(include the appropriate referential integrity CONSTRAINT)
Sailors(sid:integer, sname:string, rating:integer, age:real)
Boats(bid:integer,bname:string,color:string)
Reserves(sid:integer,bid:integer;day:date)
Note : Underlined column specifies that it is the key of the table.
DROP Clause
The DROP clause of Alter table is used to remove a CONSTRAINT FROM a table.
Syntax is:
Alter table <table_name>
Drop [CONSTRAINT]CONSTRAINT_name
[PRIMARY KEY]
[unique(column,column,..)]
[cascade]
Ex: Alter table emp drop CONSTRAINT con_nnull;
Cascade Option:
The cascade option of Drop clause removes dependent CONSTRAINTs.
For example, when we drop the PRIMARY KEY of DEPT table using CASCADE option the FOREIGN
KEY CONSTRAINT in the EMP table will be dropped automatically..
Ex: Alter table dept drop PRIMARY KEY cascade;
Inserting Data
Inserting a single row: Syntax is
Insert into <table_name>[(column_name,column_name,…)]
Values(value,value,…)
Ex: Insert into emp (empno,ename,job,mgr,hiredate,sal,comm.,deptno)
values(8888,’sam’,’analyst’,7566,sysdate,2900,null,20);
Note:
1) Date and character columns are required to be enclosed in single quotes.
2) One insert command adds one row to a table unless a subquery is used.
3)We can use substitution variables to insert rows.
Ex(substitution variable):
Insert into emp(empno,ename,job,deptno) values(&eno,’&ename’,’&job’,&dno);
Inserting multiple rows:
The syntax of multiple row insert statement is:
Insert into <table_name>[(column_name,column_name,…)]
SELECT statement
Ex: Insert into emphistory(empno,ename,job,deptno)
SELECT empno,ename,job,deptno
FROM emp WHERE hiredate>’1-JAN-82’;
Updating Data:
The UPDATE statement is used to modify one or more rows in a table.
Syntax of the update statement is:
Update <table_name> set column[,column..]={constant/NULL} [WHERE condition]
Updating a single row:
Ex: Update emp set sal=sal+(sal*0.20),deptno=20 WHERE empno=7900;
Updating multiple rows:
Ex: update emp set sal=sal+sal*0.20 WHERE job=’CLERK’;
Deleting Data
The Delete statement is used to delete data FROM a table.
The syntax is:
Delete FROM <table_name> [WHERE condition]
Deleting one or more rows:
PRACTICE EXERCISES:
1. Insert the following data into Sailors table:
Sid Sname Rating Age
22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zorba 10 16.0
74 Horatio 9 40.0
85 Art 3 25.5
31 104 11/12/98
64 101 9/5/98
64 102 9/8/98
74 103 9/8/98
Transaction is sequence of operation or events in database like SELECT, INSERT, UPDATE and
DELETE. System failure in middle of transaction gives rise to problems of inconsistency. ORACLE
allows grouping of individual change into logical transactions.
This helps in insuring data consistency and integrity.
COMMIT, ROLLBACK, SAVEPOINT (TRANSACTION) Commands
COMMIT : Used to makes all the changes of database permanent and
erases all savepoints in the current transaction.
ROLL BACK : Undoes the changes made to database in the current transaction.
Erases all savepoints.
SAVE POINT : This allows partial rollback of the transaction.
Syntax for the above
SQL> COMMIT
SQL> ROLL BACK
SQL> SAVE POINT Savepoint name;
Ex: SQL> savepoint S1;
Savepoint Created
SQL> insert into……;
SQL> insert into……;
SQL> savepoint S2;
Savepoint Created.
SQL> delete FROM………;
SQL> rollback to s2;
Rollback complete
Rollback to S2; will undo changes made FROM savepoint S2 ( DELETE…..). But changes made
before savepoint, are not done. So if a COMMIT is issued it will commit two INSERT commands
that are before savepoint S2.
Multi-table queries retrieve data FROM more than one table, using a single query statement. For
example, you use multi-table queries on DEPT and EMP tables, to retrieve department names and names
of the employees who belong to those departments.
Join
To retrieve data, multi-table queries CREATE a join BETWEEN two or more tables. A join compares
data in the specified columns of the tables, and retrieves the rows according to the results of data
comparisons. Rows in one table may be joined to rows in another according to common values existing
in the corresponding columns. You can CREATE the following types of join on tables:
a) Equi-join
b) Non Equi-join
Equi-join
An equi-join can be Created to retrieve matching rows FROM two or more tables. It is the most common
type of join. In Equi-join, you join two tables based on an equality condition specified with the WHERE
clause in the SELECT statement.
Command Syntax
SELECT <column(s)>
FROM <tables>
WHERE <join condition>
To join tables DEPARTMENTS and EMPLOYEES on DEPARTMENT_ID column, the query would be
SELECT first_name, last_name,department_name
FROM employees, departments
WHERE employees.department_id=departments.department_id;
Non Equi-join
When a relationship BETWEEN two tables is obtained by using an operator other than equal(=), it is
called a non-equi-join
SELECT e.first_name,e.salary,j.grade_level FROM employees e,job_grades j WHERE e.salary
BETWEEN j.lowest_sal and j.highest_sal;
Outer join
Sometimes you may want to retrieve rows that do not satisfy the join condition, in addition to the rows
that satisfy the join condition. A join that returns matching rows FROM both the tables, and all the rows
FROM one of the tables specified in the join is called an outer join. You need to use an outer-join
operator (+) with the column of the table FROM which you want to retrieve only the matching rows.
SELECT first_name,last_name,d.department_id,department_name FROM employees e,departments d
WHERE e.department_id(+)=d.department_id ORDER BY d.department_id DESC;
Self Join
In addition to equi-joins, non-equi-joins and outer-joins, Oracle lets you compare values within the same
column of a table. Joins that compare values in a single column of one table are called self joins. For
example, to retrieve the names of all employees and their managers, the query would be:
Set Operators
a) UNION
The UNION Operator combines the results of two queries and returns distinct rows SELECTed by either
query.
b) UNION ALL
The UNION operator removes all the duplicate values FROM the combined results of two queries.
However, if you do not want duplicates to be removed, you can use the keyword ALL with UNION.
c) INTERSECT
You can use the INTERSECT operator to retrieve rows that are common in the result sets of two or more
queries.
d) MINUS Operator
You use the MINUS Operator to retrieve all rows SELECTed by the first query that are not in the second
query.
What is a View?
A view is a window through which you access a portion of a table. View itself doesn’t contain
any data but it refers to the data of a table on which it is based. So views are used to give
simplified representation of data.
Usage of a View
To control the access to data
To simplify the query
View is also called as Virtual Table. Because a view doesn’t contain any data have its own. So it
is not a table but it is used as if it WHERE a table (Virtual)
Ex: To CREATE a view called studview on students table, enter:
CREATE view empview as
SELECT employee_id,first_name FROM employees;
View Created
SELECT * FROM empview;
Snytax
CREATE [OR replace] [Force] view viewname
[(column_name, col_name)]
as query
[with check option];
or Replace : Allows a view to be Created even if one already exists.
Force : Allows view to be Created even if the base table doesn’t exist. However,
the base table should exist become before the view is used.
Using a View
Once a view is Created, a view can be used similar to a table. You can use SELECT command.
Ex1: With check option
SQL> CREATE view V1 as
SELECT first_name, salary FROM employees
WHERE department_id = 20
with check option;
View Created
Note: Whenever views are Created with check option, insertion and deletion will not be
permitted.
Dropping View
Drop view command is used to drop a view
Syntax
Drop view viewname;
Ex: SQL> drop view empview;
Subqueries
A subquery is a query within another query. The outer query is called as main query and inner query is
called as subquery.
Types of SubQueries
1. Single row subqueries
2. Multiple value subqueries
3. Multiple column subqueries
4. Correlated subqueries
Subquery is always executed first and the result is passed to the main query. Only then the main query is
executed.
Multiple value subqueries return more than one value to the parent query. The expression in the parent
statement is compared to the list of values returned by the subquery. Multiple columkn subqueries return
values FROM more than one column
Ex: Find out the jobs HAVING the average salary less than the average salary of the IT_PROG
SELECT job_id,avg(salary) FROM employees GROUP BY job_id HAVING avg(salary)<(SELECT
avg(salary) FROM employees WHERE job_id='IT_PROG');
Correlated Subqueries:
With a normal nested subquery, the inner query is executed first and it executes once, returning values to
be used by the main query. A correlated subquery on the other hand executes once for each row
considered by the parent query.
Ex: Find out employees who earn a salary less than the average salary for their jobs.
SELECT first_name,last_name,job_id,salary FROM employees e WHERE salary<(SELECT avg(salary)
FROM employees WHERE job_id=e.job_id);
Ex1: Find out the employees who are managers i.e. who have atleast one employee reporting to them.
SELECT first_name,last_name,job_id,department_id FROM employees e1 WHERE exists(SELECT
employee_id FROM employees e2 WHERE e1.employee_id=e2.manager_id);
LAB EXPERIMENTS
PROGRAM 1
Objective: The objective of this program is to create a Library database as per the given schema and
execute basic sql queries.
Entity-Relationship Diagram
Author_Name
Book_id Title
Pub_Year M N
Has
Published-by
N No_of_copies
Branch_id
Publisher_Name
M M N
1 Book_Copies In Library_Branch
Branch_Name
Address
Publisher
N Address
Date_out
Book_Lending
Phone
Card_No
Due_date
N
Card
Schema Diagram
Table Creation
CREATE TABLE PUBLISHER(NAME VARCHAR2 (20) PRIMARY KEY, PHONE INTEGER, ADDRESS
VARCHAR2 (20));
Table Descriptions
DESC PUBLISHER;
DESC BOOK;
DESC BOOK_AUTHORS;
DESC LIBRARY_BRANCH;
DESC BOOK_COPIES;
DESC CARD;
DESC BOOK_LENDING;
Queries:
1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of
copies in each branch, etc.
2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017
to Jun 2017.
SELECT CARD_NO
FROM BOOK_LENDING
WHERE DATE_OUT BETWEEN ’01-JAN-2017’ AND ’01-JUL-2017’
GROUP BY CARD_NO
HAVING COUNT (*)>3;
3. Delete a book in BOOK table. Update the contents of other tables to reflect this data
manipulation operation.
4. Partition the BOOK table based on year of publication. Demonstrate it’s working with a
simple query.
CREATE VIEW V_PUBLICATION AS
SELECT PUB_YEAR FROM BOOK;
5. Create a view of all books and its number of copies that are currently available in the
Library.
PROGRAM 2
Objective: The objective of this program is to create Order database as per the given schema and
execute basic sql queries using the concepts of Relational algebra.
Entity-Relationship Diagram
Schema Diagram
Table Creation
CREATE TABLE SALESMAN (SALESMAN_ID NUMBER (4), NAME VARCHAR2 (20), CITY VARCHAR2
(20), COMMISSION VARCHAR2 (20), PRIMARY KEY (SALESMAN_ID));
CREATE TABLE ORDERS (ORD_NO NUMBER (5), PURCHASE_AMT NUMBER (10, 2),
ORD_DATE DATE, PRIMARY KEY (ORD_NO), CUSTOMER_ID
REFERENCES CUSTOMER1 (CUSTOMER_ID) ON DELETE CASCADE, SALESMAN_ID REFERENCES
SALESMAN (SALESMAN_ID) ON DELETE CASCADE);
Table Descriptions
DESC SALESMAN;
DESC CUSTOMER1;
DESC ORDERS;
Queries
1. Count the customers with grades above Bangalore’s average.
SELECT GRADE, COUNT (DISTINCT CUSTOMER_ID)
FROM CUSTOMER1
GROUP BY GRADE
HAVING GRADE > (SELECT AVG(GRADE)
FROM CUSTOMER1
WHERE CITY='BANGALORE');
2. Find the name and numbers of all salesmen who had more than one customer.
SELECT SALESMAN_ID, NAME
FROM SALESMAN A
WHERE 1 < (SELECT COUNT (*)
FROM CUSTOMER1
WHERE SALESMAN_ID=A.SALESMAN_ID);
3. List all salesmen and indicate those who have and don’t have customers in their cities (Use
UNION operation.)
4. Create a view that finds the salesman who has the customer with the highest order of a day.
5. Demonstrate the DELETE operation by removing salesman with id 1000. All his orders must
also be deleted.
Use ON DELETE CASCADE at the end of foreign key definitions while creating child table orders
and then execute the following:
Use ON DELETE SET NULL at the end of foreign key definitions while creating child table
customers and then executes the following:
PROGRAM 3
Objective: The objective of this program is to create Order database as per the given schema and
execute basic sql queries using the concepts of Relational algebra
Entity-Relationship Diagram
Dir_id Dir_Name
Act_id Act_Name
Dir_Phone
Act_Gender Actor Director
M
Has
Movie_Cast
N
Role
Rev_Stars
N Movies
Mov_Lang
Mov_id
Mov_Title Mov_Year
Schema Diagram
Table Creation
CREATE TABLE ACTOR (ACT_ID NUMBER (3), ACT_NAME VARCHAR (20),
ACT_GENDER CHAR (1), PRIMARY KEY (ACT_ID));
Table Descriptions
DESC ACTOR;
DESC DIRECTOR;
DESC MOVIES;
DESC MOVIE_CAST;
DESC RATING;
Queries:
SELECT MOV_TITLE
FROM MOVIES
WHERE DIR_ID IN (SELECT DIR_ID
FROM DIRECTOR
WHERE DIR_NAME = ‘HITCHCOCK’);
2. Find the movie names where one or more actors acted in two or more movies.
SELECT MOV_TITLE
FROM MOVIES M, MOVIE_CAST MV
WHERE M.MOV_ID=MV.MOV_ID AND ACT_ID IN (SELECT ACT_ID
FROM MOVIE_CAST GROUP BY ACT_ID
HAVING COUNT (ACT_ID)>1)
GROUP BY MOV_TITLE
HAVING COUNT (*)>1;
3. List all actors who acted in a movie before 2000 and also in a movie after 2015 (use JOIN
operation).
OR
4. Find the title of movies and number of stars for each movie that has at least one rating and
find the highest number of stars that movie received. Sort the result by movie title.
UPDATE RATING
SET REV_STARS=5
WHERE MOV_ID IN (SELECT MOV_ID FROM MOVIES
WHERE DIR_ID IN (SELECT DIR_ID
FROM DIRECTOR
WHERE DIR_NAME =‘STEVEN PIELBERG’));
PROGRAM 3
Aim of the Program:
Objective: The objective of this program is to create College database and and execute the given queries.
Schema Diagram
Table Creation
CREATE TABLE STUDENT ( USN VARCHAR (10) PRIMARY KEY, SNAME VARCHAR (25),
ADDRESS VARCHAR (25), PHONE NUMBER (10), GENDER CHAR (1));
CREATE TABLE SEMSEC ( SSID VARCHAR (5) PRIMARY KEY, SEM NUMBER (2),
SEC CHAR (1));
CREATE TABLE CLASS (USN VARCHAR (10), SSID VARCHAR (5),PRIMARY KEY (USN, SSID),
FOREIGN KEY (USN) REFERENCES STUDENT (USN),
FOREIGN KEY (SSID) REFERENCES SEMSEC (SSID));
CREATE TABLE SUBJECT (SUBCODE VARCHAR (8), TITLE VARCHAR (20), SEM NUMBER (2),
CREDITS NUMBER (2),PRIMARY KEY (SUBCODE));
CREATE TABLE IAMARKS (USN VARCHAR (10), SUBCODE VARCHAR (8), SSID VARCHAR (5),
TEST1 NUMBER (2), TEST2 NUMBER (2), TEST3 NUMBER (2), FINALIA NUMBER (2),
PRIMARY KEY (USN, SUBCODE, SSID),
FOREIGN KEY (USN) REFERENCES STUDENT (USN),
FOREIGN KEY (SUBCODE) REFERENCES SUBJECT (SUBCODE),
FOREIGN KEY (SSID) REFERENCES SEMSEC (SSID));
Table Descriptions
DESC STUDENT;
DESC SEMSEC;
DESC CLASS;
DESC SUBJECT;
DESC IAMARKS;
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1GA13CS091','10CS81','ISE8C', 15, 16, 18);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1GA13CS091','10CS82','ISE8C', 12, 19, 14);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1GA13CS091','10CS83','ISE8C', 19, 15, 20);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1GA13CS091','10CS84','ISE8C', 20, 16, 19);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1GA13CS091','10CS85','ISE8C', 15, 15, 12);
Queries:
1. List all the student details studying in fourth semester ‘C’ section.
SELECT S.*, SS.SEM, SS.SEC
FROM STUDENT S, SEMSEC SS, CLASS C
WHERE S.USN = C.USN AND
SS.SSID = C.SSID AND
SS.SEM = 4 AND
SS.SEc=’C’;
2. Compute the total number of male and female students in each semester and in each section.
4. Calculate the FinalIA (average of best two test marks) and update the corresponding table for all
students.
CREATE OR REPLACE PROCEDURE AVGMARKS
IS
CURSOR C_IAMARKS IS
SELECT GREATEST(TEST1,TEST2) AS A, GREATEST(TEST1,TEST3) AS B,
GREATEST(TEST3,TEST2) AS C
FROM IAMARKS
WHERE FINALIA IS NULL
FOR UPDATE;
C_A NUMBER;
C_B NUMBER;
C_C NUMBER;
C_SM NUMBER;
C_AV NUMBER;
BEGIN
OPEN C_IAMARKS;
LOOP
FETCH C_IAMARKS INTO C_A, C_B, C_C;
EXIT WHEN C_IAMARKS%NOTFOUND;
--DBMS_OUTPUT.PUT_LINE(C_A || ' ' || C_B || ' ' || C_C);
IF (C_A != C_B) THEN
C_SM:=C_A+C_B;
ELSE
C_SM:=C_A+C_C;
END IF;
C_AV:=C_SM/2;
--DBMS_OUTPUT.PUT_LINE('SUM = '||C_SM);
--DBMS_OUTPUT.PUT_LINE('AVERAGE = '||C_AV);
UPDATE IAMARKS SET FINALIA=C_AV WHERE CURRENT OF C_IAMARKS;
END LOOP;
CLOSE C_IAMARKS;
END;
/
Note: Before execution of PL/SQL procedure, IAMARKS table contents are:
Below SQL code is to invoke the PL/SQL stored procedure from the command line:
BEGIN
AVGMARKS;
END;
PROGRAM 5
Entity-Relationship Diagram
SSN Controlled_by
Name N 1
DNO
Salary
DName
1 N
MgrStartDate
1
Sex 1
N
M Dlocation
Supervisee
Supervisor
Supervision Works_on Controls
N
Hours
Project PName
PNO PLocation
Schema Diagram
Table Creation
CREATE TABLE DEPARTMENT (DNO VARCHAR2 (20) PRIMARY KEY, DNAME VARCHAR2
(20),MGRSTARTDATE DATE);
NOTE: Once DEPARTMENT and EMPLOYEE tables are created we must alter department table to add foreign
constraint MGRSSN using sql command
Table Descriptions
DESC EMPLOYEE;
DESC DEPARTMENT;
DESC DLOCATION;
DESC PROJECT;
DESC WORKS_ON;
Note: update entries of employee table to fill missing fields SUPERSSN and DNO
UPDATE EMPLOYEE SET
SUPERSSN=NULL, DNO=’3’
WHERE SSN=’GATECE01’;
Queries:
1. Make a list of all project numbers for projects that involve an employee whose last name is
‘Scott’, either as a worker or as a manager of the department that controls the project.
2. Show the resulting salaries if every employee working on the ‘IoT’ project is given a 10 percent
raise.
3. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well as the
maximum salary, the minimum salary, and the average salary in this department
4. Retrieve the name of each employee who works on all the projects Controlled by department
number 5 (use NOT EXISTS operator).
5. For each department that has more than five employees, retrieve the department number and
the number of its employees who are making more than Rs. 6, 00,000.
APPENDIX A
Viva Questions
1. What is SQL?
Structured Query Language
2. What is database?
A database is a logically coherent collection of data with some inherent meaning, representing some
aspect of real world and which is designed, built and populated with data for a specific purpose.
3. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In other words it
is general-purpose software that provides the users with the processes of defining, constructing and
manipulating the database for various applications.
4. What is a Database system?
The database and DBMS software together is called as Database system.
5. Advantages of DBMS?
Redundancy is controlled.
Unauthorized access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.
6. Disadvantage in File Processing System?
Data redundancy & inconsistency.
Difficult in accessing data.
Data isolation.
Data integrity.
Concurrent access is not possible.
Security Problems.
7. Describe the three levels of data abstraction?
There are three levels of abstraction:
Physical level: The lowest level of abstraction describes how data are stored.
Logical level: The next higher level of abstraction, describes what data are stored in database and
what relationship among those data.
View level:The highest level of abstraction describes only part of entire database.
Growth and restructuring of base tables is not reflected in views. Thus the view can
insulate users from the effects of restructuring and growth in the database. Hence accounts for logical
data independence.
47. What are partial, alternate,, artificial, compound and natural key?
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same
owner entity. It is sometime called as Discriminator.
Alternate Key: All Candidate Keys excluding the Primary Key are known as Alternate Keys.
ArtificialKey: If no obvious key, either stand alone or compound is available, then the last resort is to
simply create a key, by assigning a unique number to each record or occurrence. Then this is known as
developing an artificial key.
48. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be found.
Binary search style indexing
B-Tree indexing
Inverted list indexing
Memory resident table
Table indexing
49. What is system catalog or catalog relation? How is better known as?
A RDBMS maintains a description of all the data that it contains, information about every relation
and index that it contains. This information is stored in a collection of relations maintained by the system
called metadata. It is also called data dictionary.
62. What are the primitive operations common to all record management systems?
Addition, deletion and modification.
63. Name the buffer in which all the commands that are typed in are stored
‘Edit’ Buffer
64. What are the unary operations in Relational Algebra?
PROJECTION and SELECTION.
65. Are the resulting relations of PRODUCT and JOIN operation the same?
No.
PRODUCT: Concatenation of every row in one relation with every row in another.
JOIN: Concatenation of rows from one relation and related rows from another.
68. Which part of the RDBMS takes care of the data dictionary? How
Data dictionary is a set of tables and database objects that is stored in a special area of the
database and maintained exclusively by the kernel.
72. Define SQL and state the differences between SQL and other conventional programming
Languages
SQL is a nonprocedural language that is designed specifically for data access operations on
normalized relational database structures. The primary difference between SQL and other conventional
programming languages is that SQL statements specify what data operations should be performed rather
than how to perform them.
73. Name the three major set of files on disk that compose a database in Oracle
There are three major sets of files on disk that compose a database. All the files are binary. These
are
Database files
Control files
Redo logs
The most important of these are the database files where the actual data resides. The control files
and the redo logs support the functioning of the architecture itself.
All three sets of files must be present, open, and available to Oracle for any data on the database
to be useable. Without these files, you cannot access the database, and the database administrator might
have to recover some or all of the database using a backup, if there is one.
75. What are the four Oracle system processes that must always be up and running for the
database to be useable
The four Oracle system processes that must always be up and running for the database to be
useable include DBWR (Database Writer), LGWR (Log Writer), SMON (System Monitor), and PMON
(Process Monitor).
76. What are database files, control files and log files. How many of these files should a database
have at least? Why?
Database Files
The database files hold the actual data and are typically the largest in size. Depending on their sizes, the
tables (and other objects) for all the user accounts can go in one database file—but that's not an ideal
situation because it does not make the database structure very flexible for controlling access to storage for
different users, putting the database on different disk drives, or backing up and restoring just
part of the database.
You must have at least one database file but usually, more than one files are used. In terms of accessing and using the data in
the tables and other objects, the number (or location) of the files is immaterial.
The database files are fixed in size and never grow bigger than the size at which they were created
ControlFiles
The control files and redo logs support the rest of the architecture. Any database must have at
least one control file, although you typically have more than one to guard against loss. The control file
records the name of the database, the date and time it was created, the location of the database and redoes
logs, and the synchronization information to ensure that all three sets of files are always in step. Every
time you add a new database or redo log file to the database, the information is recorded in the control
files.
Redo Logs
Any database must have at least two redo logs. These are the journals for the database; the redo
logs record all changes to the user objects or system objects. If any type of failure occurs, the changes
recorded in the redo logs can be used to bring the database to a consistent state without losing any
committed transactions. In the case of non-data loss failure, Oracle can apply the information in the redo
logs automatically without intervention from the DBA.
The redo log files are fixed in size and never grow dynamically from the size at which they were
created.
The ROWID is used internally in indexes as a quick means of retrieving rows with a
particular key value. Application developers also use it in SQL statements as a quick way to access a row
once they know the ROWID
78. What is Oracle Block? Can two Oracle Blocks have the same address?
Oracle "formats" the database files into a number of Oracle blocks when they are first created—
making it easier for the RDBMS software to manage the files and easier to read data into the memory
areas.
The block size should be a multiple of the operating system block size. Regardless of the block
size, the entire block is not available for holding data; Oracle takes up some space to manage the contents
of the block. This block header has a minimum size, but it can grow.
These Oracle blocks are the smallest unit of storage. Increasing the Oracle block size can improve
performance, but it should be done only when the database is first created.
Each Oracle block is numbered sequentially for each database file starting at 1. Two blocks can
have the same block address if they are in different database files.
80. Name two utilities that Oracle provides, which are use for backup and recovery.
Along with the RDBMS software, Oracle provides two utilities that you can use to back up and
restore the database. These utilities are Exportand Import.
The Export utility dumps the definitions and data for the specified part of the database to an
operating system binary file. The Import utility reads the file produced by an export, recreates the
definitions of objects, and inserts the data
If Export and Import are used as a means of backing up and recovering the database, all the
changes made to the database cannot be recovered since the export was performed. The best you can do
is recovering the database to the time when the export was last performed.
81. Name two utilities that Oracle provides, which are use for backup and recovery.
Along with the RDBMS software, Oracle provides two utilities that you can use to back up and
restore the database. These utilities are Exportand Import.
The Export utility dumps the definitions and data for the specified part of the database to an
operating system binary file. The Import utility reads the file produced by an export, recreates the
definitions of objects, and inserts the data
If Export and Import are used as a means of backing up and recovering the database, all the
changes made to the database cannot be recovered since the export was performed. The best you can do
is recovering the database to the time when the export was last performed.
82. What are stored-procedures? And what are the advantages of using them.
Stored procedures are database objects that perform a user defined operation. A stored procedure
can have a set of compound SQL statements. A stored procedure executes the SQL commands and
returns the result to the client. Stored procedures are used to reduce network traffic.
87. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By
CUSTOMER Union Select 'EAST', CUSTOMER From CUST_DTLS Where REGION = 'E'
Order By CUSTOMER
The above is
a) Not an error
b) Error - the string in single quotes 'NORTH' and 'SOUTH'
c) Error - the string should be in double quotes
d) Error - ORDER BY clause
(d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS
95. What is cold backup and hot backup (in case of Oracle)?
Cold Backup:
Itis copying the three sets of files (database files, redo logs, and control file) when the instance is shut
down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance
to guarantee a consistent copy.
If a cold backup is performed, the only option available in the event of data file loss is restoring all
the files from the latest backup. All work performed on the database since the last backup is lost.
Hot Backup:
Some sites (such as worldwide airline reservations systems) cannot shut down the database while
making a backup copy of the files. The cold backup is not an available option.
So different means of backing up database must be used — the hot backup. Issue a SQL
command to indicate to Oracle, on a tablespace-by-tablespace basis, that the files of the tablespace are to
backed up. The users can continue to make full use of the files, including making changes to the data.
Once the user has indicated that he/she wants to back up the tablespace files, he/she can use the
operating system to copy those files to the desired backup destination.
The database must be running in ARCHIVELOG mode for the hot backup option. If a data loss
failure does occur, the lost database files can be restored using the hot backup and the online and offline
redo logs created since the backup was done. The database is restored to the most consistent state without
any loss of committed transactions.
96. How can you find the minimal key of relational schema?
Minimal key is one which can identify each tuple of the given relation schema uniquely. For
finding the minimal key it is required to find the closure that is the set of all attributes that are dependent
on any given set of attributes under the given set of functional dependency.
Algo. I Determining X+, closure for X, given set of FDs F
1. Set X+ = X
2. Set Old X+ = X+
3. For each FD Y Z in F and if Y belongs to X+ then add Z to X+
4. Repeat steps 2 and 3 until Old X+ = X+
Retroactive Update:
The updates that are applied to database after it becomes effective in real world.
Simultaneous Update:
The updates that are applied to database at the same time when it becomes effective in real world .What
are the different types of JOIN operations?
Equi Join: This is the most common type of join which involves only equality comparisons. The
disadvantage in this type of join is that there
SQL Questions:
1. Which is the subset of SQL commands used to manipulate Oracle Database structures,
including tables?
Data Definition Language (DDL)
2. What operator performs pattern matching?
LIKE operator
3. What operator tests column for the absence of data?
IS NULL operator
4. Which command executes the contents of a specified file?
START <filename> or @<filename>
5. What is the parameter substitution symbol used with INSERT INTO command?
&
6. Which command displays the SQL command in the SQL buffer, and then executes it?
RUN
7. What are the wildcards used for pattern matching?
For single character substitution and % for multi-character substitution
8. State true or false. EXISTS, SOME, ANY are operators in SQL.
True
9. State true or false. !=, <>, ^= all denote the same operation.
True
10. What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all
11. What command is used to get back the privileges offered by the GRANT command?
REVOKE
12. Which system tables contain information on privileges granted and privileges obtained?
USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD
13. Which system table contains information on constraints on all the tables created?
USER_CONSTRAINTS
14. TRUNCATE TABLE EMP;
DELETE FROM EMP;
Will the outputs of the above two commands differ?
Both will result in deleting all the rows in the table EMP.
15. What the difference is between TRUNCATE and DELETE commands?
TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE
operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause can be
used with DELETE and not with TRUNCATE.
16. What command is used to create a table by copying the structure of another table?
Answer:
CREATE TABLE AS SELECT command
Explanation:
To copy only the structure, the WHERE clause of the SELECT command should contain a
FALSE statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied
to the new table.
17. What will be the output of the following query?
SELECT REPLACE (TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL;
TROUBLETHETROUBLE
18. What will be the output of the following query?
SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );
Answer :
NO
Explanation :
The query checks whether a given string is a numerical digit.
SQL HANDS ON
b. EMP:
COLUMN NAME DATATYPE(SIZE)
-----------------------------------------------------------------------------------------------
EMPNO NUMBER (4)
ENAME VARCHAR2 (10)
JOB VARCHAR2 (9)
MGR NUMBER (4)
HIREDATE DATE
SAL NUMBER (7, 2)
COMM NUMBER (7, 2)
DEPTNO NUMBER (2)
2. Check the Default Size of a Number, Char and Date Data types.
3. Describe the Structure of the Table and EMP Table.
4. Add two columns to the table EMP with the following information in one single
ALTER COMMAND.
COLUMN NAME DATATYPE (SIZE)
-----------------------------------------------------------------------------------------------
SEX CHAR (1)
PLACE CHAR (15)
5. Modify the column job present in the EMP table with the following information
given below:
COLUMN NAME DATATYPE (SIZE)
-----------------------------------------------------------------------------------------------
JOB VARCHAR2 (15)
6. modify the column ENAME present in the EMP table with the following information given
below:
COLUMN NAME DATATYPE (SIZE)
-----------------------------------------------------------------------------------------------
ENAME CHAR (15)
7. Decrease the size for the column EMPNO with the following information:-
COLUMN NAME DATATYPE (SIZE)
-----------------------------------------------------------------------------------------------
EMPNO NUMBER (2)
8. Modify the column name of EMPNO to EMPLOYEE_NUMBER present in the EMP table
verify the result.
9. Add a new column nationality placed between JOB and MGR columns and verify the result
10. Drop the table DEPT and EMP.
11. What is the data type of the column HIREDATE and how many bytes it occupies.
12. Create a table EMP and DEPT using the following information.
a. DEPT:
COLUMN NAME DATATYPE(SIZE)
-----------------------------------------------------------------------------------------------
DEPTNO NUMBER(2) CONSTRAINT PK_DEPTNO PRIMARY
KEY
DNAME VARCHAR2(14)
LOC VARCHAR2(14)
b.EMP:
COLUMN NAME DATATYPE(SIZE)
-----------------------------------------------------------------------------------------------
SOL: DELETE FROM EMP X WHERE 5 > (SELECT COUNT (ROWID) FROM EMP
Y WHERE Y. ROWID < X.ROWID);
53. Delete the rows of the temp table permanently
SOL: TURNCATE TABLE TEMP;
54. Update a record of EMP table and save the changes permanently in the database
SOL: UPDATE EMP SET SAL=SAL+100 WHERE EMPNO=100; COMMIT;
55. Sql * plus has the facility to automatically save all the records without issuing the TCL
command which is that?
SOL: SET AUTOCOMMIT ON
56. Give all the privileges you have of a database object to another
SOL: GRANT ALL ON EMP TO ORA253A;
57. Give only select, insert privileges to another user
SOL: GRANT SELECT, INSERT ON EMP TO ORA267A;
58. List the user’s id and which database object you have granted
SOL: SELECT * FROM USE_TAB_PRIVS;
APPENDIX B
ADDITIONAL EXERCISES
Exercise 1: To understand some simple Database Applications and build Conceptual Data Model.
a) Select an enterprise that you are familiar with (for example, a school, a college, a company, a
small business, a club or association). List all the information that this enterprise uses.
b) Describe the steps involved in the database design process using E-R Modeling: Requirements
Analysis, Identify Entity Sets, Identify Relationship Sets, Value Sets and Attributes, Specifying
Primary keys, Building E-R diagram, Implementation
c) For the following mini-world example database applications, Design and Develop Conceptual
Data Model (E-R Diagram) with all the necessary entities, attributes, constraints and
relationships.
i. Medical Clinic Database – The clinic has a number of regular patients and new patients come
to the clinic regularly. Patients make appointments to see one of the doctors; several doctors
attend the clinic and they each have their own hours. Some doctors are General Practitioners
(GPs) while others are specialists(cardiologists, dermatologists etc.,). Patients have families
and the family relationships are important. A medical record of each patient needs to be
maintained. Information on prescriptions, insurance, allergies, etc needs to be maintained.
Different doctors may charge different fees. Billing has to be done for Patients.
iv. Time Table Preparation - An Engineering College has a number of Branches. Each Branch
has number sections, a number of courses and a number of faculty members teaching the
courses. Each branch has a number of class rooms and laboratories. Each course may be
scheduled in a class room at a particular time.
Note: Similar applications may be explored and given as assignments to students in a group.
Exercise 2: Design and build Relational Data Model for each of the application scenarios of exercise 1
specifying all possible constraints. Extend the same for a database application of students' choice.
Exercise 3 To understand and demonstrate DDL, DML and DCL Commands of SQL
a. Create a table called EMP with the following structure and describe it.
Name Type
-----------------------------------------------------
EMPNO NUMBER (6)
ENAME VARCHAR2 (20)
DOB DATE
JOB VARCHAR2 (10)
DEPTNO NUMBER (2)
SAL NUMBER (7,2)
Allow NULL for all columns except ENAME and JOB. EMPNO is the Primary Key
b. Add a column EXPERIENCE of type NUMERIC to the EMP table. Allow NULL to it.
c. Modify the column width of the JOB field of EMP table.
d. Create DEPT table with the following structure and describe it
Name Type
-----------------------------------------------------
DEPTNO NUMBER (2)
DNAME VARCHAR2 (15)
LOCN VARCHAR2 (10)
DEPTNO is the Primary Key and DNAME cannot be NULL
e. Add constraint to check the SAL value of EMP Table. SAL must be > 6000.
f. Drop a column EXPERIENCE from the EMP table.
g. Insert a single record into DEPT table. Repeat this for inserting at least 3 records
h. Insert more than a record into EMP table using a single insert command. Insert at least 10 records
i. Update the EMP table to set the salary of all employees to Rs. 30000/- for a given JOB type
j. Create a pseudo table EMPLOYEE with the same structure as the table EMP using SELECT
clause.
k. Delete employees from EMP table for a given JOB type. Delete the first five records of EMP
table
l. Grant all/some privileges of EMP table to DEPT table
m. Revoke some/all privileges of EMP table from DEPT table
n. Truncate the EMP table and drop the DEPT table
o. Demonstrate the use of COMMIT, SAVEPOINT and ROLLBACK commands