PCC-CS691 - DBMS - Assignment Details With Notes
PCC-CS691 - DBMS - Assignment Details With Notes
SYSTEM LAB
(PCC-CS 691)
Last Revised
February, 2022
Compiled by
Dept. of CSE
Techno Main Salt Lake
DATABASE MANAGEMENT SYSTEM
LAB MANUAL (PCC-CS 691)
:INDEX:
REFERENCE BOOKS
1. SQL/PLSQL Ivan Bayross
2. Fundamentals of database systems(Ramez Elmsari,Shamkant B.Navathe)
3. Database System Concepts (Avi Silberschatz · Henry F.Korth · S. Sudarshan)
4. Oracle Database 10g: The Complete Reference (Kevin Loney)
5. Oracle 9i: The Complete Reference (Kevin Loney, George Koch, and the Experts at TUSC)
Assignment List
Exp. Week
List of Experiments
No. No.
1. Design an ER diagram for a Motor Vehicle Branch that administers driving tests
and issues driver's licenses. Analyze the requirements by identifying the entities,
attributes, relationships, keys, constraints etc. Apply extended entity-relationship Week1
features to the design. Defend your design with proper assumptions and
justifications. Map the ER model into a relational model.
2. Design an ER diagram for an application that models soccer teams, the games
they play, and the players in each team. Analyze the requirements by identifying
the entities, attributes, relationships, keys, constraints etc. Apply extended entity- Week2
relationship features to the design. Defend your design with proper assumptions
and justifications. Map the ER model into a relational model.
3. Design an ER diagram for an application that models an educational institute
having several departments, faculty, students, projects, student hostels etc.
Analyze the requirements by identifying the entities, attributes, relationships,
Week3
keys, constraints etc. Apply extended entity-relationship features to the design.
Defend your design with proper assumptions and justifications. Map the ER
model into a relational model.
4. i. Create tables for Client, Product, and Salesman with the attributes given,
implementing DDL commands for specifying prime attributes, non-prime
attributes, foreign keys, cardinalities, null values, constraints etc. and the data
types. Implement DDL commands for drop, alter on the tables created.
Week4
ii. Implement DML commands like populating the tables with data using insert
command and retrieving data using simple queries in SQL. (Application of select,
update, delete etc.)
5. i. Create tables for Client, Product, Salesman, Sales Order, and
Sales Order Details and populate them. Retrieve data by writing queries in
SQL using logical operators, aggregate operators, group by, having, order by
clauses etc.
Week5
ii. Create tables for Employee, Company and works and populate them. Retrieve
data by writing nested queries in SQL using JOIN to combine tables and other
operators like IN, BETWEEN, LIKE etc.
6. i. Design an ER diagram for an application that models a car-insurance company
whose customers own one or more cars each. Analyze the requirements by
identifying the entities, attributes, relationships, keys, constraints etc. Apply
extended entity-relationship features to the design. Defend your design with Week6
proper assumptions and justifications. Map the ER model into a relational
model.
Exp. Week
List of Experiments
No. No.
ii. Create tables, populate with data and construct queries (advanced) in SQL to
extract information from the car insurance company’s database.
7. i. Design an ER diagram for an application that models a hospital doctors treat
patients, prescribe tests, monitor progress etc. Analyze the requirements by
identifying the entities, attributes, relationships, keys, constraints etc. Apply
extended entity-relationship features to the design. Defend your design with
proper assumptions and justifications. Map the ER model into a relational Week7
model.
ii. Create tables, populate with data and construct queries (advanced) in SQL to
extract information from the car insurance company’s database.
8. i. Implement a PL/SQL block that will accept student id number from the user,
and check is student attendance is less than 80% then display message that
student cannot appear in exam. [Table: STUDENT (STUD_ID, primary key,
STUD_NAME, STUD_ATT)].
ii. Implement a PL/SQL code block that will accept an account number from the
user. Check if the user’s balance is less than the minimum balance, only then
deduct Rs.100 from the balance. The process is fired on the ACCT_MSTR table.
[Table: ACCT_MSTR (ACCT_NO, ACCT_HOLDR_NAME, CURBAL].
iii. Implement a PL/SQL code block to calculate the area of a circle for a value of
radius varying from 3 to 7. Store the radius and the corresponding values of
calculated area in an empty table named AREAS, consisting of two columns
Radius and Area. [Table: AREAS (RADIUS, AREA)].
Week8
iv. Implement a PL/SQL procedure that takes weight of an apple box as input from
the user.
● If the weight is >= 10 kg, rate =Rs. 5/kg.
● If the weight is < 10 kg, rate = Rs. 7/kg.
Calculate the cost of the apple box. Display the output on the screen.
vi. Implement a PL/SQL block using cursor that will display the name, department
and the salary of the first 3 employees getting lowest salary. [Table: Employee
(ename, dept, salary)]
vii. Implement a PL/SQL cursor that will update salary of all employees, such that,
it allows an increment of 20% if the salary is less than 2000 otherwise
Exp. Week
List of Experiments
No. No.
increment of Rs.1000. It should print old and new salary for all employees.
[Table: Employee (ename, dept, salary)]
9. Consider the following relations and Draw the ER, EER Diagram, Relational Model
and write the SQL statement for the following queries:
a) Find the names of all employees who work for Axis Bank.
b) Find the names and cities of residence of all employees who work for Axis Bank.
c) Find the names, street addresses, and cities of residence of all employees who
work for Axis Bank and earn more than Rs.30000 per annum.
Week9
d) Find all employees who live in the same city as the company for which they work
is located.
e) Find all employees who live in the same city and on the same street as their
managers.
f) Find all employees in the database who do not work for Axis Bank.
g) Find all employees who earn more than every employee of Axis Bank.
h) Assume that the companies may be located in several cities. Find all companies
located in every city in which Axis Bank is located.
i) Find all employees who earn more than the average salary of all employees of
their company.
Exp. Week
List of Experiments
No. No.
l) Find those companies whose employees earn a higher salary, on average, than
the average salary at Axis Bank.
P) Give all managers in the database a 10 percent raise, unless the salary would be
greater than Rs.300000.In such cases, give only a 3 percent raise.
q) Delete all tuples in the works relation for employees of Axis Bank.
1. Draw the appropriate ER, EER and Relational model for the given data.
ii) Find player ids of players who have scored more than 30 in every ODI match that
they have batted.
iii) Find the ids of players that had a higher average score than the average score
for all players when they played in Sri Lanka.
11. A record company wishes to use a computer database to help with its operations
regarding its performers, recordings and song catalogue. A requirements analysis
has elicited the following information:
Songs have a unique song number, a non-unique title and a composition
date. Week11
Exp. Week
List of Experiments
No. No.
A song is recorded as a track of a CD. A CD has many songs on it, called
tracks. CDs have a unique record catalogue number,
A title and must have a producer (the full name of the producer is required).
Each track must have the recording date and the track number of the CD.
A song can appear on many (or no) CDs, and be recorded by many different
recording artists. The same recording artist might re-record the same song
on different CDs.
A CD must have only 1 recording artist appearing on it.
CDs can be released a number of times, and each time the release date and
associated number of sales is required.
3. PL/SQL
A. Populate the tables and answer the following query using SQL.
1. List the names and addresses of all guests in London, alphabetically ordered by Week12
name.
2. List all double or family rooms with a price below £40.00 per night, in ascending
order of price.
Exp. Week
List of Experiments
No. No.
6. What is the total revenue per night from all double rooms?
8. List the details of all rooms at the Grosvenor Hotel, including the name of the
guest staying in the room, if the room is occupied.
9. What is the total income from bookings for the Grosvenor Hotel today?
10. List the rooms that are currently unoccupied at the Grosvenor Hotel.
DLOCATION (DNo,DLoc)
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.
Exp. Week
List of Experiments
No. No.
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.
E-R Diagram
ER-Diagram is a visual representation of data that describes how data is related to each other.
1) Entity
An Entity can be any object, place, person or class. In E-R Diagram, an entity is represented using
rectangles. Consider an example of an Organisation. Employee, Manager, Department, Product
and many more can be taken as entities from an Organisation.
Weak Entity
Weak entity is an entity that depends on another entity. Weak entity doen't have key attribute of
their own. Double rectangle represents weak entity.
2) Attribute
Key Attribute
Key attribute represents the main characterstic of an Entity. It is used to represent Primary key.
Ellipse with underlying lines represent Key Attribute.
An attribute can also have their own attributes. These attributes are known as Composite attribute.
3) Relationship
Binary Relationship
Unary Relationship
Recursive Relationship
Ternary Relationship
Binary Relationship
Binary Relationship means relation between two Entities. This is further divided into three types.
The above example describes that one student can enroll only for one course and a course
will also have only one Student. This is not what you will usually see in relationship.
2. One to Many : It reflects business rule that one entity is associated with many number of same
entity. The example for this relation might sound a little weird, but this menas that one student can
enroll to many courses, but one course will have one Student.
The arrows in the diagram describes that one student can enroll for only one course.
3. Many to One : It reflects business rule that many entities can be associated with just one entity.
For example, Student enrolls for only one Course but a Course can have many Students.
4. Many to Many :
The above diagram represents that many students can enroll for more than one courses.
Unary Relationship
A unary relationship is when both participants in the relationship are the same entity.
For
Example:
Subjects may be prerequisites for other subjects.
Recursive Relationship
Recursive relationships occur within unary relationships. When an Entity is related with itself it is
known as Recursive Relationship. The relationship may be one to one, one to many or many to
many. That is the cardinality of the relationship is unary. The connectivity may be 1:1, 1:M, or
M:N.
For example:
Ternary Relationship
A ternary relationship is when three entities participate in the relationship. Relationship of degree
three is called Ternary relationship.
For Example:
The University might need to record which teachers taught which subjects in which courses.
Generalization
Generalization is a bottom-up approach in which two lower level entities combine to form a
higher level entity. In generalization, the higher level entity can also combine with other lower
level entity to make further higher level entity.
Account
BOTTOM
I UP
APPROACH
Saving
Current
Specialization
Student
Top DOWN
I APPROACH
Aggregration
Aggregration is a process when relation between two entity is treated as a single entity. Here the
relation between Center and Course, is acting as an Entity in relation with Visitor.
Examples::
1> Draw the E-R diagram which models an online bookstore.
Answer :
Consider a university database for the scheduling of classrooms for -final exams. This
database could be modeled as the single entity set exam, with attributes course-name,
section-number, room-number, and time. Alternatively, one or more additional entity sets
could be defined, along with relationship sets to replace some of the attributes of the
exam entity set, as
course with attributes name, department, and c-number
section with attributes s-number and enrollment, and dependent as a weak entity set on
course
room with attributes r-number, capacity, and building
Show an E-R diagram illustrating the use of all three additional entity sets listed.
Answer :
Company organized into DEPARTMENT. Each department has unique name and a
particular employee who manages the department. Start date for the manager is recorded.
Department may have several locations.
A department controls a number of PROJECT. Projects have a unique name, number and
a single location.
Company’s EMPLOYEE name, ssno, address, salary, sex and birth date are recorded. An
employee is assigned to one department, but may work for several projects (not
necessarily controlled by her dept). Number of
hours/week an employee works on each project is recorded; The immediate supervisor
for the employee.
Employee’s DEPENDENT are tracked for health insurance purposes (dependent name,
birthdate, relationship to employee).
Answer :
NOTE: The foreign key and relationship attributes, if any, are not included yet at this step.
STEP 2: For each weak entity type W in the ER schema with owner entity type E, create a
relation R, and include all simple attributes (or simple components of composite
attributes) of W as attributes of R. In addition, include as foreign key attributes of
R the primary key attribute(s) of the relation(s) that correspond to the owner
entity type(s); this takes care of the identifying relationship type of W. The
primary key of R is the combination of the primary key(s) of the owner(s) and the
partial key of the weak entity type W, if any.
NOTE: It is common to choose the propagate (CASCADE) option for the referential triggered
action on the foreign key in the relation corresponding to the weak entity type.
STEP 3: For each binary 1:1 relationship type R in the ER schema, identify the relations S and
T that correspond to the entity types participating in R. Choose one of the
relations—S, say—and include as foreign key in S the primary key of T. Include
all the simple attributes (or simple components of composite attributes) of the 1:1
relationship type R as attributes of S.
NOTE: It is better to choose an entity type with total participation in R in the role of S. (WHY?)
Note:When both participations are total, an alternative mapping of a 1:1 relationship type is
possible by merging the two entity types and the relationship into a single relation. (WHY?)
STEP 4: For each regular binary 1:N relationship type R, identify the relation S that
represents the participating entity type at the N-side of the relationship type.
Include as foreign key in S the primary key of the relation T that represents the
other entity type participating in R. (WHY?)
STEP 5: For each binary M:N relationship type R, create a new relation S to represent R.
Include as foreign key attributes in S the primary keys of the relations that
represent the participating entity types; their combination will form the primary
key of S.
Example: WORKS_ON
NOTE: The propagate (CASCADE) option for the referential triggered action should be
specified on the foreign keys in the relation corresponding to the relationship R, since each
relationship instance has an existence dependency on each of the entities it relates. This can be
used for both ON UPDATE and ON DELETE.
STEP 6: For each multivalued attribute A , create a new relation R. This relation R will
include an attribute corresponding to A, plus the primary key attribute K—as a
foreign key in R—of the relation that represents the entity type or relationship type
that has A as an attribute. The primary key of R is the combination of A and K. If
the multivalued attribute is composite, we include its simple components.
NOTE: The propagate (CASCADE) option for the referential triggered action should be
specified on the foreign key in the relation corresponding to the multivalued attribute for both
ON UPDATE and ON DELETE.
STEP 7: For each n-ary relationship type R, where n > 2, create a new relation S to represent
R. Include as foreign key attributes in S the primary keys of the relations that
represent the participating entity types.
STEP 8: Convert each specialization with m subclasses {S1, S2, . . ., Sm} and
(generalized) superclass C, where the attributes of C are {k, a1, . . ., an} and k is the
(primary) key, into relation schemas using one of the four following options:
Option 8A: Create a relation L for C with attributes Attrs(L) = {k, a1, . . ., an} and
PK(L) = k. Create a relation Li for each subclass Si, 1 1 i 1 m, with the attributes
Attrs(Li) = {k}D {attributes of Si} and PK(Li) = k.
Example:
Option 8B: Create a relation Li for each subclass Si, 1 1 i 1 m, with the attributes Attrs(Li) =
{attributes of Si}D {k, a1, . . ., an} and PK(Li) = k.
Example:
Option 8C: Create a single relation L with attributes Attrs(L) = {k, a1, . . ., an} D {attributes of
S1} D . . . D {attributes of Sm} D {t} and PK(L) = k. This option has the potential for
generating a large number of null values.
Example:
Option 8D: Create a single relation schema L with attributes Attrs(L) = {k, a1, . . ., an} D
{attributes of S1} D . . . D {attributes of Sm} D {t1, t2, . . ., tm} and PK(L) = k.
Example:
For mapping a category whose defining superclasses have different keys, it is customary to
specify a new key attribute, called a surrogate key, when creating a relation to correspond to the
category.
Step 1: Write Dia in run window or select Dia from all programs.
Step 2:
Now select ER from drop down list and draw the ER and EER diagram using the given
icons.
But rest of this icons you also can use the selected icons if necessary
Design an ER diagram for a Motor Vehicle Branch that administers driving tests and issues driver's
licenses. Analyze the requirements by identifying the entities, attributes, relationships, keys,
constraints etc. Apply extended entity-relationship features to the design. Defend your design with
proper assumptions and justifications. Map the ER model into a relational model.
Design an ER diagram for an application that models soccer teams, the games they play, and the players
in each team. Analyze the requirements by identifying the entities, attributes, relationships, keys,
constraints etc. Apply extended entity-relationship features to the design. Defend your design with
proper assumptions and justifications. Map the ER model into a relational model.
SQL
AIM: To create a DDL commands to perform creation of table, alter, rename, drop, truncate
and to study the various DML commands and implement them on the database.
SQL (Structured Query Language) is a database computer language designed for the retrieval and
management of data in relational database management systems (RDBMS), database schema creation and
modification, and database object access control management.SQL is a standard supported by all the
popular relational database management systems in the market place. The basis data structure in RDBMS
is a table.
1. Character Datatypes:
Char – fixed length character string that can varies between 1-2000 bytes
Varchar / Varchar2 – variable length character string, size ranges from 1-4000 bytes.it saves the
disk space(only length of the entered value will be assigned as the size of column)
Long - variable length character string, maximum size is 2 GB
2. Number Datatypes :
Can store +ve,-ve,zero,fixed point,floating point with 38 precission.
Number – {p=38,s=0}
Number(p) - fixed point
3. Date Datatype:
Used to store date and time in the table.
DB uses its own format of storing in fixed length of 7 bytes for century, date, month year, hour,
minutes, seconds
Default data type is “dd-mon-yy”
4. Raw Datatype: used to store byte oriented data like binary data and byte string.
5. Other :
CLOB – stores character object with single byte character.
BLOB – stores large binary objects such as graphics,video,sounds.
BFILE – stores file pointers to the LOB’s.
CREATE TABLE
The Create Table Command: - it defines each column of the table uniquely. Each has minimum of three
attributes, a name , data type and size.
Syntax:
CREATE TABLE <TABLE NAME> (<COL1> <DATATYPE>(<SIZE>),<COL2> <DATATYPE><SIZE>));
Example:
1. CREATE TABLE EMP(EMPNO NUMBER(4) PRIMARY KEY, ENAME CHAR(10));
2. CREATE TABLE PROG20 (PNAME VARCHAR2(20) NOT NULL, DOJ DATE NOT NULL,
DOB DATE NOT NULL, SEX VARCHAR(1) NOT NULL, PROF1 VARCHAR(20),
PROF2 VARCHAR(20),SALARY NUMBER(7,2) NOT NULL);
Rules:
1. Oracle reserved words cannot be used.
3. Underscore, numerals, letters are allowed but not blank space.
3. Maximum length for the table name is 30 characters.
4. 2 different tables should not have same name.
5. We should specify a unique column name.
6. We should specify proper data type along with width.
7. We can include “not null” condition when needed. By default it is ‘null’.
ALTER TABLE
Alter command is used to:
1. Add a new column.
2. Modify the existing column definition.
3. To include or drop integrity constraint.
Example:
1. ALTER TABLE EMP ADD (PHONE_NO CHAR (20));
2. ALTER TABLE EMP MODIFY(PHONE_NO NUMBER (10));
3. ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);
DROP TABLE
It will delete the table structure provided the table should be empty.
Syntax: DROP TABLE <TABLENAME>;
Example: DROP TABLE PROG20; //Here prog20 is table name
TRUNCATE TABLE
If there is no further use of records stored in a table and the structure has to be retained
then the records alone can be deleted.
Syntax: TRUNCATE TABLE <TABLE NAME>;
Example: TRUNCATE TABLE CUSTOMER;
DESC
This is used to view the structure of the table.
Syntax: DESC <TABLENAME>;
Example: DESC EMP;
Sample Queries:
Name Type
EMPNO NUMBER(6)
ENAME VARCHAR2(20)
JOB VARCHAR2(10)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Q2: Add a column experience to the emp table. Experience numeric null allowed.
Solution:
1. Learn alter table syntax.
2. Define the new column and its data type.
3. Use the alter table syntax.
Ans: SQL> ALTER TABLE EMP ADD(EXPERIENCE NUMBER(2));
Table altered.
Q3: Modify the column width of the job field of emp table.
Solution:
1. Use the alter table syntax.
2. Modify the column width and its data type.
Ans:
SQL> ALTER TABLE EMP MODIFY(JOB VARCHAR2(12));
Table altered.
SQL> ALTER TABLE EMP MODIFY(JOB VARCHAR(13));
Table altered.
Name Type
DEPTNO NUMBER(2)
DNAME VARCHAR2(10)
LOC VARCHAR2(10)
Solution:
1. Understand create table syntax.
2. Decide the name of the table.
3. Decide the name of each column and its data type.
4. Use the create table syntax to create the said tables.
5. Create primary key constraint for each table as understand from logical table structure.
Q5: create the emp1 table with ename and empno, add constraints to check the empno value
while entering (i.e) empno > 100.
Solution:
1. Learn alter table syntax.
2. Define the new constraint [columns name type]
3. Use the alter table syntax for adding constraints.
Solution:
1. Learn alter table syntax. Use the alter table syntax to drop the column.
Ans: SQL> ALTER TABLE EMP DROP COLUMN EXPERIENCE;
Table altered.
Q7: Truncate the emp table and drop the dept table
DML COMMANDS
DML commands are the most frequently used SQL commands and is used to query and
manipulate the existing database objects. Some of the commands are :
Insert
Select
Update
Delete.
INSERT Command
Insert Command This is used to add one or more rows to a table. The values are separated by
commas and the data types char and date are enclosed in apostrophes. The values must be
entered in the same order as they are defined.
Example:
First create a table named STD
CREATE TABLE STD (SNO NUMBER(5),SNAME VARCHAR2(20), AGE NUMBER(5),
SDOB DATE,SM1 NUMBER(4,2),SM2 NUMBER(4,2),SM3 NUMBER(4,4));
SELECT Command
Select query is used to retrieve data from a tables. It is the most used SQL query. We can retrieve complete
tables, or partial by mentioning conditions using WHERE clause.
Syntax:
Example:
Consider the following Student table,
The above query will fetch information of S_ID, S_NAME and AGE column from Student table
A special character asterisk * is used to address all the data(belonging to all columns) in a query.
The above query will show all the records of Student table that means it will show complete Student table
as result.
The above command will display a new column in the result, showing 3000 added into existing salaries of
the employees.
UPDATE command
Update command is used to update a row of a table. A single column may be updated or more than
one column could be updated.
Example:
UPDATE STUDENT SET AGE=18 WHERE S_ID=102;
DELETE command
Delete command is used to delete data from a table. Delete command can also be used with
condition to delete a particular row. The delete command consists of a from clause followed by an
optional where clause.
101 ADAM 15
102 ALEX 18
1 row created.
Q2: Insert more than a record into emp table using a single insert command.
Ans: SQL> INSERT INTO EMP VALUES(&EMPNO,'&ENAME','&JOB',&DEPTNO,&SAL);
Enter value for empno: 1
Enter value for ename: Mathi
Enter value for job: AP
Enter value for deptno: 1
Enter value for sal: 10000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(1,'Mathi','AP',1,10000)
1 row created.
SQL> /
Enter value for empno: 2
Enter value for ename: Arjun
Enter value for job: ASP
Enter value for deptno: 2
Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(2,'Arjun','ASP',2,12000)
1 row created.
SQL> /
Enter value for empno: 3
Enter value for ename: Gugan
Enter value for job: ASP
Enter value for deptno: 1
Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(3,'Gugan','ASP',1,12000)
1 row created.
Q3: Update the emp table to set the salary of all employees to Rs15000/- who are working as
ASP.
Q4: Create a pseudo table employee with the same structure as the table emp and insert rows
into the table using select clauses.
Table created.
ENAME JOB
MATHI AP
ARJUN ASP
GUGAN ASP
KARTHIK PROF
AKALYA AP
SURESH LECT
6 rows selected.
6 rows selected.
SQL> DELETE FROM EMP WHERE JOB='LECT';
1 row deleted.
SQL> SELECT * FROM EMP;
Q7: List the records in the emp table orderby salary in ascending order.
Ans: SQL> SELECT * FROM EMP ORDER BY SAL;
Q8: List the records in the emp table orderby salary in descending order.
Ans: SQL> SELECT * FROM EMP ORDER BY SAL DESC;
Q10: Display deptno from the table employee avoiding the duplicated values.
Solution: 1. Use SELECT FROM syntax.
2.Select should include distinct clause for the deptno.
Ans: SQL> SELECT DISTINCT DEPTNO FROM EMP;
DEPTNO
1
2
AIM: To study the various Constraint and wild card characters and implement them in the
database
INTEGRITY CONSTRAINT
An integrity constraint is a mechanism used by oracle to prevent invalid data entry into the
table. It has enforcing the rules for the columns in a table. The types of the integrity
constraints are:
a) Domain Integrity
b) Entity Integrity
c) Referential Integrity
a) Domain Integrity
This constraint sets a range and any violations that takes place will prevent the user from
performing the manipulation that caused the breach.It includes:
Example:
i. CREATE TABLE STUDENT(S_ID INT NOT NULL, NAME VARCHAR(60), AGE INT);
The above query will declare that the s_id field of Student table will not take NULL value.
This command will ensure that the user enters a value for the custid, name columns on the cust table, failing
which it returns an error message.
Check Constraint
Check constraint can be defined to allow only a particular range of values. When the
manipulation violates this constraint, the record will be rejected. Check condition cannot contain sub
queries.
Example:
i. Using CHECK constraint at Table Level
CREATE TABLE STUDENT(S_ID INT NOT NULL CHECK(S_ID > 0),NAME VARCHAR(60) NOT
NULL, AGE INT);
The above query will restrict the s_id value to be greater than zero.
Default constraint
The DEFAULT constraint is used to provide a default value for a column.
The default value will be added to all new records IF no other value is specified.
CREATE TABLE PERSONS (ID INT NOT NULL,LASTNAME VARCHAR2(55) NOT NULL,
FIRSTNAME VARCHAR2(55), AGE INT,CITY VARCHAR(55) DEFAULT 'SANDNES');
The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():
CREATE TABLE Orders (ID int NOT NULL, OrderNumber int NOT NULL,OrderDate date DEFAULT
GETDATE());
b) Entity Integrity
Maintains uniqueness in a record. An entity represents a table and each row of a table represents an instance
of that entity. To identify each row in a table uniquely we need to use this constraint. There are 2 entity
constraints:
Example:
CREATE TABLE CUST(CUSTID NUMBER(6) CONSTRAINT UNI UNIQUE, NAME CHAR(10));
ALTER TABLE CUST ADD(CONSTRAINT C UNIQUE(CUSTID));
The above query specifies that custid field of cust table will only have unique value
Example:
CREATE TABLE STUD(REGNO NUMBER(6) CONSTRAINT PRIMARY KEY, NAME CHAR(20));
Note: Can’t be defined using alter command when there is records in the table having null values.
c) Referential Integrity
It enforces relationship between tables. To establish parent-child relationship between 2 tables having a
common column definition, we make use of this constraint. To implement this, we should define the column
in the parent table as primary key and same column in the child table as foreign key referring to the
corresponding parent entry.
CUSTOMER_DETAIL TABLE :
C_ID CUSTOMER_NAME ADDRESS
101 ADAM NOIDA
102 ALEX DELHI
103 STUART ROHTAK
ORDER_DETAIL TABLE :
ORDER_ID ORDER_NAME C_ID
10 ORDER1 101
11 ORDER2 103
12 ORDER3 102
In CUSTOMER_DETAIL table, C_ID is the primary key which is set as foreign key in
ORDER_DETAIL table. The value that is entered in C_ID which is set as foreign key in
ORDER_DETAIL table must be present in CUSTOMER_DETAIL table where it is set as primary key.
This prevents invalid data to be inserted into C_ID column of ORDER_DETAIL table.
There are two ways to maintin the integrity of data in Child table, when a particular record is deleted in
main table. When two tables are connected with Foriegn key, and certain data in the main table is deleted,
for which record exit in child table too, then we must have some mechanism to save the integrity of data in
child table.
On Delete Cascade : This will remove the record from child table, if that value of foriegn key is
deleted from the main table.
On Delete Null : This will set all the values in that record of child table as NULL, for which the
value of foriegn key is deleted from the main table.
If we don't use any of the above, then we cannot delete data from the main table for which data in
child table exists. We will get an error if we try to do so.
ERROR : Record in child table exist
Wildcard Characters
A wildcard character is used to substitute any other character(s) in a string.
Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to
search for a specified pattern in a column.
There are two wildcards used in conjunction with the LIKE operator:
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3
'a_%_%' characters in length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
Example
Consider a “Customers" table :
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Ana Trujillo
Avda. de la México
2 Emparedados y Ana Trujillo 05021 Mexico
Constitución 2222 D.F.
helados
Antonio Moreno Antonio México
3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
Assignment. 4.
i. Create tables for Client, Product, and Salesman with the attributes given,
implementing DDL commands for specifying prime attributes, non-prime
attributes, foreign keys, cardinalities, null values, constraints etc. and the data types.
Implement DDL commands for drop, alter on the tables created.
ii. Implement DML commands like populating the tables with data using insert
command and retrieving data using simple queries in SQL. (Application of select,
update, delete etc.)
CLIENT_MASTER
PRODUCT_MASTER
SALESMAN_MASTER
SALES_ORDER
SALES_ORDER_DETAILS
ii>
2. Exercise on updating records in a table:
i. Change the city of client no ‘C001’ to ‘Bangalore’.
ii. Change the BalDue of client no ‘C006’ to Rs. 1000.
iii. Change the cost price of ‘Trousers’ to Rs. 950.00.
iv. Change the city of the salesman to ‘Pune’.
3. Add a column called ‘Telephone’ of data type number and size = 10 to the Client_Master
table.
4. Change the size of Sell_Price column in Product_Master to 10, 2.
5. Drop the column Cost_Price from Product_Master.
6. Delete all salesmen from the Salesman_Master whose salaries are equal to Rs. 3500.
7. Delete all products from Product_Master where the quantity on hand is equal to 100.
8. Delete from Client_Master where the column state holds the value ‘Tamil Nadu’.
9. Change the name of the Salesman_Master table to Sman_Mast.
10. Destroy the table Client_Master along with its data.
Function accept zero or more arguments and both return one or more results. Both are
used to manipulate individual data items. Operators differ from functional in that they
follow the format of function name(arg..). An argument is a user defined variables or
constants. Most operators accept at most 2 arguments while the structure of functions
permit to accept 3 or more arguments. Function can be classifies into:-
o Date Function
o Numeric Function
o Character Function
o Conversion Function
o Miscellaneous Function
The example that follows mostly uses the symbol table “dual”. It is a table, which is
automatically created by oracle along with the data dictionary.
Date Function
They operate on date values and produce outputs, which also belong to date data type
except for months, between, date function returns a number.
1. Add_month
This function returns a date after adding a specified date with specified number of months.
Syntax: Add_months(d,n); where d-date n-number of months
Example: Select add_months(sysdate,2) from dual;
2. last_day
It displays the last date of that month.
Syntax: last_day (d); where d-date
Example: Select last_day (‘1-jun-2009’) from dual;
3. Months_between
4. next_day
It returns a day followed the specified date.
Syntax: next_day (d,day);
Example: Select next_day (sysdate,’wednesday’) from dual
5. round
This function returns the date, which is rounded to the unit specified by the format model.
Syntax : round (d,[fmt]);
where d- date, [fmt] – optional. By default date will be rounded to the nearest day
Example: Select round (to_date(‘1-jun-2009’,’dd-mm-yy’),’year’) from dual;
Select round (‘1-jun-2009’,’year’) from dual;
Numerical Functions
Conversion Function
1. to_char()
Syntax: to_char(d,[format]);
This function converts date to a value of varchar type in a form specified by date format. If
format is negelected then it converts date to varchar2 in the default date format.
Example: select to_char (sysdate, ’dd-mm-yy’) from dual;
2. to_date()
Syntax: to_date(d,[format]);
This function converts character to date data format specified in the form character.
Example: select to_date(‘aug 15 2009’,’mm-dd-yy’) from dual;
Group Functions
A group function returns a result based on group of rows.
1. avg
Example: select avg (total) from student;
2.max
Example: select max (percentagel) from student;
3.min
Example: select min (marksl) from student;
4. sum
Example: select sum(price) from product;
Count Function
In order to count the number of rows, count function is used.
Group by clause
This allows us to use simultaneous column name and group functions.
Example: Select max(percentage), deptname from student group by deptname;
Having clause
This is used to specify conditions on rows retrieved by using group by clause.
Example: Select max(percentage), deptname from student group by deptname having
count(*)>=50;
Special Operators:
ii. Create tables for Employee, Company and works and populate them. Retrieve data by
writing nested queries in SQL using JOIN to combine tables and other operators like IN,
BETWEEN, LIKE etc.
Do the following query on the same table of Assignment No. 4 for 5.1
1. List the names of all clients having ‘a’ as the third letter in their names.
2. List the clients who stay in a city whose first letter is ‘K’.
3. List all the clients who stay in ‘Mumbai’ or ‘Kolkata’.
4. List all the clients whose BalDue is greater than value 1000.
5. List all information from the Sales_Order table for orders placed in the month of
June.
6. List the order information for Client_no ‘C00001’ and ‘C00003’.
7. List products whose selling price is greater than 500 and less than or equal to 750
Create the following tables and insert the values then do the queries for
5.2
employee: emp_no, name, dob, sex, address, salary
company: comp_no, name, address
works: emp_no, comp_no
Nested Queries:
Nesting of queries one within another is known as a nested queries.
Subqueries
The query within another is known as a subquery. A statement containing subquery is called
parent statement. The rows returned by subquery are used by the parent statement.
Example:
select ename, eno, address where salary >(select salary from employee where ename =’jones’);
Types
Sub queries can also return more than one value. Such results should be made use along with
the operators in and any.
Example: select ename, eno, from employee where salary <any (select salary from
employee where deptno =10’);
2. Multiple queries
Here more than one sub query is used. These multiple sub queries are combined by means of
‘and’ & ‘or’ keywords.
3. Correlated subquery
A subquery is evaluated once for the entire parent statement whereas a correlated
subquery is evaluated once per row processed by the parent statement.
Example: select * from emp x where x.salary > (select avg(salary) from emp where deptno =
x.deptno);
Above query selects the employees details from emp table such that the salary of employee
is > the average salary of his own department.
The purpose of a join concept is to combine data spread across tables. A JOIN clause is used to
combine rows from two or more tables, based on a related column between them.
Syntax: select columns from table1, table2 where logical expression;
a) Equi-join
A join, which is based on equalities, is called equi-join.
Example: select * from item, cust where item.id=cust.id;
In the above statement, item-id = cust-id performs the join statement. It retrieves rows
from both the tables provided they both have the same id as specified by the where clause.
Since the where clause uses the comparison operator (=) to perform a join, it is said to be
equijoin. It combines the matched rows of tables.
b) Non Equi-join
It specifies the relationship between columns belonging to different tables by making use of
relational operators other than’=’.
Example: select * from item, cust where item.id<cust.id;
Table Aliases
Table aliases are used to make multiple table queries shorted and more readable. We give
an alias name to the table in the ‘from’ clause and use it instead of the name throughout
the query.
Example
Orders table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Customers table:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Avda. de la
México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
The following SQL statement selects all orders with customer information:
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are records in the "Orders" table that do not have matches in
"Customers", these orders will not show!
Example
"Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Avda. de la
México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
"Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
The following SQL statement will select all customers, and any orders they might have:
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if there
are no matches in the right table (Orders).
Example
"Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
"Employees" table:
EmployeeID LastName FirstName BirthDate Photo
1 Davolio Nancy 12/8/1968 EmpID1.pic
2 Fuller Andrew 2/19/1952 EmpID2.pic
3 Leverling Janet 8/30/1963 EmpID3.pic
The following SQL statement will return all employees, and any orders they might have have
placed:
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even if
there are no matches in the left table (Orders).
Note: FULL OUTER JOIN can potentially return very large result-sets!
Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;
Example
"Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Avda. de la
México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
"Orders" table:
CustomerName OrderID
Alfreds Futterkiste 10308
Ana Trujillo Emparedados y helados 10365
Antonio Moreno Taquería 10382
Note: The FULL OUTER JOIN keyword returns all the rows from the left table (Customers), and
all the rows from the right table (Orders). If there are rows in "Customers" that do not have matches
in "Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows
will be listed as well.
Self Join
Joining of a table to itself is known as self-join. It joins one row in a table to another. It
can compare each row of the table to itself and also with other rows of the same table.
Syntax
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
Example
"Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
The following SQL statement matches customers that are from the same city:
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2,
A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
ii. Create tables, populate with data and construct queries (advanced) in SQL to extract
information from the car insurance company’s database.Consider a car-insurance company
whose customers own one or more cars each. Each car has associated with it zero to any
number of recorded accidents.
iii. Enter at least 5 sets of records in each table form created in part (ii).
iv. Write and run the following SQL queries for your database:
a. Find the total number of people who owned cars that were involved in accidents in 2010.
b. Find the number of accidents in which the cars belonging to “XYZ” were involved.
c. Add a new accident to the database; assume any values for required attributes.
d. Delete the model ‘Scorpio belonging to “ABC”.
e. Update the damage amount for the car with license number “AIBPC2010” in the accident
with report number “FIR271” to Rs. 5000.
Assignment.7.
I. Design an ER diagram for an application that models a hospital doctors treat patients,
prescribe tests, monitor progress etc. Analyze the requirements by identifying the entities,
attributes, relationships, keys, constraints etc. Apply extended entity-relationship features
to the design. Defend your design with proper assumptions and justifications. Map the ER
model into a relational model.
II. Create tables, populate with data and construct queries (advanced) in SQL to extract
information from the hospital doctor’s database.
III. Consider the following relations run the following SQL queries :
1. List the trade name of generic medicine with unit price less than $50.
2. List the first and last name of patients whose primary doctor named ʻJohn Smithʼ.
3. List the first and last name of doctors who are not primary doctors to any patient.
4. For medicines written in more than 20 prescriptions, report the trade name and the
total number of units prescribed.
5. List the SSN of patients who have ʻAspirinʼ and ʻVitaminʼ trade names in one
prescription.
6. List the SNN of distinct patients who have ʻAspirinʼ prescribed to them by doctor
named ʻJohn Smithʼ.
7. List the first and last name of patients who have no prescriptions written by doctors
other than their primary doctors.
PL/SQL
Aim: To combine database language and procedural programming language.
PL/SQL - FUNCTION
Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where, function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and types of the parameters. IN represents the
value that will be passed from outside and OUT represents the parameter that will be used to return
a value outside of the procedure.
The function must contain a return statement.
The RETURN clause specifies the data type you are going to return from the function.
function-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone function.
This function returns the total number of CUSTOMERS in the customers table.
RETURN total;
END;
/
Calling a Function
Following program calls the function totalCustomers from an anonymous block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
Output:Total no. of Customers: 6
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
/
Output: Factorial 6 is 720
PL/SQL - CURSOR
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds
is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors −
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit cursors
and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has
attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL
cursor has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS,
designed for use with the FORALL statement. The following table provides the description of
the most used attributes −
%FOUND
1
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or
a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the
example.
Example
We will be using the CUSTOMERS table we had created and used in the previous chapters.
Select * from customers;
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+ + + + + +
The following program will update the table and increase the salary of each customer by 500 and
use the SQL%ROWCOUNT attribute to determine the number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+ + + + + +
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created
on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
OPEN c_customers;
CLOSE c_customers;
Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
DECLARE
c_id customers.id%type;
c_name customerS.No.ame%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
PL/SQL – Procedures
A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the 'Modular design'. A subprogram
can be invoked by another subprogram or program which is called the calling program.
A subprogram can be created −
Each PL/SQL subprogram has a name, and may also have a parameter list. Like anonymous
PL/SQL blocks, the named blocks will also have the following three parts −
Declarative Part
1 It is an optional part. However, the declarative part for a subprogram does not start with the
DECLARE keyword. It contains declarations of types, cursors, constants, variables,
exceptions, and nested subprograms. These items are local to the subprogram and cease to
exist when the subprogram completes execution.
Executable Part
2
This is a mandatory part and contains statements that perform the designated action.
Exception-handling
3
This is again an optional part. It contains the code that handles run-time errors.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and OUT represents
the parameter that will be used to return a value outside of the procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on the
screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
Outuput: Procedure created.
The following table lists out the parameter modes in PL/SQL subprograms −
IN
An IN parameter lets you pass a value to the subprogram. It is a read-only parameter. Inside
1 the subprogram, an IN parameter acts like a constant. It cannot be assigned a value. You can
pass a constant, literal, initialized variable, or expression as an IN parameter. You can also
initialize it to a default value; however, in that case, it is omitted from the subprogram call. It
is the default mode of parameter passing. Parameters are passed by reference.
OUT
2 An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT
parameter acts like a variable. You can change its value and reference the value after assigning
it. The actual parameter must be variable and it is passed by value.
IN OUT
3 An IN OUT parameter passes an initial value to a subprogram and returns an updated value
to the caller. It can be assigned a value and the value can be read.
The actual parameter corresponding to an IN OUT formal parameter must be a variable, not a
constant or an expression. Formal parameter must be assigned a value. Actual parameter is
passed by value.
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/
Output: Square of (23): 529
I. Positional notation
II. Named notation
III. Mixed notation
Positional Notation
In positional notation, you can call the procedure as −
findMin(a, b, c, d);
In positional notation, the first actual parameter is substituted for the first formal parameter; the
second actual parameter is substituted for the second formal parameter, and so on. So, a is
substituted for x, b is substituted for y, c is substituted for z and d is substituted for m.
Named Notation
In named notation, the actual parameter is associated with the formal parameter using the arrow
symbol ( => ). The procedure call will be like the following −
findMin(x => a, y => b, z => c, m => d);
Mixed Notation
In mixed notation, you can mix both notations in procedure call; however, the positional notation
should precede the named notation.
The following call is legal −
findMin(a, b, c, m => d);
Assignment.8.
i. Implement a PL/SQL block that will accept student id number from the user, and check is
student attendance is less than 80% then display message that student cannot appear in exam.
[Table: STUDENT (STUD_ID, primary key, STUD_NAME, STUD_ATT)].
ii. Implement a PL/SQL code block that will accept an account number from the user. Check
if the user’s balance is less than the minimum balance, only then deduct Rs.100 from the
balance. The process is fired on the ACCT_MSTR table. [Table: ACCT_MSTR
(ACCT_NO, ACCT_HOLDR_NAME, CURBAL].
iii. Implement a PL/SQL code block to calculate the area of a circle for a value of radius varying
from 3 to 7. Store the radius and the corresponding values of calculated area in an empty
table named AREAS, consisting of two columns Radius and Area. [Table: AREAS
(RADIUS, AREA)].
iv. Implement a PL/SQL procedure that takes weight of an apple box as input from the user.
If the
weight is >= 10 kg, rate =Rs. 5/kg.
If weight is < 10 kg, rate = Rs. 7/kg.
Calculate the cost of the apple box. Display the output on the screen.
v. Implement a PL/SQL procedure to calculate the difference between highest salaried and
lowest salaried employee. Store the information in a table.
vi. Implement a PL/SQL block using cursor that will display the name, department and the
salary of the first 3 employees getting lowest salary. [Table: Employee (ename, dept, salary)]
vii. Implement a PL/SQL cursor that will update salary of all employees, such that, it allows an
increment of 20% if the salary is less than 2000 otherwise increment of Rs.1000. It should
print old and new salary for all employees. [Table: Employee (ename, dept, salary)]
Assignment.9.
Consider the following relations and Draw the ER, EER Diagram, Relational Model and
write the SQL statement for the following queries:
a) Find the names of all employees who work for Axis Bank.
b) Find the names and cities of residence of all employees who work for Axis Bank.
c) Find the names, street addresses, and cities of residence of all employees who work
for Axis Bank and earn more than Rs.30000 per annum.
d) Find all employees who live in the same city as the company for which they work is
located.
e) Find all employees who live in the same city and on the same street as their managers.
f) Find all employees in the database who do not work for Axis Bank.
g) Find all employees who earn more than every employee of Axis Bank.
h) Assume that the companies may be located in several cities. Find all companies
located in every city iin which Axis Bank is located.
i) Find all employees who earn more than the average salary of all employees of their
company.
l) Find those companies whose employees earn a higher salary, on average, than the
average salary at Axis Bank.
P) Give all managers in the database a 10 percent raise, unless the salary would be
greater than Rs.300000.In such cases, give only a 3 percent raise.
q) Delete all tuples in the works relation for employees of Axis Bank.
Assignment.10.
Consider the following tables:
MATCH (match_id, team1, team2, ground, mdate, winner)
PLAYER (p_id, lname, fname, country, yborn, bplace, ftest)
BATTING (match_id, p_id, mts, order, out_type, fow, nruns, nballs, fours, sixes)
BOWLING (match_id, p_id, novers, maidens, nruns, nwickets)
1. Draw the appropriate ER, EER and Relational model for the given data.
2. Write SQL expressions for the following:
i) Find match ids of those matches in which player 27001 bats and makes more runs than
he made at every match he played at Sydney.
ii) Find player ids of players who have scored more than 30 in every ODI match that they
have batted.
iii) Find the ids of players that had a higher average score than the average score for all
players when they played in Sri Lanka.
Assignment.11.
A record company wishes to use a computer database to help with its operations
regarding its performers, recordings and song catalogue. A requirements analysis has
elicited the following information: Songs have a unique song number, a non-unique title
and a composition date. A song can be written by a number of composers; the
composer’s full name is required. Songs are recorded by recording artists (bands or solo
performers). A song is recorded as a track of a CD. A CD has many songs on it, called
tracks. CDs have a unique record catalogue number, a title and must have a producer
(the full name of the producer is required). Each track must have the recording date and
the track number of the CD. • A song can appear on many (or no) CDs, and be recorded
by many different recording artists. The same recording artist might re-record the same
song on different CDs. A CD must have only 1 recording artist appearing on it. CDs can
be released a number of times, and each time the release date and associated number of
sales is required.
SQL:-
i>Update number of recorded album to 4 for those artist who has recorded only 3.
PL/SQL
Assignment.12.
1> Create the following tables.
Hotel (Hotel_No, Name, Address)
Room (Room_No, Hotel_No, Type, Price)
Booking (Hotel_No, Guest_No, Date_From, Date_To, Room_No)
Guest (Guest_No, Name, Address)
Populate the tables
Answer the following query using SQL.
1. List the names and addresses of all guests in London, alphabetically ordered by name
2. List all double or family rooms with a price below £40.00 per night, in ascending order of price.
3. List the bookings for which no date_to has been specified.
4. How many hotels are there?
5. What is the average price of a room?
6. What is the total revenue per night from all double rooms?
7. How many different guests have made bookings for August?
8. List the details of all rooms at the Grosvenor Hotel, including the name of the guest staying in the room,
if the room is occupied.
9. What is the total income from bookings for the Grosvenor Hotel today?
10. List the rooms that are currently unoccupied at the Grosvenor Hotel.
Design an ER Model for an application where hotels are booked by guests wanting to go on aholiday in
India or abroad. Your design should meet all requirements. Map into a relationalmodel.
DLOCATION (DNo,DLoc)
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.
C.Write a program in PL/SQL to create a cursor displays the name and salary of each employee in the EMPLOYEES
table whose salary is less than that specified by a passed-in parameter value.