0% found this document useful (0 votes)
7 views

DBMS Manual Copy

Uploaded by

Arun Dhawan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

DBMS Manual Copy

Uploaded by

Arun Dhawan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

DATABASE MANAGEMENT

SYSTEMS

LABORATORY MANUAL

B.TECH
(II YEAR)
(2021-22)

Department of INFORMATION TECHNOLOGY

University Institute of Engineering & TechnologyPanjab

University, Chandigarh – 160014, India September, 2022


1
Objectives:

Students will have the ability to:


• Keep abreast of current developments to continue their own professional
development.
• To engage themselves in lifelong learning of Database management systems
theories and technologies this enables them to purse higher studies.
• To interact professionally with colleagues or clients located abroad and the
ability to overcome challenges that arises from geographic distance, cultural
differences, and multiple languages in the context of computing.
• Develop team spirit, effective work habits, and professional attitude in written
and oral forms, towards the development of database applications

Outcomes:

Students will be able to demonstrate their skills


 In drawing the ER, EER, and UML Diagrams.
 In analyzing the business requirements and producing a viable model for the
implementation of the database.
 In converting the entity-relationship diagrams into relational tables.
 To develop appropriate Databases to a given problem that integrates ethical,
social, legal, and economic concerns.

1
INDEX

S. No Topic Page no

1 Introduction SQL. 1

2 Various Data Types 11

3 Tables 13

4 My SQL Installation 14

5 DDL and DML Commands with Examples 24

6 Key Constrains-Normalization 30

7 Aggregate functions 37

8 Joins 52

9 Views 56

10 Index 62

11 PL/ SQL 65

12 Exception handling 73

13 Triggers 85

14 Cursors 86

15 Functions of PL/ SQL 87

2
INTRODUCTION
Database Management System
This model is like a hierarchical tree structure, used to construct a hierarchy of records

in the form of nodes and branches. The data elements present in the structure have Parent-

Child relationship. Closely related information in the parent-child structure is stored together

as a logicalunit. A parent unit may have many child units, but a child is restricted to have only

one parent.

The drawbacks of this model are:


The hierarchical structure is not flexible to represent all the relationship

proportions,which occur in the real world.

It cannot demonstrate the overall data model for the enterprise because of the non-
availability of actual data at the time of designing the data model.

It cannot represent the Many-to-Many relationship.

Network Model
It supports the One-To-One and One-To-Many types only. The basic objects in this model
are Data Items, Data Aggregates, Records and Sets.
It is an improvement on the Hierarchical Model. Here multiple parent-child relationships
are used. Rapid and easy access to data is possible in this model due to multiple access paths
to the data elements.

Relational Model

Does not maintain physical connection between


relationsData is organized in terms of rows and
columns in a table

The position of a row and/or column in a table is of no


importanceThe intersection of a row and column must give a
single value

Features of an RDBMS
The ability to create multiple relations and enter data into
themAn attractive query language

Retrieval of information stored in more than one table

An RDBMS product has to satisfy at least Seven of the 12 rules of Codd to be


acceptedas a full- fledged RDBMS.

3
Relational Database Management System
RDBMS is acronym for Relation Database Management System. Dr. E. F. Codd first
introduced the Relational Database Model in 1970. The Relational model allows data to be
represented in a simple row- column. Each data field is considered as a column and each
record is considered as a row. Relational Database is more or less similar to Database
Management S ystem.In relational model there is relation between their data elements. Data is
stored in tables. Tables have columns, rows and names. Tables can be related to each other if
each has a column with a common type of information. The most famous RDBMS packages
are Oracle, Sybase and Informix.

Simple example of Relational model is as follows :

Student Details Table


Roll_no Sname S_Address

1 Rahul Satelite
2 Sachin Ambawadi
3 Saurav Naranpura

Student Marksheet Table


Rollno Sub1 Sub2 Sub3

1 78 89 94
2 54 65 77
3 23 78 46

Here, both tables are based on students details. Common field in both tables is Rollno.
So wecan say both tables are related with each other through Rollno column.

Degree of Relationship
One to One (1:1)

One to Many or Many to One (1:M /


M: 1)Many to Many (M: M)

The Degree of Relationship indicates the link between two entities for a specified occurrence
ofeach.

4
One to One Relationship:

(1:1)1 1
Student Has Roll No.
One student has only one Rollno. For one occurrence of the first entity, there can be, at the
mostone related occurrence of the second entity, and vice-versa.

One to Many or Many to One Relationship:

(1:M/M: 1)1 M

Course Contains Students


As per the Institutions Norm, One student can enroll in one course at a time however, in one
course, there can be more than one student.

For one occurrence of the first entity there can exist many related occurrences of the second
entity and for every occurrence of the second entity there exists only one associated
occurrence of the first.

Many to Many Relationship:


(M:M)M M

Students Appears Tests

The major disadvantage of the relational model is that a clear-cut interface cannot be
determined. Reusability of a structure is not possible. The Relational Database now accepted
model on which major database system are built.

Oracle has introduced added functionality to this by incorporated object-oriented capabilities.


Now it is known is as Object Relational Database Management System (ORDBMS). Object-
oriented concept is added in Oracle8.

Some basic rules have to be followed for a DBMS to be relational. They are known as
Codd’s rules, designed in such a way that when the database is ready for use it encapsulates
the relational theory to its full potential. These twelve rules are as follows.

Page | 1
E. F. Codd Rules
1. The Information Rule
All information must be store in table as data values.
2. The Rule of Guaranteed Access
Every item in a table must be logically addressable with the help of a table name.

3. The Systematic Treatment of Null Values


The RDBMS must be taken care of null values to represent

missing orinapplicable information.

4. The Database Description Rule


A description of database is maintained using the same logical structures

withwhich data was defined by the RDBMS.

5. Comprehensive Data Sub Language


According to the rule the system must support data definition, view definition, data
manipulation, integrity constraints, authorization and transaction management
operations.

6. The View Updating Rule


All views that are theoretically updatable are also updatable by the system.

7. The Insert and Update Rule


This rule indicates that all the data manipulation commands must be
operationalon sets of rows having a relation rather than on a single row.

8. The Physical Independence Rule


Application programs must remain unimpaired when any changes are made in
storagerepresentation or access methods.

9. The Logical Data Independence Rule


The changes that are made should not affect the user’s ability to work with the
data.The change can be splitting table into many more tables.

10. The Integrity Independence Rule


The integrity constraints should store in the system catalog or in the database.
11. The Distribution Rule
The system must be access or manipulate the data that is distributed in other
systems.

Page | 1
12. The Non-subversion Rule
If a RDBMS supports a lower level language then it should not bypass

anyintegrity constraints defined in the higher level.

Object Relational Database Management System


Oracle8 and later versions are supported object-oriented concepts. A structure once created can

be reused is the fundamental of the OOP’s concept. So we can say Oracle8 is supported Object
Relational model, Object - oriented model both. Oracle products are based on a concept

known as a client-server technology. This concept involves segregating the processing of an


application between two systems. One performs all activities related to the database (server)

and the other performs activities that help the user to interact with the application (client). A
client or front-end database application also interacts with the database by requesting and

receiving information from database server. It acts as an interface between the user and the
database.

The database server or back end is used to manage the database tables and also respond to
client requests.

Introduction to ORACLE

ORACLE is a powerful RDBMS product that provides efficient and effective solutions for
major database features. This includes:

Large databases and space management


controlMany concurrent database users

High transaction processing


performanceHigh availability

Controlled availability

Industry accepted
standardsManageable
security

Database enforced
integrityClient/Server
environment

Distributed database systems


Portability

Page | 1
Compatib
ility
Connectiv
ity

An ORACLE database system can easily take advantage of distributed processing by using

itsClient/ Server architecture. In this architecture, the database system is divided into two parts:

A front-end or a client portion


The client executes the database application that accesses database information and interacts

withthe user.

A back-end or a server portion

The server executes the ORACLE software and handles the functions required for
concurrent,shared data access to ORACLE database

Page | 1
What is SQL and SQL*Plus
Oracle was the first company to release a product that used the English-based Structured

Query Language or SQL. This language allows end users to manipulate information of
table(primary database object). To use SQL you need not to require any programming
experience. SQL is a standard language common to all relational databases. SQL is database

language used for storing and retrieving data from the database. Most Relational Database

Management Systems provide extension to SQL to make it easier for application developer. A
table is a primary object of database used to store data. It stores data in form of rows and

columns.

SQL*Plus is an Oracle tool (specific program ) which accepts SQL commands and PL/SQL

blocksand executes them. SQL *Plus enables manipulations of SQL commands and PL/SQL
blocks. It also performs additional tasks such as calculations, store and print query results in
the form of reports, list column definitions of any table, access and copy data between SQL

databases and send messages to and accept responses from the user. SQL *Plus is a character

based interactive tool, that runs in a GUI environment. It is loaded on the client machine.

To communicate with Oracle, SQL supports the following categories of commands:


1. Data Definition Language
Create, Alter, Drop and Truncate

2. Data Manipulation Language


Insert, Update, Delete and Select

3. Transaction Control Language


Commit, Rollback and Save point

4. Data Control Language


Grant and Revoke

Before we take a look on above-mentioned commands we will see the data types
available inOracle.
Oracle Internal Data types
When you create a table in Oracle, a few items should be important, not only do you have to

give each table a name(e.g. employee, customer), you must also list all the columns or fields

(e.g. First_name, Mname, Last_name) associated with the table. You also have to specify what

type of information thattable will hold to the database. For example, the column Empno holds

numeric information. An Oracle database can hold many different types of data.
Data type Description
Char(Size) Stores fixed-length character data to store alphanumeric values,
with amaximum size of 2000 bytes. Default and minimum size is 1 byte.

Varchar2(Size) Stores variable-length character data to store alphanumeric values,


withmaximum size of 4000 bytes.

char(Size) Stores fixed-length character data of length size characters or bytes,


depending on the choice of national character set. Maximum size if determined by the
number of bytes required storing each character with an upper limit of 2000 bytes. Default
and minimum size is 1 character or 1 byte, depending on the character set.

Nvarchar2(Size) Stores variable-length character string having maximum length size


characters or bytes, depending on the choice of national character set. Maximum size is
determined by the number of bytes required to store each character, with an upper limit
of 4000 bytes.

Long Stores variable-length character data up to 2GB(Gigabytes). Its lenth would be


restricted based on memory space available in the computer.

11
The following are tabular representation of the above entities and relationships

BUS:
COLOUMN NAME DATA TYPE CONSTRAINT

Bus No varchar2(10) Primary Key

Source varchar2(20)

Destination varchar2(20)

Couch Type varchar2(20)

Reservation:
COLOUMN NAME DATA TYPE CONSTRAINT

PNRNo number(9) Primary Key

Journey date Date

No-of-seats integer(8)

Address varchar2(50)

Contact No Number(9) Should be equal to 10


numbers and not allow
other than numeric
BusNo varchar2(10) Foreign key
Seat no Number

12
Ticket:
COLOUMN NAME DATA TYPE CONSTRAINT

Ticket_No number(9) Primary Key


Journey date Date
Age int(4)
Sex Char(10)
Source varchar2(10)
Destination varchar2(10)
Dep-time varchar2(10)
Bus No Number2(10)

Passenger:
COLOUMN NAME DATA TYPE CONSTRAINT

PNR No Number(9) Primary Key

Ticket No Number(9) Foreign key

Name varchar2(15)
Age integer(4)
Sex char(10) (Male/Female)
Contact no Number(9) Should be equal to 10 numbers
and not allow other than
numeric

Cancellation:
COLOUMN NAME DATA TYPE CONSTRAINT

PNR No Number(9) Foriegn-key

Journey-date Date

Seat no Integer(9)
Contact_No Number(9) Should be equal to 10 numbers
and not allow other than
numeric

13
AIM: Installation of MySQL and practicing DDL & DML commands.

1. Steps for installing MySQL

Step1
Make sure you already downloaded the MySQL essential 5.0.45 win32.msi file. Double
clickon the .msi file.

Step2
This is MySQL Server 5.0 setup wizard. The setup wizard will install MySQL Server 5.0
release 5.0.45 on your computer. To continue, click next.

Step3
Choose the setup type that best suits your needs. For common program features select Typical
and it’s recommended for general use. To continue, click next.
er instance.
To continue, click next.

confirm retype the password. continue, click next.

Step13
Ready to execute? Clicks execute to continue.
2. Practicing DDL & DML
Commands Data Definition
Language
The data definition language is used to create an object, alter the structure of an object and also
drop already created object. The Data Definition Languages used for table definition can be
classified into following:

 Create table command


 Alter table command
 Truncate table command
 Drop table command

Creating of Tables on ROAD WAY TRAVELS:


Table is a primary object of database, used to store data in form of rows and columns. It is
created using following command:

Create Table <table_name> (column1 datatype(size), column2 datatype(size),column(n)


datatype(size));

Example:
SQL> create table Bus(Bus_No varchar(5), source varchar(20),
destinationvarchar(20),CouchType varchar2(10),fair number);
Table Created.
create table for the object-relation feature we will discuss it afterwards.

Desc command
Describe command is external command of Oracle. The describe command is used to view
thestructure of a table as follows.
Desc <table name>
SQL> desc bus;
Name Null? Type

BUS_NO NOT NULL INTEGER2(5)


SOURCE VARCHAR2(20)
DESTINATION VARCHAR2(20)
COUCH TYPE VARCHAR2(10)

FAIR NUMBER

SQL> Describe the university database

24
Extra:1.Create a table Universities DB

Reservation Table:

SQL> create table Reservation(PNR_NO Numeric(9), No_of_seats Number(8),


Addressvarchar(50), Contact_No Numeric(9), Status char(3));
Table created.
SQL> desc Reservation
Name Null? Type

PNR_NO NUMBER(9)
NO_OF_SEATS NUMBER(8)
ADDRESS VARCHAR2(50)
CONTACT_NO NUMBER(9)
STATUS CHAR(3)

Exercise: Projects have a project number, a sponsor name (e.g., NSF), a starting date,
anending date, and a budge

Cancellation Table:

SQL> create table Cancellation(PNR_NO Numeric(9), No_of_seats Number(8), Address


varchar(50), Contact_No Numeric(9), Status char(3));
Table created.
SQL> desc Cancellation
Name Null? Type

PNR_NO NUMBER(9)
NO_OF_SEATS NUMBER(8)
ADDRESS VARCHAR2(50)
CONTACT_NO NUMBER(9)
STATUS CHAR(3)

25
Ticket Table:

SQL> create table Ticket(Ticket_No Numeric(9) primary key, age number(4), sex
char(4)Not null, source varchar(2), destination varchar(20), dep_time varchar(4));
Table created.
SQL> desc
Ticket
Name Null? Type

TICKET_NO NOT NULL NUMBER(9)


AGE NUMBER(4)
SEX NOT NULL CHAR(4)
SOURCE VARCHAR2(2)
DESTINATION VARCHAR2(20)
DEP_TIME VARCHAR2(4)

Exercise: Each project is


managedas the project’s
principal inves-

tigator).
\

Alteration of

Table Addition of

Column(s)
Addition of column in table is done using:

26
Alter table <table_name> add(column1 datatype, column2 datatype _);
SQL> ALTER TABLE Passenger ADD FOREIGN KEY (PNR_NO) REFERENCES
Reservation(PNR_
NO);Table altered.

SQL> ALTER TABLE Cancellation ADD FOREIGN KEY (PNR_NO) REFERENCES


Reservation(PNR_
NO);Table altered.

SQL> alter table Ticket modify


tiketnonumber(10);Table altered.
Test ouput:

Deletion of Column

Alter table <table_name> drop column <column name>;


SQL>Alter Table Emp_master drop column comm;

Alter table <table_name> set unused column <column

name>;For Example,
SQL>Alter Table Emp_master set unused column comm;

Alter table <table_name> drop unused columns;

Alter table <table_name> drop (Column1, Column2, _);

27
Modification in Column

Modify option is used with Alter table_ when you want


to modify any existing column.

Alter table <table name> modify (column1 datatype,


_);
.

SQL> Alter table emp_master modify salary number(9,2);

Table altered.

28
AIM: Applying Constraints on Road Way Travels

Tables.Constraints

Domain Integrit y
constraints Entity Integrity
constraints Referential
Integrity constraint

Oracle allows programmers to define

constraintsColumn Level
Table Level
Example
SQL> create table Ticket ( Ticket_No Numeric(9) , age number(4), sex char(4) Not
null,source varchar(2), destination varchar(20), dep_time varchar(4));
Table created

Exercise: Create table professor by using not null constaint

Check Constraint
SQL> create table Reservation(PNR_NO Numeric(9), No_of_seats Number(8), Address
varchar(50), Contact_No Numeric(10) constraint ck check(length(contact_no)=10), Status
char(3));
Table created.Test

Exercise: Create table manage by using check constraints


Check constraint with alter command
SQL> alter table Ticket add constraint check_age
check(age>18);Table altered.

29
Entity Integrity Constraints
This type of constraints are further classified
intoUnique Constraint

Primary Key Constraint

Unique
Constraint
Example:
SQL> create table Ticket(Ticket_No Numeric(9) unique, age number(4), sex char(4) l, source
varchar(2), destination varchar(20), dep_time varchar(4));

Exercise: Create table Professor by using unique constraint

Unique constraint with alter

commandExample:
SQL> Alter table ticket add constraint uni1 Unique
(ticket_no);Table Altered.

Exercise: Alter table professor constraint

Primary key constraint at the column


levelExample:
SQL> create table Ticket(Ticket_No Numeric(9) constraint pk primary key, age
number(4),sex char(4) l, source varchar(2), destination varchar(20), dep_time
varchar(4));

30
Exercise: Apply primary key constraint on professor table SSN column.

Example:
SQL> create table vendor_master (ven_code varchar(5), ven_name varchar(20), venadd1
varchar(15), venadd2 varchar(15),vencity varchar(15), constraint pr_com primary key
(ven_code,ven_name));

Table created.Test

Referential Integrity Constraint


References constraint defined at column level
Test Example:
SQL> create table Passenger(PNR_NO Numeric(9) references reservation , Ticket_NO
Numeric(9) references ticket, Name varchar(20), Age Number(4), Sex char(10), PPNO
varchar(15));
Table
created.

Exercise: Apply References constraint University Database Department table.

Foreign Key Constraint with alter command


SQL> alter table reservation add constraint fk_icode foreign key (busno)
referencesbus(bus_no);

Table
altered.
Test

31
Exercise:Apply Foregin Key Constriant with alter on professor SSN with Department
No
Remember that when we add constraint at table level foreign key keyword is

must.SQL> delete from bus where bus_no = 2011;

a) Insert command

Insert into <table name> values(a list of data values);


Insert into <table name>(column list) values(a list of
data);

SQL> insert into emp_master (empno,ename,salary) values


(1122,‘Smith’,8000); 1row created.

Adding values in a table using Variable method.


SQL> insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex',
'&PPNO');
Enter value for pnr_no:
1 Enter value for
ticket_no: 1
Enter value for name:
SACHINEnter value for
age: 12
Enter value for sex: m
Enter value for ppno: sd1234
old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age,

'&Sex','&PPNO')
new 1: insert into Passenger values(1,1,'SACHIN',12,'m','sd1234')
1 row
created.

32
SQL> insert into Bus
values('&Bus_No','&source','&destination');Enter value for
bus_no: 1
Enter value for source: hyd
Enter value for destination:
ban
old 1: insert into Bus
values('&Bus_No','&source','&destination')new 1: insert into
Bus values('1','hyd','ban')

b) Simple Select Command

Select <column1>,<column2>,_,<column(n)> from <table name>;


SQL> select * from
emp_master;

Exercise: Display the all column of University Database of Department.

SQL> select empno, ename, salary from


emp_master;

Exercise: Display the all column of University Database of project table


Distinct Clause

SQL> select distinct deptno from


emp_master;

Exercise: Display the all column of University Database of project table by using distinct
clause.
Select command with where clause:
Select <column(s)> from <table name> where
[condition(s)];Example

SQL> select empno, ename from emp_master where hiredate = ‘1-jan-


00’;

DROP Table

SQL> drop table


Cancellation;Table
dropped.
Test Output:
33
Select command with DDL and DML command.
Table Creation with select statement
create table <table name> as select <columnname(s)> from <existing table name>;

Example

Insert data using Select

statementSyntax:

Inert into <tablename> (select <columns> from <tablename>);


Example
SQL> insert into emp_copy (select * from
emp_master);

Example
SQL> insert into emp_copy(nm) (select name from
emp_master);

Change Table Name


One can change the existing table name with a new name.

Syntax

Rename <OldName> To

<NewName>;Example:

SQL> Rename emp_master_copy1 To emp_master1;

Table
Renamed.

34
Aim: Practice queries using ANY, ALL, IN, EXISTS, UNION, INTERSECT
Union: The union operator returns all distinct rows selected by two or more queries.
SQL> select order_no from
order_master;

SQL> select order_no from


order_detail;

Example:

SQL>select order_no from order_master union select order_no


fromorder_detail;

Intersect :
Example:
SQL> select order_no from order_master intersect select order_no
fromorder_detail;

Minus :
Example:
SQL> select order_no from order_master minus select order_no from
order_detail;Test Output:

35
EXAMPLE QUERIES:
1. Display Unique PNR_NO of all Passengers

SQL> select PNR_NO from


passenger; Test

2.Display all the names of male Passengers

SQL> select Name from Passenger where Sex='m';

1. Display Ticket numbers and names of all


PassengersSQL> select Ticket_NO,Name from
Passenger;

2. Display the source and destination having journey time more than 10
hours.SQL> select source, destination from Ticket where
Journey_Dur>10;

3. Find the ticket number of passenger whose name starts with ‘S’ and ends with ‘H’SQL> select
Ticket_NO from Passenger where Name like'S%'and name like'%N';

4.Find the names of the passenger whose age is between


20 and 40SQL> select Name from Passenger where age between 20 and 40;

36
AIM: Practice Queries using Aggregate functions, Group By, Having Clause and
OrderClause.

1) Avg (Average): This function will return the average of values of the column
specified inthe argument of the column.

Example:
SQL> select avg(comm) from
emp_master;
:

2) Min (Minimum):
Example:
SQL>Select min(salary) from
emp_master;

3) Max (Maximum):

Example:
SQL>select max(salary) from emp_master;

4) Sum:
Example:
SQL>Select sum(comm) from emp_master;

37
5) Count:
Syntax: Count(*)
Count(column name)
Count(distinct column
nameExample:

SQL>Select count(*) from


emp_master;Test

Example:
SQL> select count(comm) from emp_master;
Test Output:

Example:
SQL>Select count(distinct deptno) from
emp_master;

Group By
Clause
Example:
SQL>select deptno,count(*) from emp_master group by deptno;

38
Having
Clause
Example
SQL> select deptno,count(*) from emp_master group by deptno having Deptno is not null;

Order By Clause
Select<column(s)>from<Table Name>where[condition(s)][order by<column name>[asc
/]desc ];

Example:
SQL> select empno,ename,salary from emp_master order by
salary;

SQL> select empno,ename,salary from emp_master order by salary


desc;

SQL *Plus having following operators.


Example
SQL> select salary+comm from
emp_master;Salary+comm

39
Example:
SQL> select salary+comm net_sal from emp_master;

SQL> Select 12*(salary+comm) annual_netsal from emp_master;


Comparison Operators:
Example:
SQL> select * from emp_master where salary between 5000 and
8000;

IN Operator:

SQL>Select * from emp_master where deptno


in(10,30);
LIKE Operator:

SQL>select*From emp_master where job like ‘M%’;

Logical operator:
SQL>select*From emp_master where job like „_lerk‟;

AND Operator:
SQL> select * from emp_master where salary > 5000 and comm <
750 ;

OR Operator:
SQL>select * from emp_master where salary > 5000 or comm <

750;

NOT Operator:
SQL>select*from emp_master where not salary=10000;

The Oracle Table Dual” SQL> select 2*2 from dual;


40
Single Row Functions (Scalar Functions):
String Functions:
1) Initcap (Initial Capital): This String function is used to capitalize first character of
theinput string.

Syntax: initcap(string)

Example:
SQL> select initcap(‘azure’) from

dual;

2) Lower: This String function will convert input string in to lower case.

Syntax: Lower(string)

Example:
SQL> select lower(‘AZURE’) from

dual;

3) Upper: This string function will convert input string in to upper case.
Syntax:Upper(string)

Example:
SQL> select upper(‘azure’) from dual;

4) Ltrim (Left Trim):


Syntax: Ltrim(string,set)

Example:
SQL>select ltrim(‘azuretech’,’azure’) from
dual

41
5) Rtrim (Right Trim): Syntax: Rtrim(string,set)

Example:
SQL>select rtrim(‘azuretrim’,’trim’) from

dual;

6) Translate:

Syntax: Translate(string1, string2, string3)

Example:
SQL>select translate(‘abcde’,’xaybzcxdye’,’tanzmulrye’) from

dual;

7) Replace:
Syntax:Replace(string, searchstring, replacestring)
Example:
SQL> select replace(‘jack and jue’,’j’,’bl’) from
dual;

8) Substr:

Syntax: Substr (string, starts [, count])

Example:
SQL>select substr (‘azuretechnology’,4,6) from

dual;Test Output:

42
9) Chr:
Syntax: Chr(number)

Example:
SQL>select chr(65) fromdual;

10) Lpad (Left Pad):

Syntax: Lpad(String,length,pattern)

Example:
Sql > select lpad(‘Welcome’,15,’*’) from

dual;

11) Rpad (Right Pad):


Syntax: Lpad(String,length,pattern)

Example:
SQL> select rpad(‘Welcome’,15,’*’) from
dual;Test Output:

12) Length: Syntax:Length(string)Example:

SQL>select length(‘auzre’) from dual;

43
Decode:
Syntax: Select decode(column name,if,then,if,then_ ..) from <tablename>;
Example:
SQL> select deptno,decode(deptno,10, ‘Sales’, 20, ‘Purchase’,
‘Account’)DNAME from emp_master;

13) Concatenation ( || ) Operator:


Syntax: Concat(string1,string2)
SQL> select concat(‘Azure’,’ Technology’) from

dual;

SQL> select ‘ename is ‘||ename from


emp_master;

Numeric Functions:
1) Abs (Absolute):
Syntax: Abs(Negetive Number)

Example:
SQL> select Abs(-10) from

dual;

44
2) Ceil
Syntax: Ceil(Number)

Example:

SQL>select Ceil (23.77) from dual;

3) Floor:
Syntax: Floor(Number)

Example:
SQL>select Floor(45.3) from dual;

4) Power:
Syntax: Power(Number, Raise)

Example:
SQL>Select power (5,2) from

dual;Test Output:

45
5) Mod:
Syntax: Mod(Number, DivisionValue)

Example:
SQL>select Mod(10,3) from dual;

6) Sign:
. SQL>select sign(-45) from dual;

SQL>Select sign(45) from


dual;
Date Function:
1) Add_Months:
Syntax: Add_Months(Date,no.of Months)

Example:
SQL> select Add_Months(sysdate,2) from
dual;Test Output:
2) Last_day:
Syntax: Last_day(Date)
Example:
SQL> select sysdate, last_day(sysdate) from
dual;

46
3) Months_Between:
Syntax: Months_Between(Date1,Date2)

Example:

SQL>select months_between(sysdate,’02-AUG-01’) onths_ from

dual;

4) Next_Day:.

Syntax: Next_Day(Date,Day)

Example:

SQL>select next_day(sydate, ‘sunday’) ext_ from

dual;

5) Round:
Syntax: Round (Date, [fmt])
Example:
SQL>Select round(‘4-sep-01’,’day’) ounded_ from
dual;

47
6) Trunc (Truncate):

Syntax: Trunc(Date,[fmt])
Example:
SQL>Select Trunc(‘4-sep-01’,’day’) runcated_ from
dual;

Conversion Functions:

To_Number(
)
To_Char
()
To_Date
()

To_Number:
Example:
SQL>Select to_number(‘50’) from
dual;

48
Syntax: To_char(no,[fmt])
Example:
SQL> select to_char(17145,’$099,999’) har_ from
dual;

Syntax: To_char(Date,[fmt])
Example:
SQL>select to_char(hiredate, ‘month dd yyyy’) ireDate_ from
emp_masterwhere salary = 10000;

2) To_Date:
Syntax: To_date(char,[fmt])
Example:
SQL>select to_date(’27 January 2000’,’dd/mon/yy’) ate_ from

dual;Test Output:

SQL>select*From Reservation UNION select*from


Cancellation;Test Output:
SQL>select pnr_no,count(*) as no occurrences from passenger group by pnr_no having
count(*)>0;
Test Output:

75
SQL> select PNR_NO,sum(No_of_seats) from Reservation group by
PNR_NO;
4. Find the number of seats booked in each class where the number of seats is greater than
1. SQL> select class, sum(No_of_seats) from Reservation where class='a 'or class='b' or
class= 'c'group by class having sum(No_of_seats)>1;

5. Find the total number of cancelled seats.


SQL> select sum(No_of_seats) from
Cancellation;
6. Creating and dropping views
AIM : Implement

Joins Syntax for


joining tables

select columns from table1, table2, ... where logical expression;

Simple Join :
Example:
SQL> select * from order_master , order_detail where Order_master.order_no =order_detail.or

Example:
SQL> select a.ename, a.salary, b.ename, b.salary from emp a, emp b where a.mgr = b.empno;

Outer Join :
Example:
SQL> select * from order_master a, order_detail b where a.order_no =
b.order_no(+);

AIM : Implement Sub Queries:


Subq

uery

Exam

ple:

SQL> select * from order_master where order_no = (select order_no from order_detail
whereorder_no = ‘O001’);
Test
SQL> select * from order_master where order_no = (select order_no from
77
order_detail);Test Output:
76
Example:
SQL>Select * from order_master where order_no = any(select order_no from
order_detail);

SQL> select * from order_master where order_no in(select order_no from


order_detail);

78
AIM : Implement Views:

Views
Syntax:Create View <View_Name> As Select statement;
Example:
SQL>Create View EmpView As Select * from Employee;
View created.
Syntax:Select columnname,columnname from <View_Name>;
Example:

SQL>Select Empno,Ename,Salary from EmpView where Deptno


in(10,30);

Updatable Views:
Syntax for creating an Updatable View:
Create View Emp_vw As
Select Empno,Ename,Deptno from Employee;View created.
SQL>Insert into Emp_vw values(1126,’Brijesh’,20); SQL>Update Emp_vw set Deptno=30
where Empno=1125;1 row updated.

SQL>Delete from Emp_vw where Empno=1122;


View defined from Multiple tables (Which have no Referencing clause):

For insert/modify:
For delete:

View defined from Multiple


tables (Which have been created
with a Referencingclause):
Syntax for creating a Master/Detail View
(Join View):
SQL>Create View EmpDept_Vw As

Select
a)Empno,a.Ename,a.Salar

y,a.Deptno,b.Dname
From Employee
a,DeptDet bWhere
a.Deptno=b.Deptno;

View created.
SQL>Insert into EmpDept_Vw values(…);
Test Output:
79
SQL>Update EmpDept_Vw set salary=4300 where

Empno=1125;Test Output:

SQL>Delete From EmpDept_Vw where Empno=1123;

SQL>Create View EmpRO As select * from Employee with Read


Only;
To Create View With Check option:

SQL>Create View EmpCk As Select * from Employee Where Deptno=10 WithCheck


Option;

80
Destroying a view:
Syntax: Drop View <View_Name>;
Example:
SQL>Drop View Emp_Vw;
SQL> create view v1 as select * from Passenger full natural join Reservation; View
created.
a) INSERT

SQL> insert into male_pass


values(&PNR_NO,&age);Test Output:

b) DROP VIEW

SQL> drop view male_pass;

AIM : Implement Indexes:


An index is an ordered list of the contents of a column, (or a group of columns) of a
table.
Select order_no,order_date,client_no From Sales_order Where client_no=’C00001’;

Client_no ROWID
Syntax: Create Index <Index Name> On <Table Name>(ColumnName);
Example:
SQL>Create Index idx_client_no On Client_master

(Client_no) ;

Creating Composite Index:


Syntax: Create Index <Index Name> On <Table Name>(ColumnName, ColumnName);
Example:
SQL>Create Index idx_sales_order On Sales_order
(Order_no,product_no) ;

Creation of Unique Index:


Syntax: Create Unique Index <Index Name> On <Table Name> (Column Name);
Syntax: Create Unique Index <Index Name> On <Table Name> (ColumnName,ColumnName);
Example:
SQL>Create Unique Index idx_client_no On Client_master
(Client_no);

81
Aim : Implementing Operations on relations using PL / SQL.
PL/SQL

Block

declare

<declaration of variables, constants, function,

procedure,cursor etc.>;
begin
<executable

statement(s)>;exception

<exception
handling>;end;

Example
Begin
Insert into emp(empno,ename)
values(100,’Shruti’); Insert into

emp(empno,ename) values(101,’Yesha’); End;

SQL>Set Serveroutput On

82
Example
Write a pl/sql program

welcome

Example
Insert value into dept table using pl/sql
Example
Write a pl/sql program To get the area of the circle provided the radius is

given.

83
Example
Write a pl/sql program To get the name and salary of specified
employee.

Example
Write a pl/sql program To get the name and salary of specified employee using %type
attribute.Test Output:
Example
Write a pl/sql program To get the name and salary of specified
employeeusing %type attribute

84
PL/SQL Control

StructuresExample
Write a pl/sql program Accept Number from a User and display Hello message if the
enterednumber is Positive.

Write a pl/sql program to Accept number from a user and find out whether it is Odd or Even.

Write a pl/sql program to Accept employee number from a user and increase its salary depends
onthe current salary as follows.
Salary Increment
>= 5000 12.5%; <5000 11%
Write a pl/ sql program by using Iterative Control / Loops
Write a pl/sql program by using while loop.

Test Output:

85
Write a pl/sql program by using FOR Loop

Exception HandlingExample
Example
Write a PL/SQL Block to insert add one row in employee table with employee number and
name.Display appropriate message using exception handling on duplication entry of employee
number.
Test Output:

86
Aim : Writing triggers
Database
Triggers:
Example
Test Output:

Example
Create or replace trigger upperdname before insert or update
on dept for each row
Test Output:
:
Example
Create or replace trigger emp_rest before insert or update or
delete onEmp.

Example
Create or replace trigger find_tran before insert or
updateor delete on dept for each row
Test Output:

Examples:
Create of insert trigger, delete trigger and update trigger.
Test Output:
b) Create Trigger updchek before update on Ticket For Each

Row

96 | P a g e

You might also like