Lab Manual of Dbms All Practals
Lab Manual of Dbms All Practals
Lab Manual of Dbms All Practals
PRACTICAL –1
Almost all full-scale database systems are RDBMS's. Small database systems,
however, use other designs that provide less flexibility in posing queries.
Oracle
In June 1970, Dr. E.F Codd, presented a Relational Model sponsored by IBM. The
language developed by IBM to manipulate data stored within Codd’s Model was
originally called as Structured English Query Language. Later it was called SQL.
Oracle Corporation is a company that produces most widely used server based
multiuser RDBMS named Oracle
It can be used for departmental-style applications with a dozen users, but can
also scale up to handle thousands of users.
Opening oracle
Oracle – Login
SQL Statements
PRACTICAL – 2
1. CREATE
Syntax
CREATE TABLE Tablename( { Fieldname Datatype [ (Size) ] Fieldtype [...] } [,...] ) ;
Description:
CREATE TABLE creates a new empty table in the selected database from the structure
description in the command.
2. ALTER
Syntax
ALTER TABLE table_name ADD ( column_1 column-definition);
ALTER TABLE table_name MODIFY (column_1 column_type);
Description
The ALTER TABLE statement allows you to rename an existing table. It can also be
used to add, modify, or drop a column from an existing table.
Before using alter command
3. DROP
Syntax
DROP TABLE table_name;
Description
DROP TABLE removes one or more tables. You must have the DROP privilege for each
table. All table data and the table definition are removed.
4. RENAME
Syntax
RENAME TABLE table_name TO new_table_name
Description
The rename operation is done atomically, which means that no other session can
access any of the tables while the rename is running. For example, if you have an
existing table old_table, you can create another table new_table that has the same
structure but is empty, and then replace the existing table with the empty one.
5. TRUNCATE
Syntax
Description
TRUNCATE TABLE empties a table completely. Logically, TRUNCATE TABLE is equivalent
to a DELETE statement that deletes all rows, but there are practical differences under
some circumstances.
Syntax
INSERT
INTO <table>
(<column listings>)
VALUES (<column values>);
PRACTICAL – 3
FROM table_name
SELECT column_name(s)
FROM table_name
Joins
Equi Cross Outer
Left
Right
FROM student_details
------------- -------------
Stephen Fleming
Shekar Gowda
The above select statement searches for all the rows where the
first letter of the column first_name is 'S' and rest of the letters in
the name can be any character.
There is another wildcard character you can use with LIKE
operator. It is the underscore character, ' _ ' . In a search string,
the underscore signifies a single character.
For example: to display all the names with 'a' second character,
FROM student_details
------------- -------------
Rahul Sharma
FROM student_details
Rahul Sharma 10
Anajali Bhagwat 12
Shekar Gowda 15
SQL IN Operator:
The IN operator is used when you want to compare a column with
more than one value. It is similar to an OR condition.
For example: If you want to find the names of students who are
studying either Maths or Science, the query would be like,
SELECT first_name, last_name, subject
FROM student_details
FROM student_details
Syntax
DELETE
FROM <table>
WHERE <one or more data conditions>;
Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Employee table
Bonuses Table
Merge operation
PRACTICAL – 4
Set Operations
Union +
Intersection Minus
Union All
The set operators in oracle are UNION, UNION ALL, INTERSECT, MINUS. These set
operators allow us to combine more than one select statements and only one result set
will be returned.
UNION: The UNION operator is used to combine the result-set of two or more
SELECT statements Tables of both the select statement must have the same
number of columns with similar data types. It eliminates duplicates.
Syntax:
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
UNION ALL
UNION ALL selects all rows from all the select statements
UNION ALL output is not sorted.
Distinct keyword cannot be used in select statements.
Syntax:
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
Syntax:
select field1, field2, . field_n from tables INTERSECT select field1, field2, . field_n from
tables;
MINUS returns all rows in the first query that are not returned in the second
query. Each statement must have the same number of fields in the result sets
with similar data types.
Syntax:
Select field1, field2, . field_n from tables
MINUS
select field1, field2, . field_n from tables;
EXAMPLES
Table 1: Stu_acc Table 2: Stu_info
INTERSECTION
MINUS
FROM student_details
FROM student_details
but, if you do not know their names, then to get their id's you
need to write the query in this manner,
FROM student_details
FROM student_details
Subquery Output:
id first_name
-------- -------------
100 Rahul
102 Stephen
In the above sql statement, first the inner query is processed first
and then the outer query is processed.
p.product_id = 101
product_name supplier_name order_id
Correlated Subquery
A query is called correlated subquery when both the inner query
and the outer query are interdependent. For every row processed
by the inner query, the outer query is processed as well. The inner
query depends on the outer query before it can be processed.
order_items o
Subquery Notes
Nested Subquery
1) You can nest as many queries you want but it is recommended
not to nest more than 16 subqueries in oracle
Non-Corelated Subquery
2) If a subquery is not dependent on the outer query it is called a
non-correlated subquery
Subquery Errors
3) Minimize subquery errors: Use drag and drop, copy and paste
to avoid running subqueries with spelling and database typos.
Watch your multiple field SELECT comma use, extra or to few
getting SQL error message "Incorrect syntax".
JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables,
based on a relationship between certain columns in these tables. Tables in a database
are often related to each other with keys. A primary key is a column (or a combination
of columns) with a unique value for each row. Each primary key value must be unique
within the table. The purpose is to bind data together, across tables, without repeating
all of the data in every table.
EQUI JOIN
Syntax
Select column_list
FROM table1, table2....
Description
SQL EQUI JOIN performs a JOIN against equality or matching column(s) values of the
associated tables. An equal sign (=) is used as comparison operator in the where clause
to refer equality. You may also perform EQUI JOIN by using JOIN keyword followed by
ON keyword and then specifying names of the columns along with their associated
tables to check equality.
CROSS JOIN
Syntax
Select *
From table1
Cross join table2
Description
In cross joins, each row from first table joins with all the rows of another table. If 1st
table contains x rows and y rows in 2nd one, the result set will be x*y rows.
OUTER JOIN
LEFT JOIN
Syntax
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Description
The LEFT JOIN keyword returns all rows from the left table (table_name1), even if
there are no matches in the right table (table_name2).
RIGHT JOIN
Syntax
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Description
The RIGHT JOIN keyword returns all the rows from the right table (table_name2), even
if there are no matches in the left table (table_name1).
EXAMPLES
1. Equi Join
2. Cross Join
3. Outer Join
1. Left Outer Join 2. Right Outer Join
INCREMENT BY increment_value
VALUES(sequence_name.nextval, value1,
value2, ..)
to be auto generated
START WITH 1
INCREMENT BY 1
PRACTICAL – 5
AS
SELECT column_list
AS
FROM product;
SQL Index
Index in sql is created on existing tables to retrieve the rows
quickly.
When there are thousands of records in a table, retrieving
information will take a long time. Therefore indexes are created on
columns which are accessed frequently, so that the information
can be retrieved quickly. Indexes can be created on a single
column or a group of columns. When a index is created, it first
sorts the data and then it assigns a ROWID for each row.
Syntax to create Index:
CREATE INDEX index_name
ON table_name (column_name1,column_name2...);
Syntax to create SQL unique Index:
CREATE UNIQUE INDEX index_name
ON table_name (column_name1,column_name2...);
Implicit Indexes:
They are created when a column is explicity defined with PRIMARY
KEY, UNIQUE KEY Constraint.
Explicit Indexes:
They are created using the "create index.. " syntax.
ON object_name
REVOKE privilege_name
ON object_name
from more than one users, he/she can SELECT from that table
until everyone who granted the permission revokes it. You cannot
REVOKE privileges if they were not initially granted by you.
The above rules also apply for ALTER and DROP system
privileges.
Few of the object privileges are listed below:
Object
Description
Privileges
Creating Roles:
The Syntax to create a role is:
CREATE ROLE role_name
[IDENTIFIED BY password];
For Example: To create a role called "developer" with password
as "pwd",the code will be as follows
CREATE ROLE testing
[IDENTIFIED BY pwd];
PRACTICAL – 6
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.
This section is optional and is used to declare any placeholders like variables, constants,
records and cursors, which are used to manipulate data in the execution section.
Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and
ends with END. This is a mandatory section and is the section where the program logic
is written to perform any task. The programmatic constructs like loops, conditional
statement and SQL statements form the part of execution section.
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.
Every statement in the above three sections must end with a semicolon ; . PL/SQL
blocks can be nested within other PL/SQL blocks. Comments can be used to document
code.
IF-THEN-ELSE
Syntax
IF condition THEN
{...statements...}
ELSE
{...statements...}
END IF;
EXAMPLE
Table- Acc_no
PRACTICAL – 7
Procedure
A procedure or in simple a proc is a named PL/SQL block which performs one or more
specific task. This is similar to a procedure in other programming languages.
A procedure has a header and a body. The header consists of the name of the
procedure and the parameters or variables passed to the procedure. The body consists
or declaration section, execution section and exception section similar to a general
PL/SQL Block.
IN - The parameter can be referenced by the procedure or function. The value of the
parameter can not be overwritten by the procedure or function.
OUT - The parameter can not 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.
Syntax
Functions
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
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;
1) 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.
2)The execution and exception section both should return a value which is of the
datatype defined in the header section.
EXAMPLES
1. PROCEDURE
o Before executing Procedure
2. Function
o Creating the Function
PR
Iterative
Statements
for in
for while
reverse
FOR Loop
A FOR LOOP is used to execute a set of statements for a predetermined number of
times. Iteration occurs between the start and end integer values given. The counter is
always incremented by 1. The loop exits when the counter reaches the value of the end
integer.
Syntax
FOR counter IN val1..val2
LOOP
statements;
END LOOP;
val1 - Start integer value.
val2 - End integer value.
Syntax
FOR counter IN REVERSE val1..val2
LOOP
statements;
END LOOP;
While Loop
A WHILE LOOP is used when a set of statements has to be executed as long as a
condition is true. The condition is evaluated at the beginning of each iteration. The
iteration continues until the condition becomes false.
Syntax
WHILE <condition>
LOOP statements;
END LOOP;
EXAMPLES
1. FOR LOOP
3. WHILE LOOP
PRACTICAL – 8
TRIGGERS
A trigger is a pl/sql block structure which is fired when a DML statements like Insert,
Delete, Update is executed on a database table. A trigger is triggered automatically
when an associated DML statement is executed.
Syntax
CREATE [OR REPLACE ] TRIGGER trigger_name
CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with
the given name or overwrites an existing trigger with the same name.
{BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the
trigger get fired. i.e for example: before or after updating a table. INSTEAD OF is used
to create a trigger on a view. before and after cannot be used to create a trigger on a
view.
{INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering
event. More than one triggering events can be used together separated by OR keyword.
The trigger gets fired at all the specified triggering event.
[OF col_name] -This clause is used with update triggers. This clause is used when you
want to trigger an event only when a specific column is updated.
CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the
given name or overwrites an existing trigger with the same name.
[ON table_name] - This clause identifies the name of the table or view to which the
trigger is associated.
[REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and
new values of the data being changed. By default, you reference the values
as :old.column_name or :new.column_name. The reference names can also be changed
from old (or new) to any other user-defined name. You cannot reference old values
when inserting a record, or new values when deleting a record, because they do not
exist.
[FOR EACH ROW] - This clause is used to determine whether a trigger must fire when
each row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql
statement is executed(i.e.statement level Trigger).
WHEN (condition) -This clause is valid only for row level triggers. The trigger is fired
only for rows that satisfy the condition specified.
2. Trigger
o Creating Trigger
Cursors
Oracle creates a memory area, known as context area, for processing an SQL
statement, which contains all information needed for processing the statement, for
example, number of rows processed etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a
cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of
rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process
the rows returned by the SQL statement, one at a time. There are two types of cursors:
Cursors
Implicit Explicit
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor
is associated with this statement.
Attribute Description
Always returns FALSE for implicit cursors, because Oracle closes the
%ISOPEN
SQL cursor automatically after executing its associated SQL statement.
Explicit Cursors
Explicit cursors are programmer defined cursors for gaining more control over the
context area. An explicit cursor should be defined in the declaration section of the
PL/SQL Block. It is created on a SELECT Statement which returns more than one row.
Syntax
Working with an explicit cursor involves four steps:
EXAMPLES
CURSOR