You are on page 1of 80

S.A.

ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
VISION
To conceive our department as Centre of Academic Excellence by catering quality
education with ethical standards

MISSION
 To create a conducive atmosphere to achieve active professionalism by fortifying
academic proficiency with ethical standards
 To enhance the confidence level to develop sustainable solution to upgrade the
society forever
 To empower the students with prerequisite professional skills for enhancing
employability and entrepreneurship, continuing education and research

PROGRAMME EDUCATIONAL OBJECTIVES

1. Graduates shall have professional competency in the field of Computer Science


and Engineering for pursuing higher education, research or as entrepreneurs.
2. Graduates shall work in a business environment with ethical standards, leadership
qualities and communication necessary for engineering principles.
3. Graduates shall adapt to emerging technologies and respond to the challenges of
the environment and society forever.

PROGRAMME SPECIFIC OUTCOMES


1. To analyze, design and develop computing solutions by applying foundational
concepts of Computer Science and Engineering.
2. To apply software engineering principles and practices for developing quality
software for scientific and business applications.
3. To adapt to emerging Information and Communication Technologies (ICT) to
innovate ideas and solutions to existing/novel problems.
PROGRAMME OUTCOMES (POs)
Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

3. Design/development of solutions: Design solutions for complex engineering problems and


design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

4. Conduct investigations of complex problems: Use research-based knowledge and research


methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.

6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.

7. Environment and sustainability: Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

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.
IT1402 DATABASE MANAGEMENT SYSTEMS LABORATORY LTPC 0042

OBJECTIVES:

 To learn and implement important commands in SQL.


 To learn the usage of nested and joint queries.
 To understand functions, procedures and procedural extensions of databases.
 To understand design and implementation of typical database applications.
 To be familiar with the use of a front end tool for GUI based application development

Experiments:

1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating
and retrieving Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
3. Views, Sequences, Synonyms
4. Database Programming: Implicit and Explicit Cursors
5. Procedures and Functions
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any application
9. Create Document, column and graph based data using NOSQL database tools.
10. Develop a simple GUI based database application

OUTCOMES:

Upon completion of the course, the students will be able to:

 Use typical data definitions and manipulation commands.


 Design applications to test Nested and Join Queries
 Implement simple applications that use Views
 Critically analyze the use of Tables, Views, Functions and Procedures
 Implement a GUI application that require a Front-end and Back end Tool
 Create and manipulate data using NOSQL database.
S.A.ENGINEERING COLLEGE, CHENNAI-600 077

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

NAME OF FACULTY : Mr.M.Balasubramanian, Dr.R.Siva Subramanian, Mr.K.Swaminathan


YEAR/SEMESTER : II CSE A, B, C/IV
SUBJECT CODE/NAME: IT1402 - DATABASE MANAGEMENT SYSTEMS
LABORATORY
ACADEMIC YEAR : 2021-2022 (EVEN)
COURSE OBJECTIVES:
 To learn and implement important commands in SQL.
 To learn the usage of nested and joint queries.
 To understand functions, procedures and procedural extensions of databases.
 To understand design and implementation of typical database applications.
 To be familiar with the use of a front end tool for GUI based application development

COURSE OUTCOMES:

COs Course Outcomes Description

IT1402.1 Use typical data definitions and manipulation commands.


IT1402.2 Design applications to test Nested and Join Queries

IT1402.3 Implement simple applications that use Views, Sequences, Synonyms, Cursors and
critically analyze the use of Tables, Functions, Procedures, Triggers and
Exception Handling using PL/SQL
IT1402.4 Create and manipulate data using NOSQL database.
IT1402.5 Design database using ER modeling, Normalize and Implement a GUI application that require
a Front-end and Back end Tool

MAPPING OF COS WITH POs AND PSOs

PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO


1 2 3 4 5 6 7 8 9 10 11 12 1 2 3

IT1402.1 3 2 2 2 1 2 2
IT1402.2 3 2 2 2 1 2 2
IT1402.3 3 2 2 2 1 2 2 2
IT1402.4 3 3 3 3 2 1 2 2
IT1402.5 3 3 3 1 2 1 2 2
INDEX

Mapped Page
S.No. Date Name of the Experiment
CO No.

Data Definition Commands, Data Manipulation


1. Commands for inserting, deleting, updating and retrieving IT1402.1
Tables and Transaction Control statements

2. Database Querying – Simple queries, Nested queries, Sub IT1402.2


queries and Joins

3. Views, Sequences, Synonyms IT1402.3

4. Database Programming: Implicit and Explicit Cursors IT1402.3

5. Procedures and Functions IT1402.3

6. Triggers IT1402.3

7. Exception Handling IT1402.3

8. Database Design using ER modeling, normalization and


IT1402.5
Implementation for any application

9.
Create Document, column and graph based data using
NOSQL database tools IT1402.4

10. Develop a simple GUI based database application IT1402.5

All 10 experiments are completed as per syllabus and 10th experiment is implemented as a Mini
Project.

Signature of Faculty Incharge


EXP. NO: 1
DATE:

Data Definition Commands, Data Manipulation Commands for inserting,


deleting, updating and retrieving Tables and Transaction Control statements

AIM: To create a database and to write SQL queries to retrieve information from the database
and executing transaction control statements in RDBMS.

DEFINITIONS AND SYNTAX:


SQL:
SQL stands for Structured Query Language. SQL is composed of commands that enable users to
create database and table structures, perform various types of data manipulation and data
administration, and query the database to extract useful information.

DATA DEFINITION LANGUAGE (DDL)


The language used to define the database schema is called Data Definition language. DDL is
used to create, update and drop the database views. The Commands used in DDL are
 CREATE
 ALTER
 DROP

Create Table:
This command is used to create database tables in RDBMS.
Syntax
CREATE TABLE table_name (colname1 datatype, colname2 datatype,
colname3 datatype, …..…colnamen datatype);

Alter Table:
This command is used to add or drop or modify the attributes from the existing table.
Syntax

Adding an attribute:
ALTER TABLE <table_name> ADD column_name datatype;

Dropping an attribute:
ALTER TABLE <table_name> DROP COLUMN column_name;

Modifying an attribute:
ALTER TABLE <table_name> MODIFY column_name newdatatype;

Drop Table:
This command is used to remove a relation from an SQL database. This command deletes not
only the records of the table but also the entire schema of the database.
Syntax:
DROP TABLE <table_name>;

DML COMMANDS:

 Insert
 Select
 Update
 Delete

INSERT:

Insert command is used to insert the values into the table. There are three ways to insert a record
into the database.

1. Inserting Data’s in specified columns:

Syntax
INSERT INTO table_name(col1,col2,…….,coln)
VALUES(val1,val2,……,valn);

2. Inserting Values:

Syntax
INSERT INTO table_name VALUES(val1,val2,……...,valn);

3. Inserting Multiple Rows:

Syntax
INSERT INTO tablename VALUES(&col1,’&col2’,’&col3’,…….,&coln);

SELECT:

The select statement is used to query a database. This statement is used to retrieve the
information from the database. The SELECT statement can be used in many ways. They are:

1. Selecting some columns:


To select specified number of columns from the table the following command is used.

Syntax
SELECT column name FROM table_name;

2. Query All Columns:


To select all columns from the table * is used instead of column names.

Syntax
SELECT * FROM table_name;

UPDATE:

UPDATE command is used to change a value of a record in the database.

Syntax:

UPDATE table_name
SET column name =new value
WHERE column name=some value;

DELETE:

The DELETE statement is used to delete rows in a table.

Syntax:

DELETE FROM table_name


WHERE column name=some value;

SAVE POINT

A SAVEPOINT is a marker within a transaction that allows for a partial rollback. As changes are made in
a transaction, we can create SAVEPOINTs to mark different points within the transaction. If we
encounter an error, we can rollback to a SAVEPOINT or all the way back to the beginning of the
transaction.
Create a Save point:

Syntax

Savepoint <Save point name>;

Partial Rollback:

Syntax

Rollback to < Save point name>;


EXERCISES:

1. Create the following table with the given specifications.

a. Table name: Department

NAME TYPE

DNO NUMBER(4)

DNAME VARCHAR2(20)

b. Table name: EMPLOYEE

NAME TYPE

EID NUMBER(4)
NAME VARCHAR2(30)
DOB DATE
ADDR VARCHAR2(50)
PIN NUMBER(10)
SEX CHARACTER
DESIG VARCHAR2(25)
DEPTNO NUMBER(4)
MARISTA CHARACTER
SALARY NUMBER(8,2)

2. Add one additional field called manager to the department table

3. Change the data type of the field MARISTA to varchar2 (10)

4. Delete the field PIN from the EMPLOYEE table.

5. Delete the department table

1.Command for creating the table:

SQL> create table department


(dno number(4),
dname varchar2(20) );

Table created.
SQL> desc department;
Name Null? Type
----------------------------------------- -------- -----------------------
DNO NOT NULL NUMBER(4)
DNAME VARCHAR2(20)

SQL> create table employee


(eid number(4),
name varchar2(20),
dob date,
addr varchar2(50),
pin number(10),
sex char,
desig varchar2(15),
deptno number(4),
salary number(8,2));

Table created.

SQL> desc employee

Name Null? Type


----------------------------------------- -------- ----------------------------
EID NOT NULL NUMBER(4)
NAME VARCHAR2(20)
DOB DATE
ADDR VARCHAR2(50)
PIN NUMBER (10)
SEX CHAR (1)
DESIG VARCHAR2 (15)
DEPTNO NUMBER (4)
SALARY NUMBER (8,2)

2. Command for adding additional field:

SQL> alter table department add manager varchar2(25);


Table altered.

SQL> desc department

Name Null? Type


----------------------------------------- -------- ----------------------------
DNO NUMBER(4)
DNAME VARCHAR2(20)
MANAGER VARCHAR2(25)

3. Command for changing the data type of an attribute:

SQL> alter table employee modify PIN NUMBER(6);

Table altered.

SQL> desc employee


Name Null? Type
----------------------------------------- -------- ----------------------------
EID NUMBER(4)
NAME VARCHAR2(20)
DOB DATE
ADDR VARCHAR2(50)
PIN NUMBER(6)
SEX CHAR(1)
DESIG VARCHAR2(15)
DEPTNO NUMBER(4)
SALARY NUMBER(8,2)

4. Command to delete the field PIN

SQL> alter table employee drop column pin;

Table altered.

SQL> desc employee


Name Null? Type
----------------------------------------- -------- ----------------------------
EID NUMBER(4)
NAME VARCHAR2(20)
DOB DATE
ADDR VARCHAR2(50)
SEX CHAR(1)
DESIG VARCHAR2(15)
DEPTNO NUMBER(4)
SALARY NUMBER(8,2)

5. Command to drop the department table

SQL> drop table department;

Table dropped
CREATION OF TABLE:

SQL> CREATE TABLE STUDENT


(STUD_ID NUMBER (3),
STUD_NAME VARCHAR2(15),
STUD_DEPT VARCHAR2(5));

Table created.

SQL> DESC STUDENT;


Name Null? Type
----------------------------------------- -------- ----------------------------
STUD_ ID NUMBER(3)
STUD_NAME VARCHAR2(15)
STUD_DEPT VARCHAR2(5)

INSERTING VALUES INTO THE TABLE:

SQL> INSERT INTO STUDENT VALUES (&STUD_ID,'&STUD_NAME','&STUD_DEPT');

Enter value for STUD_ID: 001


Enter value for STUD_NAME: ABHI
Enter value for STUD_DEPT: CSE
old 1: INSERT INTO STUDENT VALUES(&STUD_ID,'&STUD_NAME','&STUD_DEPT')
new 1: INSERT INTO STUDENT VALUES(001,'ABHI','CSE')
1 row created.

SQL> /
Enter value for STUD_ID: 002
Enter value for STUD_NAME: ARUN
Enter value for STUD_DEPT: ECE
old 1: INSERT INTO STUDENT VALUES(&STUD_ID,'&STUD_NAME','&STUD_DEPT')
new 1: INSERT INTO STUDENT VALUES(002,'ARUN','ECE')
1 row created.

SQL> /
Enter value for STUD_ID: 003
Enter value for STUD_NAME: ARNAV
Enter value for STUD_DEPT: EEE
old 1: INSERT INTO STUDENT VALUES(&STUD_ID,'&STUD_NAME','&STUD_DEPT')
new 1: INSERT INTO STUDENT VALUES(003,'ARNAV','EEE')
1 row created.

SQL> /
Enter value for STUD_ID: 004
Enter value for STUD_NAME: ABHINAV
Enter value for STUD_DEPT: MECH
old 1: INSERT INTO STUDENT VALUES(&STUD_ID,'&STUD_NAME','&STUD_DEPT')
new 1: INSERT INTO STUDENT VALUES(004,'ABHINAV','MECH')
1 row created.

SQL> /
Enter value for STUD_ID: 005
Enter value for STUD_NAME: JAY
Enter value for STUD_DEPT: IT
old 1: INSERT INTO STUDENT VALUES(&STUD_ID,'&STUD_NAME','&STUD_DEPT')
new 1: INSERT INTO STUDENT VALUES(005,'JAY','IT')
1 row created.

SELECTING THE TABLE

SQL> SELECT * FROM STUDENT;

STUD_ID STUD_NAME STUD_DEPT


---------- -------------------- --------------------------
1 ABHI CSE
2 ARUN ECE
3 ARNAV EEE
4 ABHINAV MECH
5 JAY IT

UPDATE VALUES IN THE TABLE:

SQL> UPDATE STUDENT SET STUD_DEPT='CIVIL' WHERE STUD_DEPT='CSE';

1 row updated.

SQL> SELECT * FROM STUDENT;

STUD_ID STUD_NAME STUD_DEPT


---------- -------------------- --------------------------
1 ABHI CIVIL
2 ARUN ECE
3 ARNAV EEE
4 ABHINAV MECH
5 JAY IT
DELETE ONE OR MORE ROWS FROM A TABLE:

SQL> DELETE FROM STUDENT WHERE STUD_ID=1;


1 row deleted.

SQL> SELECT * FROM STUDENT;

STUD_ID STUD_NAME STUD_DEPT


-------------------------------------------------------------
2 ARUN ECE
3 ARNAV EEE
4 ABHINAV MECH
5 JAY IT

SAVE POINT:

SQL> select * from depmt;

ID SNAME SDEPT
---------- -------------------- --------------------
2 ARUN ECE
3 ARNAV EEE
4 ABHINAV MECH
5 JAY IT
SQL> insert into depmt values(6,'ABHI','MCA');
1 row created.

SQL>savepoint t1;
Savepoint created.

SQL> select * from depmt;


ID SNAME SDEPT
-------------------------------------------------------------
6 ABHI MCA
2 ARUN ECE
3 ARNAV EEE
8 ABHINAV MECH
5 JAY IT
5 rows selected.

SQL> insert into depmt values(7,'ASHU','MBA');


1 row created.
SQL> select * from depmt;
ID SNAME SDEPT
-----------------------------------------------------------
6 ABHI MCA
7 ASHU MBA
2 ARUN ECE
3 ARNAV EEE
8 ABHINAV MECH
5 JAY IT
6 rows selected.

SQL> rollback to t1;


Rollback complete.

SQL> select * from depmt;

ID SNAME SDEPT
--------------------------------------------------------------
6 ABHI MCA
2 ARUN ECE
3 ARNAV EEE
8 ABHINAV MECH
5 JAY IT

RESULT:
Thus the database is created and the information is well retrieved using SQL in RDBMS.
EXP. NO: 2
DATE:

Database Querying – Simple queries, Nested queries, Sub queries and Joins
AIM: To query a database using simple SQL queries, Nested queries, Sub queries and Joins in
RDBMS.

DEFINITION AND SYNTAX:

DATA MANIPULATION LANGUAGE (DML):

The language used to manipulate data is called DML Manipulation of data includes the insertion
of data into the database, modification of data stored in the database, deletion of data from the
database and retrieval of data for further process. The commands used are
 Insert
 Update
 Delete

QUERY:

Query is a statement in the DML that request the retrieval of data from database. The portion of
the DML used in a Query is called Query language. The SELECT statement is used to query a
database.

INSERT:

Insert command is used to insert the values into the table. There are three ways to insert a record
into the database.

1. Inserting Data’s in specified columns:

Syntax:
INSERT INTO table_name(col1,col2,…….,coln)
VALUES(val1,val2,……,valn);

2. Inserting Values:

Syntax:
INSERT INTO table_name VALUES(val1,val2,……...,valn);

3. Inserting Multiple Rows:


Syntax:

INSERT INTO tablename VALUES(&col1,’&col2’,’&col3’,…….,&coln);

UPDATE:

UPDATE command is used to change a value of a record in the database.

Syntax:

UPDATE table_name
SET column name =new value
WHERE column name=some value;

DELETE:

The DELETE statement is used to delete rows in a table.

Syntax:

DELETE FROM table_name


WHERE column name=some value;

SELECT:

The select statement is used to query a database. This statement is used to retrieve the
information from the database. The SELECT statement can be used in many ways. They are:

1. Selecting some columns:


To select specified number of columns from the table the following command is used.

Syntax:
SELECT column name FROM table_name;

2. Query All Columns:

To select all columns from the table * is used instead of column names.

Syntax:

SELECT * FROM table_name;

3. Select using DISTINCT:

The DISTINCT keyword is used to return only different values (i.e. ) this command does
not select the duplicate values from the table .
Syntax:
SELECT DISTINCT column name(s) FROM table_name;

4. Select using IN:

If you want to get the rows, which contain certain values, the best way to do it is to use
the IN conditional expression.

Syntax:
SELECT column name(s) FROM table_name WHERE
Column name IN(value1,value2,……,value n);

5. Select using BETWEEN:

BETWEEN can be used to get those items that fall within a range.

Syntax:
SELECT column name FROM table_name WHERE
Column name BETWEEN value1 AND value2;

6. Creating a alias for a column:

The select statement can be used to rename either a column or the entire table.

Syntax: Renaming a column:

SELECT column name AS new name FROM table_name;

7. Sorting:

The select statement with the order by Clause is used to sort the contents of the table
either in ascending or descending order.

Syntax:
SELECT column name FROM table_name WHERE
Condition ORDER BY column name ASC/DESC;

8. To Select by matching some patterns:

The select statement along with like clause I is used to match strings. The like condition
is used to specify a search pattern in a column.
Syntax:

SELECT column name FROM table_name WHERE


Column name LIKE “% or-“;
% : Matches any sub string.
- : Matches a single character.

9. To Select NULL values:

We can use the SELECT statement to select the ‘null’ values also. For retrieving
rows where some of the columns have been defined as NULLs there is a special
comparison operator of the form IS[NOT]NULL.

Syntax:
SELECT column name FROM table_name WHERE
Column name IS NULL;

10. Select using AND, OR, NOT:

We can combine one or more conditions in a SELECT statement using the logical
operators AND,OR,NOT.

Syntax:
SELECT column name FROM table_name WHERE
Condition1 LOGICAL OPERATOR condition2;

JOIN

This command is used for joining two or more relations into a single relation. It is of two
types namely,
 Inner join
 Full Outer join
*Left Outer Join
*Right Outer Join

1) INNER JOIN

Only pairs of tuples that match the join condition are retrieved from the two different
relations.
Syntax:
SELECT <attribute names> from ( <table name1> INNER JOIN <tablename2> on
<condition>);
2) FULL OUTER JOIN

Every tuple in the left table and right table must appear in the result; if it does not have a
matching tuple, it is padded with NULL values.
Syntax:
SELECT <attribute name> from ( <table name1> FULL OUTER JOIN <tablename2> on
<condition>);

LEFT OUTER JOIN

Every tuple in the left table must appear in the result; if it does not have a matching tuple,
it is padded with NULL values for the attributes of the right table
Syntax:
SELECT <attribute name> from ( <table name1> LEFT OUTER JOIN <tablename2> on
<condition>);

RIGHT OUTER JOIN

Every tuple in the right table must appear in the result; if it does not have a matching
tuple, it is padded with NULL values for the attributes of the left table
Syntax:
SELECT <attribute name> from ( <table name1> RIGHT OUTER JOIN <tablename2> on
<condition>);
EXERCISES:

CREATION OF TABLE:

SQL> CREATE TABLE STUDENT


(STUD_ID NUMBER (3),
STUD_NAME VARCHAR2(15),
STUD_DEPT VARCHAR2(5));

Table created.

SQL> DESC STUDENT;


Name Null? Type
----------------------------------------- -------- ----------------------------
STUD_ ID NUMBER(3)
STUD_NAME VARCHAR2(15)
STUD_DEPT VARCHAR2(5)

INSERTING VALUES INTO THE TABLE:

SQL> INSERT INTO STUDENT VALUES (&STUD_ID,'&STUD_NAME','&STUD_DEPT');

Enter value for STUD_ID: 001


Enter value for STUD_NAME: ABHI
Enter value for STUD_DEPT: CSE
old 1: INSERT INTO STUDENT VALUES(&STUD_ID,'&STUD_NAME','&STUD_DEPT')
new 1: INSERT INTO STUDENT VALUES(001,'ABHI','CSE')
1 row created.

SQL> /
Enter value for STUD_ID: 002
Enter value for STUD_NAME: ARUN
Enter value for STUD_DEPT: ECE
old 1: INSERT INTO STUDENT VALUES(&STUD_ID,'&STUD_NAME','&STUD_DEPT')
new 1: INSERT INTO STUDENT VALUES(002,'ARUN','ECE')
1 row created.

SQL> /
Enter value for STUD_ID: 003
Enter value for STUD_NAME: ARNAV
Enter value for STUD_DEPT: EEE
old 1: INSERT INTO STUDENT VALUES(&STUD_ID,'&STUD_NAME','&STUD_DEPT')
new 1: INSERT INTO STUDENT VALUES(003,'ARNAV','EEE')
1 row created.

SQL> /
Enter value for STUD_ID: 004
Enter value for STUD_NAME: ABHINAV
Enter value for STUD_DEPT: MECH
old 1: INSERT INTO STUDENT VALUES(&STUD_ID,'&STUD_NAME','&STUD_DEPT')
new 1: INSERT INTO STUDENT VALUES(004,'ABHINAV','MECH')
1 row created.

SQL> /
Enter value for STUD_ID: 005
Enter value for STUD_NAME: JAY
Enter value for STUD_DEPT: IT
old 1: INSERT INTO STUDENT VALUES(&STUD_ID,'&STUD_NAME','&STUD_DEPT')
new 1: INSERT INTO STUDENT VALUES(005,'JAY','IT')
1 row created.

SELECTING A TABLE:

SQL> SELECT * FROM STUDENT;

STUD_ID STUD_NAME STUD_DEPT


---------- -------------------- --------------------------
1 ABHI CSE
2 ARUN ECE
3 ARNAV EEE
4 ABHINAV MECH
5 JAY IT

UPDATE VALUES IN A TABLE:

SQL> UPDATE STUDENT SET STUD_DEPT='CIVIL' WHERE STUD_DEPT='CSE';

1 row updated.

SQL> SELECT * FROM STUDENT;

STUD_ID STUD_NAME STUD_DEPT


---------- -------------------- --------------------------
1 ABHI CIVIL
2 ARUN ECE
3 ARNAV EEE
4 ABHINAV MECH
5 JAY IT
DELETE ONE OR MORE ROWS FROM A TABLE:

SQL> DELETE FROM STUDENT WHERE STUD_ID=1;


1 row deleted.

SQL> SELECT * FROM STUDENT;

STUD_ID STUD_NAME STUD_DEPT


-------------------------------------------------------------
2 ARUN ECE
3 ARNAV EEE
4 ABHINAV MECH
5 JAY IT

JOINS

1. Create the following tables with the given specifications and insert few records in both the
relations.

a. Table name: STUDENT

NAME DATATYPE CONSTRAINTS

PROD_ID NUMBER(3) Primary Key


P_NAME VARCHAR2(10) NOT NULL
QUANTITY NUMBER(2)

b. Table name: DEPT

NAME TYPE CONSTRAINTS


CUST_ID NUMBER(2) PRIMARY KEY
CUST_NAME VARCHAR2(10) NOT NULL
P_ID NUMBER(2) PRIMARY KEY

2. Write a SQL query to execute INNER JOIN on both the relations and record the output.
3. Write a SQL query to execute LEFT OUTER JOIN on both the relations and record the
output.
4. Write a SQL query to execute RIGHT OUTER JOIN on both the relations and record the
output.
5. Write a SQL query to execute FULL OUTER JOIN on both the relations and record the
output.

OUTPUT:

Creation of Base Table- Product Details

SQL> create table product_details(prod_id number(2),p_name varchar(10),quantity


number(2),primary key(prod_id));

Table created.

SQL> desc product_details;


Name Null? Type
----------------------------------------- -------- ----------------------------

PROD_ID NOT NULL NUMBER(2)


P_NAME VARCHAR2(10)
QUANTITY NUMBER(2)

Inserting values in to the Base Table

SQL> insert into product_details values(&prod_id,'&p_name',&quantity);


Enter value for prod_id: 10
Enter value for p_name: pencil
Enter value for quantity: 25
old 1: insert into product_details values(&prod_id,'&p_name',&quantity)
new 1: insert into product_details values(10,'pencil',25)

1 row created.

SQL> /
Enter value for prod_id: 20
Enter value for p_name: eraser
Enter value for quantity: 30
old 1: insert into product_details values(&prod_id,'&p_name',&quantity)
new 1: insert into product_details values(20,'eraser',30)

1 row created.

SQL> /
Enter value for prod_id: 30
Enter value for p_name: pen
Enter value for quantity: 35
old 1: insert into product_details values(&prod_id,'&p_name',&quantity)
new 1: insert into product_details values(30,'pen',35)

1 row created.
SQL> /
Enter value for prod_id: 40
Enter value for p_name: compass
Enter value for quantity: 45
old 1: insert into product_details values(&prod_id,'&p_name',&quantity)
new 1: insert into product_details values(40,'compass',45)

1 row created

Retrieving Information from Base Table

SQL> select * from product_details;

PROD_ID P_NAME QUANTITY


---------- ---------- -------- ----------------
10 pencil 25
20 eraser 30
30 pen 35
40 compass 45

Creation of Sub Table- Customer Order

SQL> create table cust_order(cust_id number(3),cust_name varchar2(10),p_id numbe


r(2),primary key(cust_id),foreign key(p_id) references product_details(prod_id))
;

Table created.

SQL> desc cust_order;


Name Null? Type
---------------------------------- ------- ------------------------------

CUST_ID NOT NULL NUMBER(3)


CUST_NAME VARCHAR2(10)
P_ID NUMBER(2)

Inserting values in to the Sub Table

SQL> insert into cust_order values(&cust_id,'&cust_name',&p_id);


Enter value for cust_id: 111
Enter value for cust_name: abhi
Enter value for p_id: 10
old 1: insert into cust_order values(&cust_id,'&cust_name',&p_id)
new 1: insert into cust_order values(111,'abhi',10)

1 row created.

SQL> /
Enter value for cust_id: 222
Enter value for cust_name: arun
Enter value for p_id: 30
old 1: insert into cust_order values(&cust_id,'&cust_name',&p_id)
new 1: insert into cust_order values(222,'arun',30)

1 row created.

SQL> /
Enter value for cust_id: 333
Enter value for cust_name: joy
Enter value for p_id: 20
old 1: insert into cust_order values(&cust_id,'&cust_name',&p_id)
new 1: insert into cust_order values(333,'joy',20)

1 row created.

Retrieving Information from Sub Table

SQL> select * from cust_order;

CUST_ID CUST_NAME P_ID


---------- ---------- ---------- ------------
111 abhi 10
222 arun 30
333 joy 20

Performing INNER JOIN

SQL> select * from(product_details P inner join cust_order C on P.prod_id=C.p_id


;

PROD_ID P_NAME QUANTITY CUST_ID CUST_NAME P_ID


--------- ---------- ---------- ---------- ---------- -------------------------------------
10 pencil 25 111 abhi 10
30 pen 35 222 arun 30
20 eraser 30 333 joy 20
Performing LEFT OUTER JOIN

SQL> select * from(product_details P left outer join cust_order C on P.prod_id=C


p_id);

PROD_ID P_NAME QUANTITY CUST_ID CUST_NAME P_ID


--------- ---------- ---------- ---------- ---------- ------- ----------------- --------
10 pencil 25 111 abhi 10
30 pen 35 222 arun 30
20 eraser 30 333 joy 20
40 compass 45

Performing RIGHT OUTER JOIN

SQL> select * from(product_details P right outer join cust_order C on P.prod_id=


.p_id);

PROD_ID P_NAME QUANTITY CUST_ID CUST_NAME P_ID


--------- ---------- ---------- ---------- ---------- ------- ----------------- ---------
10 pencil 25 111 abhi 10
30 pen 35 222 arun 30
20 eraser 30 333 joy 20

Performing FULL OUTER JOIN

SQL> select * from(product_details P full outer join cust_order C on P.prod_id=C


p_id)
2 ;

PROD_ID P_NAME QUANTITY CUST_ID CUST_NAME P_ID


--------- ---------- ---------- ---------- ---------- ------- ----------------- --------
10 pencil 25 111 abhi 10
20 eraser 30 333 joy 20
30 pen 35 222 arun 30

MERITS:

 More readable, as the JOIN criteria is separate from the WHERE clause
 The main advantage of a join is that it executes faster and provides more information of a
particular tuple.

DEMERITS:

 A disadvantage of using joins is that they are not as easy to read as sub queries.
 Another disadvantage is that it can be confusing as to which relation the appropriate type
of join to use to yield the correct desired result set.

URL:

 http://www.ehow.com/info_8700587_advantages-disadvantages-join-subquery.html
 http://stackoverflow.com/questions/2241991/in-mysql-queries-why-use-join-instead-of-
where
 http://ask.sqlservercentral.com/questions/91760/inner-join-vs-a-select-with-a-bunch-of-
tables-spec.html
 http://www.techbubbles.com/sql-server/sql-server-joins-or-subqueries/
 http://www.databasejournal.com/features/mssql/article.php/3623916/MS-SQL-Joins-
Part-2.htm

VIVA QUESTIONS:

1. What is a join?
2. Differentiate inner join from outer join.
3. What is the need for joining relations?

RESULT:
Thus simple SQL queries, Nested queries, Sub queries and Joins are successfully
executed in RDBMS.
EXP NO: 3
DATE:

Views, Sequences, Synonyms


AIM: To create views, sequences and synonyms in RDBMS.

VIEW
Views are used to provide security for the data. They provide a virtual image for a database.
#Create View:
This command is used to create database view in RDBMS.
Syntax
CREATE VIEW view_name as select <columnname> from <tablename>;
#Update View:
This command is used to change a value of a record in the database.

Syntax

UPDATE view_name SET column name =new value WHERE column name=some value;

#Drop View:
Drop command is used to drop the view.

Syntax

DROP view view_name;

SYNONYM
Description

A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and
other database objects.

Syntax

The syntax to create a synonym in Oracle is:

CREATE OR REPLACE SYNONYM <synonym_name> FOR <object name>;


OR REPLACE allows you to recreate the synonym (if it already exists) without having to issue a DROP
synonym command. The object_name is the name of the object for which you are creating the synonym.
It can be one of the following:

 table
 view
 sequence
 stored procedure
 function
 synonym

Drop Synonym:

Once a synonym has been created in Oracle, you might at some point need to drop the synonym.

Syntax

The syntax to drop a synonym in Oracle is:

DROP SYNONYM <synonym_name>;

SEQUENCES (AUTONUMBER)

Learn how to create and drop sequences in Oracle with syntax and examples.

Description

In Oracle, you can create an auto number field by using sequences. A sequence is an object in Oracle that
is used to generate a number sequence. This can be useful when you need to create a unique number to act
as a primary key.

Create Sequence:

You may wish to create a sequence in Oracle to handle an auto number field.

Syntax

The syntax to create a sequence in Oracle is:


CREATE SEQUENCE sequence_name
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;

Using Sequences:

<sequence name>.NEXTVAL;

INSERT INTO <tablename> VALUES (<sequence name>.NEXTVAL);

Drop Sequence:

Once you have created your sequence in Oracle, you might find that you need to remove it from the
database.

Syntax

The syntax to a drop a sequence in Oracle is:

DROP SEQUENCE <sequence_name>;

sequence_name is the name of the sequence that you wish to drop.


OUTPUT:

CREATE VIEW:
SQL> create view depview as select id,sname from depmt;
View created.

SQL> select * from tab;

TNAME TABTYPE CLUSTERID


------------------------------ ------- -----------------------------
STUD TABLE
EPP TABLE
EMPL TABLE
EMP TABLE
DVIEW VIEW
DEPMT TABLE

SQL> select * from depview;

ID SNAME
---------- -----------------------------
6 ABHI
2 ARUN
3 ARNAV
4 ABHINAV
5 JAY

UPDATE VIEW:
SQL> update depview set id=8 where id=4;
1 row updated.

SQL> select * from depview;

ID SNAME
---------- ----------------------------
6 ABHI
2 ARUN
3 ARNAV
8 ABHINAV
5 JAY

DROP VIEW:
SQL> drop view depview;
View dropped.
SQL> select * from depview;
ERROR at line 1:
ORA-00942: table or view does not exist

SQL> select * from tab;

TNAME TABTYPE CLUSTERID


------------------------------ ------- ----------
STUD TABLE
EPP TABLE
EMPL TABLE
EMP TABLE
DEPMT TABLE

SYNONYM:
SQL> create synonym d for depmt;
Synonym created.

SQL> select * from tab;

TNAME TABTYPE CLUSTERID


------------------------------ ------- ----------
STUD TABLE
EPP TABLE
EMPL TABLE
EMP TABLE
DEPMT TABLE
D SYNONYM

SQL> select * from d;


ID SNAME SDEPT
---------- -------------------- --------------------
6 ABHI MCA
2 ARUN ECE
3 ARNAV EEE
8 ABHINAV MECH
5 JAY IT

DROP SYNONYM:
SQL> DROP synonym d;
Synonym dropped.
SQL> select * from tab;

TNAME TABTYPE CLUSTERID


------------------------------ ------- -------------------
STUD TABLE
EPP TABLE
EMPL TABLE
EMP TABLE
DEPMT TABLE

SEQUENCES:

SQL> create table stu(sid number(3),sname varchar2(10));


Table created.

SQL> select * from tab;

TNAME TABTYPE CLUSTERID


------------------------------ ------- -------------------
STUD TABLE
EPP TABLE
EMPL TABLE
EMP TABLE
DEPMT TABLE
STU TABLE

CREATE SEQUENCE:

SQL> create sequence seq_stud minvalue 100 maxvalue 999 start with 100 increment
by 2 cache 20;
Sequence created.

SQL> insert into stu values(seq_stud.nextval,'&sname');


Enter value for sname: abhi
old 1: insert into stu values(seq_stud.nextval,'&sname')
new 1: insert into stu values(seq_stud.nextval,'abhi')
1 row created.

SQL> /
Enter value for sname: arun
old 1: insert into stu values(seq_stud.nextval,'&sname')
new 1: insert into stu values(seq_stud.nextval,'arun')
1 row created.
SQL> select * from stu;

SID SNAME
---------- --------------------
102 abhi
104 arun

DROP SEQUENCE:
SQL> drop sequence seq_stud;
Sequence dropped.

RESULT:
Thus Views, Sequences and Synonyms have been created and updated in
RDBMS.
Ex. No: 4
Date:

Database Programming: Implicit and Explicit Cursors

AIM:
To implement implicit and explicit cursors using PL/SQL programs.

Hardware Requirements:
 Pentium IV Processor
 2 GB RAM

Software Requirements:
 Windows 7 or above
 Oracle
 Visual Basic 6.0

DEFINITION AND SYNTAX:

1. PL/SQL:
PL/SQL stands for procedural structural language/SQL. PL/SQL
extends SQL by adding control structures found in other structural languages. PL/SQL
can be used in the Oracle relational database in the Oracle server and in the client side
application development tools.

SYNTAX:
A PL/SQL block can be divided into three parts namely, a
declarative part, an executable part and an exception handling part. The order is shown
below:
DECLARE

Declarations

BEGIN

Executable Statements

EXCEPTION

Handlers

END;
Objects can be declared in the declarative part, which can be used, in the
executable part for further manipulations. All procedural statements are included between
the BEGIN and END statements. Errors that occur during the execution are handled by
the exception handlers.

2. ATTRIBUTES:
Attributes allows us to refer data types and objects from
database. PL/SQL constants and variables can have attributes. The following are the
types of attributes supported by the PL/SQL.

 %type
 %row type
%type:
%type is used when declaring variables that refer to database columns.

SYNTAX:

Variablename tablename. Colname %type

%rowtype:
%rowtype attributes provides a record type that represents a row in the table. The
record can store an entire row of data selected from the table or fetched by a cursor.

SYNTAX:

Variablename tablename %rowype;

3. CURSORS:
Oracle allocates a memory known as the context area for the processing
of the SQL statements. A cursor is a pointer or handle to the context area. Through the
cursor, a PL/SQL program can control the context area and what happens to it as the
statement is processed.

The three types of the cursors are

 Static cursors
 Dynamic cursors
 REF cursors
Static cursors are the ones whose select statements are known at the compile time. These
are further classified into

 Explicit cursors
 Implicit cursors
4. EXPLICIT CURSORS:
The set of rows returned by a query can contain zero or multiple
rows depending on the query defined. These rows are called the active set. The cursor
will point to the current row in the active set.

After declaring a cursor, we can use the following commands to control the
cursor.

 Open
 Fetch
 Close

The ‘open’ statement executes the query, identifies the active set and positions the
cursor before the first row. The syntax is given below:

Open <cursor_name>;

The ‘fetch’ statement retrieves the current row and advances the cursor to the next
row to fetch the remaining rows. The syntax is given below:

Fetch <cursor_name> into <column_name>;

After processing the last row in the active set, the cursor is disabled with the help
of the ‘close’ command. The syntax is as follows:

Close <cursor_name>;

5. CURSOR ATTRIBUTES:
Explicit cursor attributes when appended to the cursor name
allows us to access useful information from the retrieved rows.
They are:

 %notfound
 %found
 %rowcount
 %isopen
%Notfound:

after opening the cursor , a fetch is used to fetch the rows from the active set, one
at a time. The attribute %notfound indicates whether fetch statements returns row from
the active set. If the last ‘fetch’ fails to return a row, then %notfound evaluates to true,
else, it evaluates to false.

%found:
It evaluates to true if the last ‘fetch’ statement succeeds in returning a row. It
would be evaluated to false if the last ‘fetch’ statement fails to return a row because no
rows were available.

%rowcount:
The %rowcount is used to return the number of rows fetched. Before the first
fetch, %rowcount is zero.

%isopen:
if the cursor is already open, then the attribute %isopen evaluates to true, else it
evaluates to false.

/*PL/SQL to update the details of employee using cursors*/

SQL>declare
cursor emp is select * from employee where marista='m';
dno employee.deptno%type;
a employee%rowtype;
begin
dno:=&dno;
open emp;
loop
fetch emp into a;
update employee set salary=salary+500 where deptno=dno;
exit when emp%notfound;
end loop;
end;
/

OUTPUT:

Enter value for dno: 2


old 6: dno:=&dno;
new 6: dno:=2;

PL/SQL procedure successfully completed.


SQL> select * from employee where marista='m' and deptno=2;

EID NAME DOB ADDR S DESIG DEPTNO M


---------- ---------- --------- ---------- - ------------ ---------- -
SALARY
----------
7567 balu 11-NOV-81 chennai m cashier 2m
16000

4444 sunil 21-DEC-81 delhi m cashier 2m


13000

RESULT:

Thus implicit and explicit cursors using PL/SQL were executed successfully.
Ex. No: 5
Date:

PROCEDURES AND FUNCTIONS


OBJECTIVE:
To study and execute the procedures and functions using control structures in PL/SQL.

HARDWARE REQUIREMENTS:
Processor Type : Pentium IV
RAM : 1 GB
Hard Disk : 80GB
Frequency : 1.60 GHZ

SOFTWARE REQUIREMENTS:
Front End : VB/VC ++/JAVA or equivalent
Back End : Oracle /SQL /MySQL/PostGress /DB2 or equivalent
Platform : Windows/XP, Windows 7 or its higher versions

PROBLEM DEFINITION:
The main concept is to understand the how procedures are created and implemented in
PL/SQL .

BASIC TERMINOLOGIES:
PL/SQL
PL/SQL stands for Procedural Language extension of SQL.PL/SQL is a combination
of SQL along with the procedural features of programming languages. It was developed by
Oracle Corporation in the early 90’s to enhance the capabilities of SQL.

PL/SQL Engine
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be
stored in the client system (client-side) or in the database (server-side).

A SIMPLE PL/SQL BLOCK

Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block.

PL/SQL Block consists of three sections:

 The Declaration section (optional).


 The Execution section (mandatory).
 The Exception (or Error) Handling section (optional).

Syntax PL/SQL Block Looks


DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;

PROCEDURES

A procedure is a subprogram that performs a specific action.

Syntax for creating a procedure:.


create or replace procedure <Proc_name> [parameter list] is

<local declarations>;
begin

(executable statements)
[exception] (exception handlers)

end;
A procedure has two parts, namely, specification and body. The procedure specification
begins with the keyword procedure and ends with the procedure name or parameter list. The
procedure body begins with the keyword is and ends with the keyword end. It can also include
declarative, executable and exceptional parts within the keywords are and end.

Syntax to execute a procedure

SQL > exec < proc_name> (parameters);

FUNCTIONS

A function is a subprogram that computes a value.The syntax for creating a function is given
below.

create or replace function <function_name> [argument]


return datatype is
(local declaration)
begin
(exectable statements)
[Exception]
(exception handlers)
end;

where arguments can be in, out or inout.

Similar to a procedure, a function also has two parts, namely, the function specification
and the function body. The function specification begins with the keyword function and ends
with the return clause. The function body begins with the keyword is and ends with the keyword
end. A PL/SQL block can also be included in a function body.
EXERCISES:

1) To create a procedure to display the salary of the specified employee from employee
table

SQL> create or replace procedure proc1(A in number)is


2 sal number(7,2);
3 begin
4 select salary into sal from emp where id=A;
5 dbms_output.put_line('Salary is'||sal);
6 end;
7/

Procedure created.
OUTPUT

SQL> set serveroutput on;


SQL> exec proc1(11);
Salary is20000

2) To create a PL/SQL program which calls a procedure to print 0 if salary is less than
15000 else print 1.

Contents of Emp table


SQL> select * from emp;

ID NAME DESIG SEX SALARY


---------- -------------------- -------------------- ---------- ----------
11 abhi hr male 20000
22 arun ceo male 30000
33 deepak executive male 10000

SQL> create or replace procedure proc2(A in number,B out number) is


2 sal number;
3 begin
4 select salary into sal from emp where id=A;
5 if(sal<15000)then
6 B:=0;
7 else
8 B:=1;
9 end if;
10 end proc2;
11 /
Procedure created.

SQL> declare
2 A number;
3 B number;
4 begin
5 A:=&A;
6 proc2(A,B);
7 Dbms_output.put_line('B value is:'||B);
8 end;
9 /

OUTPUT:
Enter value for a: 22
old 5: A:=&A;
new 5: A:=22;
B value is:1

PL/SQL procedure successfully completed.

SQL> /
Enter value for a: 33
old 5: A:=&A;
new 5: A:=33;
B value is:0

PL/SQL procedure successfully completed.

3) To create and execute a function to multiply the given number by 1000

SQL> create or replace function f1(n number)return


2 number is
3 k number;
4 begin
5 k:=n*1000;
6 return k;
7 end;
8 /

Function created.

OUTPUT

SQL> select f1(5) from dual;


F1(5)
----------
5000
SQL> select * from dual;
D
-
X
4) To create and execute a factorial program using function

SQL> CREATE OR REPLACE FUNCTION F1(N NUMBER)RETURN


2 NUMBER IS
3 F NUMBER;
4 BEGIN
5 F:=1;
6 FOR I IN 1..N LOOP
7 F:=F*I;
8 END LOOP;
9 RETURN F;
10 END;
11 /

Function created.
OUTPUT

SQL> SELECT F1(5) FROM DUAL;

F1(5)
----------
120

MERITS:

PROCEDURES

 Stored procedures are compiled once and stored in executable form, so procedure calls
are quick and efficient.
 Executable code is automatically cached and shared among users.
 By grouping SQL statements, a stored procedure allows them to be executed with a
single call.

FUNCTIONS

 The ability to store functions within the Oracle database allows you to reach great heights
in modularity, maintainability, and performance improvement. Using functions to
accomplish specific tasks improves the reliability of other modules and reduces
development time.

DEMERITS:

 Limited coding functionality


 Testing
 Portability

URLs:

 http://www.dbforums.com/db2/972602-advanteges-disadvanteges-check-
constraints-triggers-stored-procedures.html
 http://sqlperformance.com/2012/11/t-sql-queries/benefits-indexing-foreign-
keys
 http://docs.oracle.com/cd/E18283_01/server.112/e16508/datainte.htm
 http:/www.javas.com/oracle/catalog/index.html

VIVA QUESTIONS:

1. What is a PL/SQL?
2. Give the structure of Procedure?
3. Give the merits and demerits of using the procedure.

RESULT:

Thus the procedures and functions using control structures were studied and executed in
PL/SQL.
Ex. No: 06
Date:

TRIGGERS
OBJECTIVE:
To study and execute Triggers in RDBMS.

HARDWARE REQUIREMENTS:
Processor Type : Pentium IV
RAM : 2 GB
Hard Disk : 500 GB
Frequency : 1.60 GHZ

SOFTWARE REQUIREMENTS:
Front End : VB/VC ++/JAVA or equivalent
Back End : Oracle /SQL /MySQL/PostGress /DB2 or equivalent
Platform : Windows/XP, Windows 7 or its higher versions

PROBLEM DEFINITION:
The main concept is to understand the concept of triggers and functions in PL/SQL and
implement them in simple programs

BASIC TERMINOLOGIES:
PL/SQL
PL/SQL stands for Procedural Language extension of SQL.PL/SQL is a combination
of SQL along with the procedural features of programming languages. It was developed by
Oracle Corporation in the early 90’s to enhance the capabilities of SQL.

TRIGGERS

Triggers are stored programs, which are automatically executed or fired when some events
occur. Triggers are, in fact, written to be executed in response to any of the following events:
 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
 A database definition (DDL) statement (CREATES, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated.

PARTS OF A TRIGGER
A database trigger has three parts, namely, a trigger statement, a trigger body and a
trigger restriction.
Trigger Statement: -
A trigger statement specifies the DML statements like update, delete and insert and it
fires the trigger body. It also specifies the table to which the trigger is associated.
Trigger Body: -
Trigger body is a PL/SQL block that is executed when a triggering statement is issued.
Trigger Restriction: -
Restrictions on a triggers can be achieved using the WHEN clause as shown in the syntax
for creating triggers. They can be included in the definition of a row trigger, where in, the
condition in the WHEN clause is evaluated for each row that is affected by the trigger.

Syntax for creating a trigger


Create or Replace trigger <trigger_name>
[before/after] [insert/update/delete] on <table_name>
[for each statement/for each row]
[when <condition>]
PL/SQL block;
EXERCISES:

1) PL/SQL program to create a trigger before the user inserts the data into the table.

SQL> create or replace trigger ins2 before insert on emp


2 begin
3 raise_application_error(-20001,'you cant insert a row');
4 end;
5 /

Trigger created.

OUTPUT

SQL> insert into emp values(44,'ashu','cfo','male',30000);


insert into emp values(44,'ashu','cfo','male',30000)
*
ERROR at line 1:
ORA-20001: you cant insert a row
ORA-06512: at "CSE2A3.INS2", line 2
ORA-04088: error during execution of trigger 'CSE2A3.INS2'

2) Write a PL/SQL program to create a trigger before the user deletes the data from the
table.

SQL> create or replace trigger del2 before delete on emp


2 begin
3 raise_application_error(-20001,'you cant delete a row');
4 end;
5 /

Trigger created.

OUTPUT

SQL> delete from emp where id=22;


delete from emp where id=22
*
ERROR at line 1:
ORA-20001: you cant delete a row
ORA-06512: at "CSE2A3.DEL2", line 2
ORA-04088: error during execution of trigger 'CSE2A3.DEL2'
3) Write a PL/SQL program to create a trigger before the user changes the value of the
salary of an employee

SQL> create trigger upd1 before update on emp for each row
2 begin
3 if:new.salary<20000 then
4 raise_application_error(-20001,'salary cant be lower than this');
5 end if;
6 end;
7 /

Trigger created.

OUTPUT

SQL> update emp set salary=3000 where id=11;


update emp set salary=3000 where id=11
*
ERROR at line 1:
ORA-20001: salary cant be lower than this
ORA-06512: at "CSE2A3.UPD1", line 3
ORA-04088: error during execution of trigger 'CSE2A3.UPD1'

MERITS:

TRIGGERS

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

DEMERITS:

TRIGGERS

 Trigger can provide extended validation and it cannot be replaced with all the validations.
 Simple validations can be done at the application level itself.
 Triggers executes invisibly from client-application which connects to the database server.
So it is difficult to figure out what happens at the database layer.
 Triggers run on every update made to the table therefore it adds more load to the database
and cause the system to run slow.
FUNCTIONS
 Limited coding functionality
 Testing
 Portability

URLs:

 http://www.dbforums.com/db2/972602-advanteges-disadvanteges-check-
constraints-triggers-stored-procedures.html
 http://sqlperformance.com/2012/11/t-sql-queries/benefits-indexing-foreign-
keys
 http://docs.oracle.com/cd/E18283_01/server.112/e16508/datainte.htm
 http:/www.javas.com/oracle/catalog/index.html

VIVA QUESTIONS:

1. What is a PL/SQL functions?


2. Define a trigger.
3. What is the use of triggers in database?
4. List the different types of triggers.
5. What are the merits and demerits of using triggers?
6. Give the merits and demerits of using the functions.

RESULT:

Thus the usage of triggers were studied and executed in RDBMS.


Ex. No: 7
Date:
EXCEPTION HANDLING

OBJECTIVE:
To write a PL/SQL block to handle all types of exceptions.

HARDWARE REQUIREMENTS:
Processor Type : Pentium IV
RAM : 1 GB
Hard Disk : 80GB
Frequency : 1.60 GHZ

SOFTWARE REQUIREMENTS:
Front End : VB/VC ++/JAVA or equivalent
Back End : Oracle /SQL /MySQL/PostGress /DB2 or equivalent
Platform : Windows/XP, Windows 7 or its higher versions

PROBLEM DEFINITION:
The main concept is to understand the basic concepts of Exceptions in PL/SQL and to
write some simple programs using it.

BASIC TERMINOLOGIES:

Exception Handling

PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block
known as exception Handling. Using Exception Handling we can test the code and avoid it from
exiting abruptly.
When an exception occurs messages which explains its cause is received.
PL/SQL Exception message consists of three parts.
1) Type of Exception
2) An Error Code
3) A message
By Handling the exceptions we can ensure a PL/SQL block does not exit abruptly.
General Syntax for coding the exception section

DECLARE
Declaration section
BEGIN
Exception section
EXCEPTION
WHEN ex_name1 THEN
-Error handling statements
WHEN ex_name2 THEN
-Error handling statements
WHEN Others THEN
-Error handling statements
END;

General PL/SQL statments can be used in the Exception Block

When an exception is raised, Oracle searches for an appropriate exception handler in the
exception section. For example in the above example, if the error raised is 'ex_name1 ', then the
error is handled according to the statements under it. Since, it is not possible to determine all the
possible runtime errors during testing fo the code, the 'WHEN Others' exception is used to
manage the exceptions that are not explicitly handled. Only one exception can be raised in a
Block and the control does not return to the Execution Section after the error is handled.

If there are nested PL/SQL blocks then

DELCARE
Declaration section
BEGIN
DECLARE
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
EXCEPTION
Exception section
END;

In the above case, if the exception is raised in the inner block it should be handled in the
exception block of the inner PL/SQL block else the control moves to the Exception block of the
next upper PL/SQL Block. If none of the blocks handle the exception the program ends abruptly
with an error.
Types of Exception

There are 3 types of Exceptions.


a) Named System Exceptions
b) Unnamed System Exceptions
c) User-defined Exceptions

a) Named System Exceptions


System exceptions are automatically raised by Oracle, when a program violates a
RDBMS rule. There are some system exceptions which are raised frequently, so they are pre-
defined and given a name in Oracle which are known as Named System Exceptions.

For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.

Named system exceptions are:


1) Not Declared explicitly,
2) Raised implicitly when a predefined Oracle error occurs,
3) caught by referencing the standard name within an exception-handling routine.

Exception Name Reason Error


Number
CURSOR_ALREADY_OPEN When you open a cursor that is already open. ORA-
06511
INVALID_CURSOR When you perform an invalid operation on a ORA-
cursor like closing a cursor, fetch data from a 01001
cursor that is not opened.
NO_DATA_FOUND When a SELECT...INTO clause does not return ORA-
any row from a table. 01403
TOO_MANY_ROWS When you SELECT or fetch more than one row ORA-
into a record or variable. 01422
ZERO_DIVIDE When you attempt to divide a number by zero. ORA-
01476

b) Unnamed System Exceptions


Those system exception for which oracle does not provide a name is known as unamed
system exception. These exception do not occur frequently. These Exceptions have a code and an
associated message.

There are two ways to handle unnamed system exceptions:


1. By using the WHEN OTHERS exception handler, or
2. By associating the exception code to a name and using it as a named exception.

We can assign a name to unnamed system exceptions using a Pragma called


EXCEPTION_INIT.
EXCEPTION_INIT will associate a predefined Oracle error number to a
programmer_defined exception name.
Steps to be followed to use unnamed system exceptions are
• They are raised implicitly.
• If they are not handled in WHEN Others they must be handled explicity.
• To handle the exception explicity, they must be declared using Pragma EXCEPTION_INIT as
given above and handled referecing the user-defined exception name in the exception section.

The general syntax to declare unnamed system exception using EXCEPTION_INIT is:

DECLARE
exception_name EXCEPTION;
PRAGMA
EXCEPTION_INIT (exception_name, Err_code);
BEGIN
Execution section
EXCEPTION
WHEN exception_name THEN
handle the exception
END;

c) User-defined Exceptions
Apart from sytem exceptions we can explicity define exceptions based on business rules.
These are known as user-defined exceptions.

Steps to be followed to use user-defined exceptions:


• They should be explicitly declared in the declaration section.
• They should be explicitly raised in the Execution Section.
• They should be handled by referencing the user-defined exception name in the exception
section.

RAISE_APPLICATION_ERROR ( )

RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to


display the user-defined error messages along with the error number whose range is in between -
20000 and -20999.

Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous


transactions which are not committed within the PL/SQL Block are rolled back automatically
(i.e. change due to INSERT, UPDATE, or DELETE statements).

RAISE_APPLICATION_ERROR raises an exception but does not handle it.

RAISE_APPLICATION_ERROR is used for the following reasons,


a) to create a unique id for an user-defined exception.
b) to make the user-defined exception look like an Oracle error.
The General Syntax to use this procedure is:

RAISE_APPLICATION_ERROR (error_number, error_message);

• The Error number must be between -20000 and -20999


• The Error_message is the message you want to display when the error occurs.

Steps to be followed to use RAISE_APPLICATION_ERROR procedure:


1. Declare a user-defined exception in the declaration section.
2. Raise the user-defined exception based on a specific business rule in the execution section.
3. Finally, catch the exception and link the exception to a user-defined error number in
RAISE_APPLICATION_ERROR.

PRE-DEFINED EXCEPTIONS

PL/SQL provides many pre-defined exceptions, which are executed when any database
rule is violated by a program. For example, the predefined exception NO_DATA_FOUND is
raised when a SELECT INTO statement returns no rows. The following table lists few of the
important pre-defined exceptions:

Oracle
Exception SQLCODE Description
Error

It is raised when a null object is automatically


ACCESS_INTO_NULL 06530 -6530
assigned a value.

It is raised when none of the choices in the


CASE_NOT_FOUND 06592 -6592 WHEN clauses of a CASE statement is
selected, and there is no ELSE clause.

It is raised when a program attempts to apply


collection methods other than EXISTS to an
uninitialized nested table or varray, or the
COLLECTION_IS_NULL 06531 -6531
program attempts to assign values to the
elements of an uninitialized nested table or
varray.

DUP_VAL_ON_INDEX 00001 -1 It is raised when duplicate values are


attempted to be stored in a column with
unique index.

It is raised when attempts are made to make a


INVALID_CURSOR 01001 -1001 cursor operation that is not allowed, such as
closing an unopened cursor.

It is raised when the conversion of a character


INVALID_NUMBER 01722 -1722 string into a number fails because the string
does not represent a valid number.

It is raised when s program attempts to log on


LOGIN_DENIED 01017 -1017 to the database with an invalid username or
password.

It is raised when a SELECT INTO statement


NO_DATA_FOUND 01403 +100
returns no rows.

It is raised when a database call is issued


NOT_LOGGED_ON 01012 -1012
without being connected to the database.

It is raised when PL/SQL has an internal


PROGRAM_ERROR 06501 -6501
problem.

It is raised when a cursor fetches value in a


ROWTYPE_MISMATCH 06504 -6504
variable having incompatible data type.

It is raised when a member method is invoked,


SELF_IS_NULL 30625 -30625 but the instance of the object type was not
initialized.

It is raised when PL/SQL ran out of memory


STORAGE_ERROR 06500 -6500
or memory was corrupted.
It is raised when s SELECT INTO statement
TOO_MANY_ROWS 01422 -1422
returns more than one row.

It is raised when an arithmetic, conversion,


VALUE_ERROR 06502 -6502
truncation, or size-constraint error occurs.

It is raised when an attempt is made to divide


ZERO_DIVIDE 01476 1476
a number by zero.
EXERCISE:

1) PL/SQL program to implement Check Exception Type

SQL>
SQL> DECLARE
2 num_a NUMBER := 6;
3 num_b NUMBER;
4 BEGIN
5 num_b := 0;
6 num_a := num_a / num_b;
7 num_b := 7;
8 dbms_output.put_line(' Value of num_b ' || num_b);
9 EXCEPTION
10 WHEN ZERO_DIVIDE
11 THEN
12 dbms_output.put_line('Trying to divide by zero');
13 dbms_output.put_line(' Value of num_a ' || num_a);
14 dbms_output.put_line(' Value of num_b ' || num_b);
15 END;
16 /

OUTPUT
Trying to divide by zero
Value of num_a 6
Value of num_b 0

PL/SQL procedure successfully completed.

2) PL/SQL program to implement When Other Exceptions Then

SQL> -- when others then


SQL>
SQL> set serveroutput on
SQL>
SQL> DECLARE
2 PARENT_ERROR exception;
3 BEGIN
4 DECLARE
5 CHILD_ERROR exception;
6 BEGIN
7 raise CHILD_ERROR;
8 EXCEPTION
9 WHEN CHILD_ERROR THEN
10 dbms_output.put_line('nested block exception handler');
11 raise;
12 END;
13 EXCEPTION
14 WHEN PARENT_ERROR THEN
15 dbms_output.put_line('parent block exception handler');
16 WHEN OTHERS THEN
17 dbms_output.put_line('Caught the OTHERS exception');
18 raise;
19 END;
20 /
22

OUTPUT

nested block exception handler


Caught the OTHERS exception
declare
*
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at line 19

3)PL/SQL program to implement Declaration Exception

SQL> DECLARE
2 myNumber number default 'MY NUMBER';
3 BEGIN
4 NULL;
5 EXCEPTION
6 WHEN OTHERS THEN
7 dbms_output.put_line('Exception caught');
8 raise;
9 END;
10 /
OUTPUT

declare
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 2

4) PL/SQL program to display the details of customer using Exception Handling

SQL> select * from customer;

C_ID C_NAME C_ADDR

---------- -------------------- --------------------

11 arun mumbai

22 harish delhi

33 deepak kolkata

SQL> declare

2 cid customer.c_id%type;

3 cname customer.c_name%type;

4 caddr customer.c_addr%type;

5 begin

6 cid:=&cid;

7 select c_name,C_addr into cname,caddr

8 from customer

9 where c_id=cid;

10 dbms_output.put_line('Name:'||cname);

11 dbms_output.put_line('Address:'||caddr);

12 exception
13 when no_data_found then

14 dbms_output.put_line('No such customer!');

15 when others THEN

16 dbms_output.put_line('Error!');

17 end;

18 /

OUTPUT

/* for a valid customer id */

Enter value for cid: 22

old 6: cid:=&cid;

new 6: cid:=22;

Name:harish

Address:delhi

PL/SQL procedure successfully completed.

/* for an Invalid customer id */

SQL> /

Enter value for cid: 44

old 6: cid:=&cid;

new 6: cid:=44;

No such customer! (Exception raised)

PL/SQL procedure successfully completed.


MERITS:

 Using exceptions for error handling has several advantages. With exceptions, you can
reliably handle potential errors from many statements with a single exception handler

 Instead of checking for an error at every point where it might occur, add an exception
handler to your PL/SQL block. If the exception is ever raised in that block (including
inside a sub-block), it will be handled.

 Isolating error-handling routines makes the rest of the program easier to read and
understand.

DEMERITS:

Using exceptions for error handling has two disadvantages:


 First, exceptions can trap only runtime errors. Therefore, a PL/SQL program cannot trap
and recover from compile-time (syntax and semantic) errors such as table or view does
not exist.
 Second, exceptions can mask the statement that caused an error

URLs:

 http://www.dbforums.com/db2/972602-advanteges-disadvanteges-check-
constraints-triggers-stored-procedures.html
 http://sqlperformance.com/2012/11/t-sql-queries/benefits-indexing-foreign-
keys
 http://docs.oracle.com/cd/E18283_01/server.112/e16508/datainte.htm
 http:/www.javas.com/oracle/catalog/index.html

VIVA QUESTIONS:

1. What is an Exception?
2. What is the function of Exception Handler?
3. Mention the different types of Exception.

RESULT:

Thus the PL/SQL block is created to handle all types of exceptions and are well executed.
Ex. No: 8
Date:
Database Design using ER modeling, normalization and
Implementation for any application

Aim:
To design database using normalization and ER-Diagram.

Hardware Requirements:
 Pentium IV Processor or higher end processor
 2 GB RAM

Software Requirements:
 Windows 7 or above
 Oracle
 Visual Basic 6.0

Definition and Syntax:

Normalization

Normalization is the process of minimizing redundancy in a database.A


relation schema is taken and subjected to a series of tests to verify whether it is in normal
form or not.This process proceeds in top-down fashion evaluating each relation against
criteria and decomposing relations.It is proposed by Codd.

Normalization of data is a process of analyzing the given relation schemas


based on their functional dependencies and primary keys to achieve the desirable
properties of

 minimizing redundancy

 minimizing the insertion,deletion and update anomalies.

A normal form is a state of a table that results from applying simple rules regarding
functional dependencies to that table.The various types of normal form are:
 First Normal Form(1NF): The multi-valued should be removed i.e elimination
of redundant groups.

 Second Normal Form(2NF): The partial functional dependencies have to be


removed i.e elimination of redundant data.

 Third Normal Form(3NF): The transitive dependencies have to be removed i.e


elimination of columns not dependent on the key.

 Boyce-Codd Normal Form(BCNF): The remaining anomalies that result from


functional dependencies are removed.

 Fourth Normal Form(4NF): Multi-valued dependencies are removed i.e


isolation of independent multiple relationships.

 Fifth Normal Form(5NF): Any remaining anomalies are removed.Here we


isolate semantically related multiple relationships.

First Normal Form(1NF)


1NF states that the domain of an attribute must include only atomic
(simple,indivisible) values and that value of any attribute in a tuple must be a single value
from the domain of that attribute.Hence 1NF disallows multi-valued attributes,composite
attributes.It disallows “relations
within relations”.

Second Normal Form(2NF)

A relation is said to be in 2NF if it is already in 1NF and it has no partial


dependency.2NF is based on the concept of full functional dependency.

A functional dependency(FD) XY is full functional dependency if


(X-(A))Y does not hold dependency any more if AX.

A functional dependency XY is partial dependency if A can be removed which


does not affect the dependency i.e. (X-(A))Y holds.

A relation is in 2NF if it is in 1NF and every non-primary key attribute is fully


and functionally dependent on primary key.

A relation in the 1NF will be in the 2NF if one of the following conditions is
satisfied:
The primary key consist of only one attribute.

No non-key attribute exist in relation i.e. all the attributes in the relation are components
of the primary key.
Every non-key attribute is FD on full set of primary key attributes.

Third Normal Form(3NF)

A relation is said to be in 3NF if it is already in 2NF and it has no transitive


dependency.

A FD XY in a relation schema R is a transitive dependency if there is a


set of attributes Z that is neither a candidate key nor a subset of any key of the relation
and both XZ and ZY hold.

Boyce-Codd Normal Form(BCNF)


A relation is said to be in BCNF if it is already in 3NF and every
determinant is a candidate key.It is stronger version of 3NF.Every relation in BCNF is
also in 3NF but the vice-versa may not hold.

The formal definition of BCNF differs from the definition of 3NF.A relatio
schema R is in BCNF if whenever a non-trivial functional dependency XA holds in
R,then X is a superkey of R.

Procedure:

1.Create a type „Address‟ to represent composite attribute.


2. Create the table
3. Insert the values in the table.
4. Draw the E-R diagram for the table.
5. Convert the given table to the normalized form.

a) Converting a table to 1NF:

To convert a table to 1NF removes all the multi valued &


composite attributes from the table.

b) Converting a Table to 2NF:

i) Find and remove attributes that are functionally dependent


on only a part of the key and not on the whole key. Place
them in a different table.Group the remaining attributes.
FIRST NORMAL FORM:

SQL>create type address as object(sno number(5),


2 sname varchar2(20),
3 city varchar2(20),
4 state varchar2(20)); /

Type created.

SQL>create table Employees(eno number(3) primary key,


2 enmae varchar2(20),
3 eadd address,
4 sal number(7,2))
SQL> /

Table created.

SQL> desc employees


Name Null? Type
----------------------------------------- -------- --------------------------
ENO NOT NULL NUMBER(3)
ENMAE VARCHAR2(20)
EADD ADDR
SAL NUMBER(7,2)

SQL> insert into employees


values(&eno,'&enmae',address(&sno,'&sname','&city','&state'),&sal);
Enter value for eno: 001
Enter value for enmae: anbu
Enter value for sno: 12
Enter value for sname: Ist street
Enter value for city: chennai
Enter value for state: tamilnadu
Enter value for sal: 10000
old 1: insert into employees
values(&eno,'&enmae',address(&sno,'&sname','&city','&state'),&sal)
new 1: insert into employees values(001,'anbu',address(12,'Ist
street','chennai','tamilnadu'),10000)

1 row created.
SQL> /
Enter value for eno: 002
Enter value for enmae: balu
Enter value for sno: 13
Enter value for sname: car street
Enter value for city: madurai
Enter value for state: tamilnadu
Enter value for sal: 10000
old 1: insert into employees
values(&eno,'&enmae',address(&sno,'&sname','&city','&state'),&sal)
new 1: insert into employees values(002,'balu',address(13,'car
street','madurai','tamilnadu'),10000)

1 row created.

SQL> /
Enter value for eno: 003
Enter value for enmae: chiru
Enter value for sno: 10
Enter value for sname: 9th street
Enter value for city: hyderabad
Enter value for state: andhra pradesh
Enter value for sal: 15000
old 1: insert into employees
values(&eno,'&enmae',address(&sno,'&sname','&city','&state'),&sal)
new 1: insert into employees values(003,'chiru',address(10,'9th
street','hyderabad','andhra pradesh')

1 row created.

SQL> select * from employees;

ENO ENMAE EADD(SNO, SNAME, CITY, STATE) SAL


---------- ---------- ------------------------------------------------------------
1 anbu ADDR(12, 'Ist street', 'chennai', 'tamilnadu') 10000

2 balu ADDR(13, 'car street', 'madurai', 'tamilnadu') 10000

3 chiru ADDR(10, '9th street', 'hyderabad', 'andhra pradesh') 15000


Normalizing the table to 1NF:

SQL> create table en1 as select eno, ename ,sal from employees;

Table created.

SQL> alter table en1 add primary key(eno);

Table altered.

SQL> desc en1


Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(15)
SAL NUMBER(7,2)

SQL> create table en2 as select eno,eadd from employees;

Table created.

SQL> alter table en2 add foreign key(eno) references en1(eno);

Table altered.

SQL> desc en2


Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NUMBER(3)
EADD ADDR

Normalizing to 1NF:

employee
Eno Ename Eadd Sal

1NF

Emp1 emp2
Ename Sal Eno eadd
Eno
SECOND NORMAL FORM:

SQL> create table empproject(eno number(3) primary key,


2 ename varchar2(20),
3 pno number(3) unique,
4 pname varchar2(20),
5 hours number(3));

Table created.

SQL> desc empproject


Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(20)
PNO NUMBER(3)
PNAME VARCHAR2(20)
HOURS NUMBER(3)

SQL> insert into empproject values(&eno,'&ename',&pno,'&pname',&hours);

Enter value for eno: 101


Enter value for ename: raja
Enter value for pno: 12
Enter value for pname: compilers
Enter value for hours: 12
old 1: insert into empproject values(&eno,'&ename',&pno,'&pname',&hours)
new 1: insert into empproject values(101,'raja',12,'compilers',12)

1 row created.

SQL> /
Enter value for eno: 102
Enter value for ename: ragu
Enter value for pno: 13
Enter value for pname: atm
Enter value for hours: 24
old 1: insert into empproject values(&eno,'&ename',&pno,'&pname',&hours)
new 1: insert into empproject values(102,'ragu',13,'atm',24)

1 row created.
SQL> /
Enter value for eno: 103
Enter value for ename: sunil
Enter value for pno: 14
Enter value for pname: robotics
Enter value for hours: 15
old 1: insert into empproject values(&eno,'&ename',&pno,'&pname',&hours)
new 1: insert into empproject values(103,'sunil',14,'robotics',15)

1 row created.

SQL> select * from empproject;

ENO ENAME PNO PNAME HOURS


---------- -------------------- ---------- -------------------- ----------
101 raja 12 compilers 12
102 ragu 13 atm 24
103 sunil 14 robotics 15

Normalizing the table to 2NF:

SQL>create table ep1 as select eno,ename from empproject;

Table created.

SQL>alter table ep1 add primary key(eno);

Table altered.

SQL> desc ep1


Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(20)

SQL>create table ep2 as select pno,pname from empproject;

Table created.

SQL>alter table ep3 add primary key(pno);

Table altered.
SQL> desc ep2
Name Null? Type
----------------------------------------- -------- ----------------------------
PNO NOT NULL NUMBER(3)
PNAME VARCHAR2(20)

SQL>create table ep3 as select eno,pno,hours from empproj;

Table created.

SQL>alter table ep3 add primary key(eno);

Table altered.

SQL>alter table ep3 add unique(pno);

Table altered.

SQL> desc ep3


Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NOT NULL NUMBER(3)
PNO NUMBER(3)
HOURS NUMBER(3)

Normalizing to 2NF:

Eno Ename pno pname hours

 2NF

Ep1
eno Ename

Ep2
pno Pname

Ep3
eno pno Hours
THIRD NORMAL FORM:

SQL>create table empdept (eno number(3) primary key,


2 ename varchar2(20),
3 sal number(7),
4 dno number(3),
5 dname varchar2(20));

Table created.

SQL> desc empdept


Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(20)
SAL NUMBER(7)
DNO NUMBER(3)
DNAME VARCHAR2(20)

SQL> insert into empdept values(&eno,'&ename',&sal,&dno,'&dname');


Enter value for eno: 101
Enter value for ename: ravi
Enter value for sal: 10000
Enter value for dno: 1
Enter value for dname: cse
old 1: insert into empdept values(&eno,'&ename',&sal,&dno,'&dname')
new 1: insert into empdept values(101,'ravi',10000,1,'cse')

1 row created.

SQL> /
Enter value for eno: 102
Enter value for ename: ragu
Enter value for sal: 20000
Enter value for dno: 2
Enter value for dname: eee
old 1: insert into empdept values(&eno,'&ename',&sal,&dno,'&dname')
new 1: insert into empdept values(102,'ragu',20000,2,'eee')

1 row created.
SQL> select * FROM EMPDEPT;

ENO ENAME SAL DNO DNAME


---------- -------------------- ---------- ---------- --------------------
101 ravi 10000 1 cse
102 ragu 20000 2 eee

Normalizing the table to 3NF:

SQL>create table ed1 as select eno,ename,sal,dno from empdept;

Table created.

SQL>alter table ed1 add primary key(eno);

Table altered.

SQL> desc ed1


Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(20)
SAL NUMBER(7,2)
DNO NUMBER(3)

SQL>create table ed2 as select dno,dname from empdept;


Table created.

SQL>alter table ed2 add primary key(dno);

SQL> desc ed2


Name Null? Type
----------------------------------------- -------- ----------------------------
DNO NOT NULL NUMBER(3)
DNAME VARCHAR2(20)

SQL>alter table ed1 add foreign key(dno) references ed2(dno);

Table altered.
Normalizing to 3NF:

Empdept
Eno ename Sal dno dname
    

 3NF
Ed1
eno ename sal dno

Ed2
Dno Dname

Result:
Thus the database was designed using E-R diagram and Normalization.
EXP. NO : 9

NOSQL DATABASE TOOLS


AIM:

To Create Document, column and graph based data using NOSQL database tools.

What is NoSQL and what is a NoSQL database?

NoSQL database technology stores information in JSON documents instead of


columns and rows used by relational databases. To be clear, NoSQL stands for “not
only SQL” rather than “no SQL” at all. This means a NoSQL JSON database can
store and retrieve data using literally “no SQL.” Or you can combine the flexibility of
JSON with the power of SQL for the best of both worlds. Consequently, NoSQL
databases are built to be flexible, scalable, and capable of rapidly responding to the
data management demands of modern businesses. The following defines the four
most-popular types of NoSQL database:

Types of NOSQL Databases:

 Document databases are primarily built for storing information as


documents, including, but not limited to, JSON documents. These systems can
also be used for storing XML documents, for example.
 Key-value stores group associated data in collections with records that are
identified with unique keys for easy retrieval. Key-value stores have just
enough structure to mirror the value of relational databases while still
preserving the benefits of NoSQL.
 Wide-column databases use the tabular format of relational databases yet
allow a wide variance in how data is named and formatted in each row, even
in the same table. Like key-value stores, wide-column databases have some
basic structure while also preserving a lot of flexibility
 Graph databases use graph structures to define the relationships between
stored data points. Graph databases are useful for identifying patterns in
unstructured and semi-structured information.

Example:

{
"_id": 1,
"first_name": "Tom",
"email": "tom@example.com",
"cell": "765-555-5555",
"likes": [
"fashion",
"spas",
"shopping"
],
"businesses": [
{
"name": "Entertainment 1080",
"partner": "Jean",
"status": "Bankrupt",
"date_founded": {
"$date": "2012-05-19T04:00:00Z"
}
},
{
"name": "Swag for Tweens",
"date_founded": {
"$date": "2012-11-01T04:00:00Z"
}
}
]
}
"_id": 2,
"first_name": "Donna",
"email": "donna@example.com",
"spouse": "Joe",
"likes": [
"spas",
"shopping",
"live tweeting"
],
"businesses": [
{
"name": "Castle Realty",
"status": "Thriving",
"date_founded": {
"$date": "2013-11-21T04:00:00Z"
}
}
]
}

Users

ID first_name email cell


1 Tom tom@example.com 765-555-5555

Likes

ID user_id like
10 1 fashion
11 1 spas
12 1 shopping
Businesses

ID user_id name partner status date_founded


20 1 Entertainment 1080 Jean Bankrupt 2011-05-19
21 1 Swag for Tweens NULL NULL 2012-11-01

RESULT:

Thus the Document, column and graph based data using NOSQL database tools is
successfully completed.

You might also like