Sie sind auf Seite 1von 25

RDBMS

LAB
MANUAL
EXPERIMENT NO: 1

AIM: Preparing an ER diagram for given database and Conversion from ER diagram
to tables

THEORY:

• Database :
A Database is a collection of interrelated data and a Database Management
System is a a software system that enables users to define, create and maintain the database
and which provides controlled access to the database.

• ER- Diagram :
It is an Entity –Relationship diagram which is used to represent the
relationship between different entities. An entity is an object in the real world which is
distinguishable from other objects. The overall logical structure of a database can be
expressed graphically by an ER diagram, which is built up from following components.

Rectangles: represent entity sets.


Ellipses: represent attributes.
Diamonds: represent relationships among entity sets.
Lines: link attribute to entity sets and entity sets to relationships.

• Mapping Cardinalities :

It expresses the number of entities to which another entity can be associated via a
relationship set. For a binary relationship set R between entity sets A and B. The
Mapping Cardinalities must be one of the following.

• One to one
• One to many
• Many to one
• Many to many

Conversion from ER diagram to tables

Step 1: Mapping of Regular Entity Types:

For each regular(strong) entity type E in the ER schema create a relation R that
includes all the simple attributes of E. Include only the simple component attributes of a
composite ,the set of simple attributes that form it will together form the primary key of R.

Step 2: Mapping of Weak Entity Types:


For each weak entity type W in the ER schema with owner entity type E, create a
relation R and include all the attributes of W and the specific attributes of R. In addition
include the Primary key attribute(s) of the owner entity type. 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.

Step 3 : Mapping of Binary 1:1 Relationship Types :

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 a Foreign key in S the primary key of T. It is better to choose an entity
type with total participation in R in the role of S. Include all the simple attributes (or simple
components of a composite attributes) of the 1:1 relationship type R as attributes of S.

Step 4: Mapping of Binary 1:N Relationship Types :

For each regular binary 1:N relationship type R, identifying the relation S that
represent the participating Entity Type at the N side of the relationship type. Include as
Foreign key in S the primary key of T that represents the other entity type participating in R;
this is done because each entity instance on the N side is related to at most one entity instance
on the 1-side of the relationship Type. Include any simple attributes (or simple components of
composite attributes) of the 1:N relationship type as attributes of S.

Step 5: Mapping of Binary M:N Relationship Types :

For each binary M:N relationship type R, create a new relation S to represent R.
Include the primary key of the participating entity types; their combination will form the
primary key of S. Also include any simple attributes of the M:N relationship types (or
simple components of a composite attributes) as attributes of S.

Step 6: Mapping of Multivalued Attributes:

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

Step 7: Mapping of N-ary Relationship Types:

For each N-ary relationship type R, where N>2, create a new relation S to represent
R. Include the primary keys of the relations that represent the participating entity types. Also
include any simple attributes of the N-ary relationship types (or simple components of a
composite attributes) as attributes of S.

Conclusion:
Referring to the problem statement the ER diagram was designed and converted into
the tables.
EXPERIMENT NO: 2

AIM: To perform DDL (Data Definition Language) commands.

THEORY:

SQL: It is structured query language, basically used to pass the query to retrieve and
manipulate the information from database. Depending upon the nature of query, SQL is
divided into different components:

• DDL(Data Definition Language )


• DML(Data Manipulation Language )
• DCL(Data Control Language )

DDL: The Data Definition Language (DDL) is used to create the database (i.e. tables,
keys, relationships etc), maintain the structure of the database and destroy databases and
database objects.
Eg. Create, Drop, Alter, Describe, Truncate

1. CREATE statements: It is used to create the table.


Syntax:
CREATE TABLE table_name(columnName1 datatype(size), columnName2
datatype(size),………);

2. DROP statements: To destroy an existing database, table, index, or view. If a table is


dropped all records held within it are lost and cannot be recovered.

Syntax:

DROP TABLE table_name;

3. ALTER statements: To modify an existing database object.

• Adding new columns:

Syntax:

Alter table table_name Add(New_columnName1 datatype(size),


New_columnName2 datatype(size),………);
• Dropping a columns from a table :

Alter table table_name DROP column columnName:

• Modifying Existing columns:

Syntax:

Alter table table_name Modify (columnName1


Newdatatype(Newsize));

4. Describe statements: To describe the structure (column and data types) of an


existing database, table, index, or view.

Syntax:

DESC table_name;

5. Truncate statements: To destroy the data in an existing database, table, index, or


view. If a table is truncated all records held within it are lost and cannot be recovered
but the table structure is maintained.

Syntax :

TRUNCATE TABLE table_name;

CONCLUSION:

Implemented various DDL commands

Post Lab Questions:

1. What is Data Dictionary?

2. What is Schema?

3. What are different data types in SQL?


EXPERIMENT NO: 3

AIM: To perform DML statement.

THEORY:

Data Manipulation Language

• A Data Manipulation Language enables programmers and users of the database to


retrieve insert, delete and update data in a database. e.g. INSERT, UPDATE,
DELETE, SELECT.

INSERT:

INSERT statement adds one or more records to any single table in a relational database.

Syntax:

INSERT INTO tablename VALUES (expr1,expr2……..);

UPDATE:

UPDATE statement that changes the data of one or more records in a table. Either all the
rows can be updated, or a subset may be chosen using a condition.

Syntax:

UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE


condition]

DELETE:

DELETE statement removes one or more records from a table. A subset may be defined for
deletion using a condition, otherwise all records are removed.

Syntax:

DELETE FROM tablename WHERE condition:


SELECT: SELECT statement returns a result set of records from one or more tables.
The select statement has optional clauses:
• WHERE specifies which rows to retrieve
• GROUP BY groups rows sharing a property so that an aggregate function can be
applied to each group having group.
• HAVING selects among the groups defined by the GROUP BY clause.
• ORDER BY specifies an order in which to return the rows.

Syntax:
SELECT<attribute list>
FROM<table list>
WHERE<condition>

Where

• Attribute list is a list of attribute name whose values to be retrieved by the query.
• Table list is a list of table name required to process query.
• Condition is a Boolean expression that identifies the tuples to be retrieved by query.

CONCLUSION:
Implemented various DML commands and also executed simple SQL queries.
EXPERIMENT NO: 4

AIM: To implement Data Constraints

THEORY:

Constraints are the business Rules which are enforced on the data being stored in a table
are called Constraints.

Types of Data Constraints


1. I/O Constraint
This type of constraint determines the speed at which data can be inserted or extracted
from an Oracle table.
I/O Constraints is divided into two different types
● The Primary Key Constraint
● The Foreign Key Constraint

2. Business rule Constraint


This type of constraint is applied to data prior the data being inserted into table columns.

Oracle allows programmer to define constraints at


● Column level
● Table level

The PRIMARY KEY defined at column level

Syntax:

CREATE TABLE tablename


(Columnname1 DATATYPE CONSTRAINT <constraintname1> PRIMARY KEY,
Columnname2 DATATYPE, columnname3 DATATYPE,.....);

The PRIMARY KEY defined at table level

Syntax:

CREATE TABLE tablename


(Columnname1 DATATYPE, columnname2 DATATYPE, columnname3 DATATYPE,
PRIMARY KEY (columnname1, columnname2));

The FOREIGN KEY defined at column level

Syntax:

CREATE TABLE tablename


(Columnname1 DATATYPE REFERENCES tablename[(columnname)] [ON DELETE
CASCADE], columnname2 DATATYPE , columnname3 DATATYPE ,.....);
The table in which FOREIGN KEY is defined is called FOREIGN TABLE or DETAIL
TABLE.
The table in which PRIMARY KEY is defined and referenced by FOREIGN KEY is called
PRIMARY TABLE or MASTER TABLE.

ON DELETE CASCADE is set then DELETE operation in master table will trigger
the DELETE operation for corresponding records in the detail table.

The FOREIGN KEY defined at table level

Syntax:

CREATE TABLE tablename


(Columnname1 DATATYPE, columnname2 DATATYPE, columnname3 DATATYPE,
PRIMARY KEY (columnname1, columnname2), FOREIGN KEY (columnname2)
REFERENCES tablename2;

A CONSTRAINT can be given User Defined Name, the syntax is:


CONSTRAINT < constraint name><constraint definition>

The CHECK Constraint defined at column level

CREATE TABLE tablename


(Columnname1 DATATYPE CHECK (logical expression), columnname2
DATATYPE, columnname3 DATATYPE,...);

The CHECK Constraint defined at table level

CREATE TABLE tablename


(Columnname1 DATATYPE, columnname2 DATATYPE, columnname3 DATATYPE,
CHECK (logical expression1), CHECK (logical expression2));

The UNIQUE Constraint defined at the column level

CREATE TABLE tablename


(Columnname1 DATATYPE UNIQUE, columnname2 DATATYPE UNIQUE,
columnname3 DATATYPE ...);

The UNIQUE Constraint defined at the the table level

CREATE TABLE tablename


(Columnname1 DATATYPE, columnname2 DATATYPE, columnname3 DATATYPE,
UNIQUE(columnname1));
NOT NULL constraint defined at column level :
CREATE TABLE tablename
(Columnname1 DATATYPE NOT NULL, columnname2 DATATYPE NOT NULL,
columnname3 DATATYPE,...);

Note: The NOT NULL constraint can only be applied at column level.
EXPERIMENT NO: 5

AIM : To implement Subquery.

THEORY:

Subquery is a form of SQL statement that appears inside another SQL statement. It is also
called as Nested Query.
The statement containing a subquery is called a Parent Statement.
The parent statement uses the rows returned by the subquery

It can be used by following commands


1. To insert records in a target table.
2. To create table and insert records into created table
3. To update records in the target table
4. To create views
5. To provide values for conditions in WHERE, HAVING, IN etc used with SELECT,
UPDATE, and DELETE statement.

CORRRELATED SUBQUERY

A subquery which executes once for each and every row of main query is called correlated
subquery.
It is mainly used for row by row process
The main difference between Correlated subquery and subquery is that in
Subquery(child query),Main Query is executed first.

Post Lab Assignments


1. Explain different types of SQL join.
EXPERIMENT NO: 6

AIM : To implement queries using set operations.

THEORY:
Multiple queries can be put together and their output combined using the union, intersects,
minus clause. The union clause merges the output of two or more queries into a single set of
rows and columns. The intersect clause outputs only rows produced by both the queries
intersected. The minus clause outputs the rows produced by the first query, after filtering the
rows retrieved by the second query.

Syntax:

Query1 union/intersect Query2 union/intersect …….


Query1 minus Query 2

Restrictions on using set operators


• Number of columns in all the queries should be the same.
• The data type of the columns in each query must be same
• It cannot be used in sub-queries
• Aggregate functions can not be used with set operators

Post Lab Assignments


1. Explain set membership operators like exist, not exist, in, not in, some, any, all
EXPERIMENT NO: 7

AIM : To implement PL/SQL Block.

THEORY:

PLSQL stands for "Procedural Language extensions to SQL", and can be used in Oracle
databases. PLSQL is closely integrated into the SQL language, yet it adds programming
constructs that are not native to SQL.
Advantages of PL/SQL
1. PL/SQL supports not only SQL data manipulation but also provides facilities of
conditional checking, branching and looping.
2. PL/SQL sends an entire block of statements to the Oracle engine at one time.
3. PL/SQL permits dealing with errors and displaying user friendly messages when the error
occurs.
4. Via PL/SQL all sorts of calculations can be done quickly without the use of Oracle Engine
5. Applications written in PL/SQL are portable to any computer hardware and operating
system where Oracle is operational.

The different sections of PL/SQL block are as follows:

DECLARE SECTION
Declarations of memory variables, constants, cursors etc in PL/SQL

BEGIN
SQL executable statements
PL/SQL executable statements

EXCEPTION
SQL or PL/SQL code to handle errors that may arise during the execution of the code block
EXPERIMENT NO: 8

AIM : To implement Cursors

THEORY:
The oracle engine uses a work area for its internal processing in order to execute an SQL
statement. This work area is private to SQL’s operations and is called a cursor. A cursor is a
mechanism by which you can assign a name to a "select statement" and manipulate the
information within that SQL statement.

There are two types of Cursors.


Inplicit Cursors
Explicit Cursors

Both the types of Cursors have following General attributes.

Attribute Name Description

%ISOPEN returns true if cursor is open, false otherwise


%FOUND returns true if record was fetched successfully, false otherwise.
%NOTFOUND returns true if record was not fetched successfully, false otherwise.
%ROWCOUNT returns number of records processed from the cursor.

Implicit cursor attributes can be used to access information about status of last insert, update,
delete or single - row select statement. This can be done by preceding the implicit cursor
attribute with cursor name (i.e. sql)

Explicit cursor is defined in the declarative part of a pl/sql block. This is done by naming the
cursor and mapping it to a query.
The commands used to control the cursor are DECLARE, OPEN, FETCH and CLOSE.

• Oracle/PLSQL: Declare a Cursor

A cursor is a SELECT statement that is defined within the declaration section of your
PLSQL code. We'll take a look at three different syntaxes for cursors.

1. Cursor without parameters (simplest)

The basic syntax for a cursor without parameters is:

CURSOR cursor_name
IS
SELECT_statement;

2. Cursor with parameters

The basic syntax for a cursor with parameters is:


CURSOR cursor_name (parameter_list)
IS
SELECT_statement;

3. Cursor with return clause

The basic syntax for a cursor with a return clause is:

CURSOR cursor_name
RETURN field%ROWTYPE
IS
SELECT_statement;

• Oracle/PLSQL: OPEN Statement

Once you've declared your cursor, the next step is to open the cursor.

The basic syntax to OPEN the cursor is:

OPEN cursor_name;

• Oracle/PLSQL: FETCH Statement

The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so that
some type of operation can be performed on the data. After declaring and opening your
cursor, the next step is to FETCH the rows from your cursor.

The basic syntax for a FETCH statement is:

FETCH cursor_name INTO <list of variables>;

• Oracle/PLSQL: CLOSE Statement

The final step of working with cursors is to close the cursor once you have finished using it.

The basic syntax to CLOSE the cursor is:

CLOSE cursor_name;

Post Lab Questions


1. Explain Implicit and Explicit cursors.
EXPERIMENT NO: 9

AIM: To Implement Procedures

THEORY:
Procedure is a subprogram used to perform a specific action. A subprogram is a
named block of PL/SQL. There are two types of subprograms in PL/SQL namely Procedures
and Functions. Every subprogram will have a declarative part, an executable part or body,
and an exception handling part, which is optional. Declarative part contains variable
declarations. Body of a subprogram contains executable statements of SQL and PL/SQL.
Statements to handle exceptions are written in exception part.

Procedure specification begins with CREATE and ends with procedure name or
parameters list. Procedures that do not take parameters are written without a parenthesis. The
body of the procedure starts after the keyword IS or AS and ends with keyword END.

Syntax for Procedure:

CREATE [OR REPLACE] PROCEDURE procedure_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS |
AS}
BEGIN
procedure_body
EXCEPTION
Exception handling
END procedure_name;

Procedure is created using CREATE PROCEDURE statement.

OR REPLACE specifies the procedure is to replace an existing procedure if present.


One can use this option to modify an existing procedure.

A procedure may be passed multiple parameters. IN | OUT | IN OUT specifies the mode of
the parameter. Type specifies the datatype of the parameter.

IN - The parameter can be referenced by the procedure or function. The value of the
parameter cannot be overwritten by the procedure or function.

OUT - The parameter cannot be referenced by the procedure or function, but the value of the
parameter can be overwritten by the procedure or function.

IN OUT - The parameter can be referenced by the procedure or function and the value of the
parameter can be overwritten by the procedure or function.

Procedure body contains the SQL and PL/SQL statements to perform the procedure's task.

Exception Section:

The Exception section of a PL/SQL Block starts with the reserved keyword
EXCEPTION. This section is optional. Any errors in the program can be handled in this
section, so that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains
exceptions that cannot be handled, the Block terminates abruptly with errors.

Advantages:

When client executes a procedure or a function, the processing is done in the server.
Server is likely to me more powerful than the clients which in turn mean that stored
procedures should run faster. This reduces network traffic.
As the procedures/functions are stored in the Oracle database there is no need to
transfer the code from the clients to the database server or to transfer intermediate results
from the server to the clients. This results in much less network traffic and again improves
scalability
The subprograms are compiled and stored in the Oracle database as stored programs
and can be invoked whenever required. As they are stored in compiled form when called,
they only need to be executed. Hence they save time needed for compilation. They allow
breaking the program into manageable modules. They provide reusability and maintainability
for the code.

Disadvantages:
There is an overhead involved in embedding or calling PL/SQL procedures from SQL
in Oracle due to the context switching that the Oracle database has to perform. This may be
significant in terms of performance but usually this overhead is outweighed by performance
advantages of using PL/SQL.
More memory may be required on the Oracle database server when using Oracle
PL/SQL packages as the whole package is loaded into memory as soon as any object in the
package is accessed

Conclusion:
Stored procedures should be used to improve the performance and scalability of applications.
The disadvantages are easily outweighed by the advantages and the use of packages to
combine related objects (procedures, functions and variables) into one physical unit enhances
these advantages.
EXPERIMENT NO: 10

AIM : To Implement Function

THEORY :

A function is a named PL/SQL Block which is similar to a procedure. The major


difference between a procedure and a function is, a function must always return a value, but a
procedure may or may not return a value.

Syntax for Function:

CREATE [OR REPLACE] FUNCTION function_name [parameters] RETURN


return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
Return Type: The header section defines the return type of the function. The return datatype
can be any of the oracle datatype like varchar, number etc.
The execution and exception section both should return a value which is of the
datatype defined in the header section.
Conclusion:
Functions are PL/SQL stored programming units, providing a way to hide implementation
details in a programming unit. Functions can be used as right operands in PL/SQL and be
called from SQL statements, while procedures cannot.
EXPERIMENT NO: 11

AIM: To Implement Trigger

THEORY:
A database triggers is stored PL/SQL program unit associated with a specific database
table or view. The code in the trigger defines the action the database needs to perform
whenever some database manipulation (INSERT, UPDATE, and DELETE) takes place.

Unlike the stored procedure and functions, which have to be called explicitly, the database
triggers are fired (executed) or called implicitly whenever the table is affected by any of the
above said DML operations. Till oracle 7.0 only 12 triggers could be associated with a given
table, but in higher versions of Oracle there is no such limitation. A database trigger fires
with the privileges of owner not that of user

A database trigger has three parts

1. A triggering event

2. A trigger constraint (Optional)

3. Trigger action

A triggering event can be an insert, update, or delete statement or a instance shutdown or


startup etc. The trigger fires automatically when any of these events occur on the specified
table or a view. A trigger constraint specifies a Boolean expression that must be true for the
trigger to fire. This condition is specified using the WHEN clause. The trigger action is a
procedure that contains the code to be executed when the trigger fires.

Syntax:

Trigger

A BEFORE INSERT Trigger means that Oracle will fire this trigger before the INSERT
operation is executed.

CREATE or REPLACE TRIGGER trigger_name BEFORE/AFTER


INSERT/UPDATE/DELETE ON table_name [ FOR EACH ROW ]
DECLARE
- variable declarations
BEGIN
- trigger code
EXCEPTION
WHEN ...
- exception
handling END;
trigger_name is the name of the trigger to create.

Restrictions:

• One can not create a BEFORE trigger on a view.

• One can update the :NEW values.

• One can not update the :OLD values.

Drop a Trigger

The syntax for a dropping a Trigger is:

DROP TRIGGER trigger_name;

Disable a Trigger

The syntax for a disabling a Trigger is:

ALTER TRIGGER trigger_name DISABLE;

Enable a Trigger

The syntax for a enabling a Trigger is:

ALTER TRIGGER trigger_name ENABLE;


EXPERIMENT NO:12

AIM: To implement TCL statements.

THEORY:
A transaction begins with the first executable SQL statement after a connection made
to the Oracle engine. All changes made to an Oracle table data via unit a transaction are made
or undone at one instance.
Transaction Control Language (TCL) consists of various commands which are as
follows.
COMMIT
ROLLBACK
SAVEPOINT
COMMIT:
A commit ends the current transaction and makes permanent any changes made
during the transactions. A commit will also release any existing savepoint that may be in use.
Syntax:
COMMIT;
ROLLBACK:
A ROLLBACK does exactly the opposite of COMMIT. It ends the transaction but
undoes any changes made during the transaction.
Syntax:
ROLLBACK TO [SAVEPOINT] savepointname;
Where,
SAVEPOINT: is optional and is used to rollback a partial transaction, as far
the specified savepoint.
Savepointname: is a savepoint created in current transaction.

SAVEPOINT:
SAVEPOINT marks and saves current point in the processing of a transaction. When
a SAVEPOINT is used with a ROLLBACK statement, parts of a transaction can be undone.
An active savepoint is the one that is specified since the last COMMIT or ROLLBACK.
Syntax:
SAVEPOINT savepointname;
ROLLBACK can be performed with or without the SAVEPOINT clause. The
implication of each is described below:
A ROLLBACK operation performed without the SAVEPONT clause amounts to the
following:
• Ends the transaction.
• Undoes all the changes in the current transaction.
• Erases all savepoints in that transaction.
A ROLLBACK operation performed with the TO SAVEPOINT clause amounts to
the following:
• A predetermined portion of the transaction is rolled back.
• Retains the savepoint rolled back to, but losses those create after the
named savepoint.
Conclusion:
TCL statements are used to save or erase changes made in the database during current
transaction.
EXPERIMENT NO:13

AIM: To implement DCL statements.

THEORY:

Data Control Language (DCL) consists of various commands which are related to
data sharing and security of data in database.
They are
GRANT
REVOKE
Granting Privileges:
Objects that are created by a user are owned and controlled by that user. If user
wishes to access any of the objects belonging to another user, the owner of the object will
have to give permissions for such access. This is called Granting of Privileges.
Granting privileges using the GRANT statements:
The GRANT statements provide various types of access to database objects such as
tables, views.
Syntax:
GRANT {object privileges}
ON object name
TO username;
Object Privileges:
each object privilege that is granted authorizes the grantee to perform some operation
on the object. The user can grant all the privileges or grant only specific object privileges.
The list of object privileges is as follows:
• ALTER: allows the grantee to change the table definitions with the ALTER table
command.
• DELETE: allows the grantee to remove the records from the table with the DELETE
command.
• INDEX: allows the grantee to create an index on the table with the CREATE INDEX
command.
• INSERT: allows the grantee to add records to the table with the INSERT command.
• SELECT: allows the grantee to query the table with SELECT command.
• UPDATE: allows the grantee to modify the records in the table with the UPDATE
command.

Revoking privileges given:


Privileges once given can be denied to a user using the REVOKE command. The
object owner can revoke privileges granted to another user. A user of an object who is not
owner, but has been granted the GRANT privilege, has the power to REVOKE the privileges
from the grantee.
Revoking permission using the REVOKE statement:
The REVOKE statement is used to deny the grant given on an object.
Syntax:
REVOKE {object privileges}
ON object name
FROM username;
The REVOKE command is used to revoke object privileges that the user previously
granted to the Revoke.
The REVOKE command cannot be used to revoke the privileges granted
through operating system.

Conclusion:
DCL statements are used to provide data sharing of data in database.

Das könnte Ihnen auch gefallen