0% found this document useful (0 votes)
11 views33 pages

DBMS Laboratory Observation of 10 experiments

This document outlines SQL commands for creating and manipulating tables in a relational database management system (RDBMS). It covers Data Definition Language (DDL) commands such as CREATE, ALTER, and DROP, as well as Data Manipulation Language (DML) commands like INSERT, SELECT, UPDATE, and DELETE. Additionally, it discusses constraints, joins, and subqueries, providing syntax and examples for each operation.

Uploaded by

Pendem Ajay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views33 pages

DBMS Laboratory Observation of 10 experiments

This document outlines SQL commands for creating and manipulating tables in a relational database management system (RDBMS). It covers Data Definition Language (DDL) commands such as CREATE, ALTER, and DROP, as well as Data Manipulation Language (DML) commands like INSERT, SELECT, UPDATE, and DELETE. Additionally, it discusses constraints, joins, and subqueries, providing syntax and examples for each operation.

Uploaded by

Pendem Ajay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Ex No: 1

DATE: Data Definition Language(DDL) and Data


Manipulation Commands (DML) Commands

AIM: To create a table and to write SQL queries to perform modifications to the table 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>;

CONSTRAINTS

Constraints are the rules enforced on the data columns of a table. This ensures the accuracy and
reliability of the data in the database.

NOT NULL − Ensures that a column cannot have NULL value.


UNIQUE − Ensures that all values in a column are different.
PRIMARY KEY − Uniquely identifies each row/record in a database table.
CHECK- The CHECK constraint ensures that all the values in a column satisfies certain
conditions.
Syntax
CREATE TABLE <table_name> (<colname1> <datatype><constraint name>,
<colname2> <datatype>,<colname3> < datatype>, …..…<colnamen> <datatype>);

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;

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)
GENDER CHARACTER
DESIG VARCHAR2(25)
DEPTNO NUMBER(4)
SALARY NUMBER(8,2)

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

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


4. Insert 5 records to the Department table
5. Insert 5 records to the EMPLOYEE table

6. Remove the field PIN from the EMPLOYEE table.

7. Delete one record from Department table

8. Delete the department table

9. Update the address field in the EMPLOYEE table

RESULT:
Thus the database is created and the DML commands were executed in RDBMS.
EX NO 2. CONSTRAINTS

AIM: To write and execute queries to implement constraints in RDBMS.

DEFINITION AND SYNTAX:

CONSTRAINTS

Constraints are a set of rules. It is used to maintain the quality of information. Constraints ensure
that the data insertion, updating, and other processes have to be performed in such a way that
data integrity is not affected. Constraints are the rules enforced on the data columns of a table.
These are used to limit the type of data that can go into a table.

TYPES OF CONSTRAINTS

 NOT NULL
 UNIQUE
 PRIMARY KEY
 CHECK
 FOREIGN KEY

Not Null Constraint

A not null constraint prevents null values.

Syntax:
CREATE TABLE <table_name>
( <column1> <datatype> not null, <column2> <datatype>);

Unique Constraint

A unique constraint prevents duplicate values. It ensures that all values in a column are different.

Syntax:
CREATE TABLE <table_name>
( <column1> <datatype> unique, <column2> <datatype>);

Check Constraint
A check constraint allows you to specify a condition for a column in a table. It ensures that the
values in a column satisfies a specific condition.
Syntax:
CREATE TABLE <table_name>
( <column1> <datatype>, <column2> <datatype> CHECK (<column_name> <condition>));

Primary Key Constraints


Primary key constraints define a column or series of columns that uniquely identify a
given row in a table. It is a combination of a NOT NULL and UNIQUE. It prevents duplicate
values and Null values.

Syntax:
CREATE TABLE <table_name>
(<column1> <datatype>, <column2> <datatype>,
PRIMARY KEY(<column1>));

Foreign Key Constraints:


A foreign key is a field in a table that matches the primary key column of
another table. The foreign key can be used to cross-reference tables.

Syntax:

CREATE TABLE <table_name1>(<column1> <datatype> ,<column2> <datatype>,


primary key(<column1>));

CREATE TABLE <table_name2>(<column1> <datatype> ,<column2> <datatype>


FOREIGN KEY(<column1>) REFERENCES <table_name1>(<column1>));

Adding a constraint to the table:

Syntax:
ALTER TABLE <table_name> ADD constraint <constraint name> primary
key(<column_name>);

Removing a constraint from the table:

Syntax:

ALTER TABLE <table_name> DROP constraint <constraint_name>;


EXERCISES

2. Create the following tables with the given specifications.

a. Table name: COURSE

NAME TYPE CONSTRAINTS


C_ID int Primary Key
C_NAME VARCHAR2(10) NOT NULL
DURATION int

b. Table name: STUDENT

NAME DATATYPE CONSTRAINTS

S_ID int Unique

S_NAME VARCHAR2(10) NOT NULL

AGE NUMBER(6,2) Check(Age>=18)

COUR_ID int Foreign Key(Refers C_ID)

3. Insert 5 records in both the relations.

4. Display all the records in both the relations.


5. Add a primary key constraint to EID field in the Employee table.
6. Remove the primary key constraint from the Employee table.
Ex No: 3 SELECT STATEMENT AND AGGREGATE FUNCTIONS
DATE:

AIM:

To query the database tables using different ‘where’ clause conditions and also implement
aggregate functions.

DEFINITIONS AND SYNTAX:

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 name1, column name2> 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. Filtering Data

Select command is used to filter data by providing a single or multiple conditions based on user
requirement.

Syntax:

i)Selected Rows and All Columns :

SELECT * FROM <tableName> where <condition>;

ii) Selected Columns And Selected Rows :

SELECT <ColumnName(1)> .. <ColumnName(n)> FROM <tableName> WHERE <condition>;


4. To Select by matching some patterns:

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

Syntax:
SELECT <columnname> FROM table_name WHERE <column name> LIKE “% or-“;

% : Matches any sub string.


- : Matches a single character.

5.Logical & Comparison Operator

Rows can be retrieved from the table by combining multiple conditions with ( AND
OR)Operator.
We can filter data by using the different logical operator(s) in where condition and can check
null value to using IS NULL or IS NOT NULL operators.

Syntax:
SELECT * FROM <tableName> WHERE <condition1> [AND|OR] <condition2>;

6.Sorting Data

We can retrieve rows from the table in ascending or descending order which is depending on the
condition specified with the select statement.ORDER BY Clause sorts results set based on the
column specified. It can only be used with SELECT Statements.
Sort order can be ASC(Ascending) or DESC(Descending). By default, Sort order is ascending ,
if any order is not specified.

Syntax:
SELECT * FROM <tableName> ORDER BY <ColumnName1> ASC;

7.Aggregate Functions

The functions that work on a set of numeric values are termed an aggregate function.
For example, COUNT is a function, which counts the number of occurrences of the values/field
passed by the user.

Syntax:
SELECT <aggregate functionName> (<ColumnName>) from <tableName>;

8. Select using IN and NOT 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 <columnname> FROM <table_name> WHERE
<column name> IN(value1,value2,……,value n);

SELECT <columnname> FROM <table_name> WHERE


<column name> NOT IN(value1,value2,……,value n);

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

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

SELECT <column name> FROM <table_name> WHERE <Column name> IS NOT NULL;

11. Select using GROUP BY:

The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of
some functions. i.e if a particular column has same values in different rows then it will arrange
these rows in a group.

Syntax:
SELECT <column name> FROM <table_name> GROUP BY <Column name>;
EXERCISES:

1. Create the following tables with the given specifications and appropriate constraints.

a. Table name: Assessment (reg_no, name, dept_name,mark1, mark2, mark3, total)


b. Table name: dept_details (dept_no, reg_no, dept_name, location).

2. Insert 5 rows to the above relations.


3. Display the department details which is located in ‘B’ block.
4. Display the student details those who got total below 150 and dept_name is ECE.
5. Find out the average value of Mark1 column.
6. Display the student details those who are having names starting with the letter ‘S’.
7. Find out the total number of records in the dept_details table.
8. Display the student details based on the highest total value to the lowest.
9. Display the department details with the dept_no 10,20 and 30.
10. Find out the highest total value for each department.
11. Display the department details which is not having location information.
12. Find out the minimum and maximum value in Mark3 column.
13. Display the student details those who got mark3 in the range of 80 -100.
14. Display the student details those who are studying in ‘CSE’ or ‘IT’ department.
Ex No 4. JOINS

AIM: To write and execute queries to perform different types of Joins in RDBMS.

DEFINITION AND SYNTAX:

JOIN

This command is used for joining two or more relations into a single relation. The
different types of joins are namely,
 Inner join
 Natural Join
 Outer join
*Left Outer Join
*Right Outer Join
*Full 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)NATURAL JOIN

A natural join in SQL combines rows from two or more tables based on the common column(s)
between them. The common columns on which the tables are joined must have the same name
and data type across the tables.

Syntax:

SELECT * FROM <tablename1> NATURAL JOIN <tablename2>;

3) OUTER JOIN

Outer joins are joins that return matched values and unmatched values from either or both tables.
There are a few types of outer joins:
*Left Outer Join
*Right Outer Join
*Full Outer Join
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>);

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>);
EXERCISES

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

a. Table name: PRODUCT

NAME DATA TYPE CONSTRAINTS


PROD_ID INT Primary Key
P_NAME VARCHAR2(10) NOT NULL
PRICE NUMBER(4,2)

b. Table name: ORDER

NAME TYPE CONSTRAINTS


CUST_ID INT PRIMARY KEY
CUST_NAME VARCHAR2(10) NOT NULL
P_ID INT
QUANTITY INT

2. Write a SQL query to perform NATURAL JOIN on both the relations and record the output.
3. Write a SQL query to perform EQUI JOIN on both the relations and record the output.
4. Write a SQL query to perform INNER JOIN on both the relations and record the output.
5. Write a SQL query to perform LEFT OUTER JOIN on both the relations and record the
output.
6. Write a SQL query to perform RIGHT OUTER JOIN on both the relations and record the
output.
7. Write a SQL query to perform FULL OUTER JOIN on both the relations and record the
output.
Ex No 5 SUB QUERIES

AIM
To execute sub queries or nested sub queries in RDBMS.

DEFINITION
A subquery is a SQL query nested inside a larger query.

 The sub query can be nested inside a SELECT, INSERT, UPDATE, or DELETE
statement or inside another subquery.

 A sub query is usually added within the WHERE Clause of another SQL SELECT
statement.

 You can use the comparison operators, such as >, <, or =. The comparison operator can
also be a multiple-row operator, such as IN, ANY, or ALL.

 A sub query is also called an inner query or inner select, while the statement containing a
sub query is also called an outer query or outer select.

 The inner query executes first before its parent query so that the results of an inner query
can be passed to the outer query.

Types of Subqueries
 Single Row Sub Query: Sub query which returns single row output. They mark the
usage of single row comparison operators, when used in WHERE conditions.

 Multiple row sub query: Sub query returning multiple row output. They make use of
multiple row comparison operators like IN, ANY, ALL. There can be sub queries
returning multiple columns also.

SQL ANY

 SQL ANY compares a value of the first table with all values of the second table and
returns the row if there is a match with any value.
SYNTAX
Select <fieldname> from <tablename> where <fieldname> = ANY ( select <fieldname>
from <tablename> where <condition>);
SQL ALL

 SQL ALL compares a value of the first table with all values of the second table and
returns the row if there is a match with all values.
SYNTAX
 Select <fieldname> from <tablename> where <fieldname> = ALL (select <fieldname>
from <tablename> where <condition>);

SUB QUERY WITH SELECT


SYNTAX
Select <fieldname> from <tablename> where <fieldname> <operator> ( select <fieldname> from
<tablename> where <condition>);

SUB QUERY WITH UPDATE


SYNTAX
Update <tablename> set < fieldname > = <newvalue> where <fieldname> <operator> ( select
<fieldname> from <tablename> where <condition>);
SUB QUERY WITH DELETE
SYNTAX
delete from <tablename> where <fieldname> <operator> ( select <fieldname> from
<tablename> where <condition>);

QUESTIONS
1.Create the following tables with the given specifications and appropriate constraints.

a. Table name: PASSENGER (PID, PNAME, AGE, GENDER)


b. Table name: BOOK_TICKET (PID, JOURNEY_DATE, SEAT_NO, SOURCE,
DESTINATION, FARE)
2.Insert 4 rows to the above relations.
3.Display the passenger details those who are travelling from ‘Chennai’.
4.Display the passenger details those who were paid highest fare.
5.Reduce the Fare by 2% for Senior citizens.
6.Display the passenger details those who are travelling to ‘Coimbatore’.
7.Display the passenger details those who were paid lowest fare.
8.Remove the passenger details those who were travelled on ’10th February 2023’
9.Display the passenger details those who are travelling on ’10th March 2023’

10.Display the passengers who had booked the journey from Mumbai to Chennai.

11.Display the Booking details of the passengers those who are having age of 25,30 or 35.
Ex No 6 TCL & DCL Commands

AIM
To execute TCL and DCL queries in RDBMS.

DEFINITION

TCL(Transactional Control Language ) COMMANDS

TCL statements help to control and manage transactions in database. It helps to maintain the
integrity of data within SQL statements.

 Commit
 Rollback
 Savepoint

Commit
Commit command is used to save the changes permanently into the database.

Syntax

Commit;

ROLLBACK

ROLLBACK is a transactional control language command in SQL. It lets a user undo those transactions
that aren't saved yet in the database. One can make use of this command if they wish to undo any
changes or alterations since the execution of the last COMMIT.

Syntax

rollback;

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

Data control language (DCL) Commands

Data control language (DCL) is used to access the stored data. It is mainly used for revoke and to grant
the user the required access to a database. It is a part of the structured query language (SQL). It helps in
controlling access to information stored in a database. It provides the administrators, to remove and set
database permissions to desired users as needed.

 Grant
 Revoke

GRANT Command

It is employed to grant a privilege to a user. GRANT command allows specified users to perform
specified tasks

Syntax

GRANT <privilege_name> on <tablename> to <user>;

Here, privilege names are SELECT,UPDATE,DELETE,INSERT & ALTER

REVOKE Command

It is employed to remove a privilege from a user. REVOKE helps the owner to cancel previously granted
permissions.

Syntax

REVOKE <privilege_name> on <tablename> from <user>;


QUESTIONS

1. Create the following tables with the given specifications and appropriate constraints.

a. Table name: CUSTOMER (CID, CNAME, BNAME,AGE)


b. Table name: ACCOUNT (ACNO, ATYPE, BALANCE, CID, BCODE)

2. Insert 4 rows to the above relations.


3. Save the changes permanently to the database.
4. Remove the records from Account relation if the balance is below 500.
5. Insert 1 more record to the Account relation.
6. Cancel the last two transactions.
7. Remove the records from Customer relation if the age is above 65.
8. Create a save point.
9. Remove the records from Customer relation which are having Bname as ‘CBE’.
10. Cancel the last transaction.
11. Display the records from both relations.
Ex. No: 7
Date:
PROCEDURES AND FUNCTIONS

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

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

2) To create a PL/SQL program which calls a procedure to print 0 if salary is less than 15000
else print 1.
3) To create and execute a function to multiply the given number by 1000

4) To create and execute a factorial program using function

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

OBJECTIVE:

To study and execute Triggers in RDBMS.

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:

Create the following Tables:


Account(Accno, CName,City,Balance)
Transaction(Tid,Accno,Amount,Items)
1) PL/SQL program to create a trigger before the user inserts the data into the Account table.

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

3) Write a PL/SQL program to create a trigger before the user changes the value of the
Amount(>10)in the Transaction table.

4) Write a PL/SQL Trigger to verify the minimumBalance(>500) before insertion on Account


table.
5) Create a database trigger to display the total number of records after inserting a record
into the Account table.

RESULT:

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


Ex No: 9

Views and Index

AIM:
To create views and index 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> where <condition>;
#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>=
< value>;

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

Syntax

DROP view <view_name>;

INDEX

An index can be used by the Oracle server to speed up the retrieval of rows by using a pointer
• Can reduce disk I/O by using a rapid path access method to locate data quickly
• Is independent of the table that it indexes
Syntax to create SQL index

CREATE INDEX <index_name> ON <table_name> (<column_name1>);

The Drop Index Command


An index can be dropped using SQL DROP command. Care should be taken when dropping an
index because performance may be slowed or improved.
DROP INDEX <index_name>;

QUESTIONS

Create the following Tables and insert 3 rows.

Book(BID,book_name,author_name,price,quantity)

Loan(BID,CID,Name,Dateof_issue)

1.Create a view for the Book table with the fields BID, book_name & author_name.
2.Display the details in the view.
3. Update the author_name in the view.
4.Drop the view.
5.Create a view for the Book table with records having quantity >100.
6.Create an index for the CID column in the Loan table.
7. Create an index for the BID and book_name columns in the Book table.
8.Drop the index.
Ex No 10 XML Database Validation

Aim
Validate XML document against a XML Schema (XSD) in an Oracle database.

Procedure
1.Register an XML Schema
First register the schema using the DBMS_XMLSCHEMA.REGISTERSCHEMA procedure. This
allows you to specify the XML schema using
a VARCHAR2, BFILE, BLOB, CLOB, XMLTYPE or URIType types. The parameter list is quite
important. By default the REGISTERSCHEMA procedure will create database types and object
tables, allowing documents to be shredded into object tables.

2. Validate XML Document (SCHEMAVALIDATE)


Create an XMLTYPE from some XML in a CLOB, then call the SCHEMAVALIDATE member
procedure to test the XML against the XML schema.

SQL> DECLARE
2 l_schema CLOB;
3 BEGIN
4

5 l_schema := '<?xml version="1.0" encoding="UTF-8" ?>


6 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
7
8 <!-- definition of simple elements -->
9 <xs:element name="orderperson" type="xs:string"/>
10 <xs:element name="name" type="xs:string"/>

11 <xs:element name="address" type="xs:string"/>


12 <xs:element name="city" type="xs:string"/>
13 <xs:element name="country" type="xs:string"/>
14 <xs:element name="title" type="xs:string"/>
15 <xs:element name="note" type="xs:string"/>
16 <xs:element name="quantity" type="xs:positiveInteger"/>
17 <xs:element name="price" type="xs:decimal"/>
18
19 <!-- definition of attributes -->

20 <xs:attribute name="orderid" type="xs:string"/>


21
22 <!-- definition of complex elements -->
23 <xs:element name="shipto">
24 <xs:complexType>
25 <xs:sequence>

26 <xs:element ref="name"/>
27 <xs:element ref="address"/>
28 <xs:element ref="city"/>
29 <xs:element ref="country"/>
30 </xs:sequence>
31 </xs:complexType>

32 </xs:element>
33
34 <xs:element name="item">
35 <xs:complexType>
36 <xs:sequence>
37 <xs:element ref="title"/>

38 <xs:element ref="note" minOccurs="0"/>


39 <xs:element ref="quantity"/>
40 <xs:element ref="price"/>
41 </xs:sequence>
42 </xs:complexType>
43 </xs:element>
44
45 <xs:element name="shiporder">
46 <xs:complexType>

47 <xs:sequence>
48 <xs:element ref="orderperson"/>
49 <xs:element ref="shipto"/>
50 <xs:element ref="item" maxOccurs="unbounded"/>
51 </xs:sequence>
52 <xs:attribute ref="orderid" use="required"/>

53 </xs:complexType>
54 </xs:element>
55
56 </xs:schema>';
57
58 DBMS_XMLSCHEMA.registerSchema(schemaurl => 'my_schema.xsd',

59 schemadoc => l_schema,


60 local => TRUE,
61 gentypes => FALSE,
62 gentables => FALSE,
63 enablehierarchy => DBMS_XMLSCHEMA.enable_hierarchy_none);
64

65 END;
66 /

PL/SQL procedure successfully completed.

SQL> SELECT schema_url FROM user_xml_schemas;


SCHEMA_URL

--------------------------------------------------------------------------------
my_schema.xsd

SQL> DECLARE

2 l_xml CLOB;
3 l_xmltype XMLTYPE;
4 BEGIN
5
6 l_xml := '<?xml version="1.0" encoding="UTF-8"?>
7 <shiporder orderid="889923">

8 <orderperson>John Smith</orderperson>
9 <shipto>
10 <name>Ola Nordmann</name>
11 <address>Langgt 23</address>
12 <city>4000 Stavanger</city>
13 <country>Norway</country>

14 </shipto>
15 <item>
16 <title>Empire Burlesque</title>
17 <note>Special Edition</note>
18 <quantity>1</quantity>
19 <price>10.90</price>

20 </item>
21 <item>
22 <title>Hide your heart</title>
23 <quantity>1</quantity>
24 <price>9.90</price>
25 </item>
26 </shiporder>';
27 l_xmltype := XMLTYPE(l_xml, 'my_schema.xsd');

28 l_xmltype.schemavalidate;
29 END;
30 /
PL/SQL procedure successfully completed.

SQL> DECLARE
2 l_xml CLOB;
3 l_xmltype XMLTYPE;
4 BEGIN
5

6 l_xml := '<?xml version="1.0" encoding="UTF-8"?>


7 <shiporder orderid="889923">
8 <orderperson>John Smith</orderperson>
9 <shipto>
10 <name1>Ola Nordmann</name1>
11 <address>Langgt 23</address>

12 <city>4000 Stavanger</city>
13 <country>Norway</country>
14 </shipto>
15 <item>
16 <title>Empire Burlesque</title>
17 <note>Special Edition</note>

18 <quantity>1</quantity>
19 <price>10.90</price>
20 </item>
21 <item>
22 <title>Hide your heart</title>
23 <quantity>1</quantity>

24 <price>9.90</price>
25 </item>
26 </shiporder>';
27
28 l_xmltype := XMLTYPE(l_xml, 'my_schema.xsd');
29 l_xmltype.schemavalidate;

30
31 END;
32 /
DECLARE
*
ERROR at line 1:

ORA-30937: No schema definition for 'name1' (namespace '##local') in parent


'/shiporder/shipto'
ORA-06512: at "SYS.XMLTYPE", line 354
ORA-06512: at line 29

Result
Thus the XML document was validated against a XML Schema (XSD) in an Oracle database.

You might also like