Sunteți pe pagina 1din 104

DATABASE MANAGEMENT SYSTEMS LAB MANUAL

PROGRAMS LIST:
1) Creation, altering and droping of tables and inserting rows into a table (use constraints while
creating tables) examples using SELECT command.

2) Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSET, Constraints.
Example:- Select the roll number and name of the student who secured fourth rank in the class.

3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY, HAVING and
Creation and dropping of Views.

4) Queries using Conversion functions (to_char, to_number and to_date), string functions (Concatenation,
lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date
functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunc, round, to_char,
to_date)

5) i)Creation of simple PL/SQL program which includes declaration section, executable section and
exception –Handling section (Ex. Student marks can be selected from the table and printed for those who
secured first class and an exception can be raised if no records were found) ii)Insert data into student table
and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.

6) Develop a program that includes the features NESTED IF, CASE and CASE expression. The
program can be extended using the NULLIF and COALESCE functions.

7) Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR
Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE- APPLICATION ERROR.

8) Programs development using creation of procedures, passing parameters IN and OUT of


PROCEDURES.

9) Program development using creation of stored functions, invoke functions in SQL Statements and write
complex functions.

1
10) Program development using creation of package specification, package bodies, private objects, package
variables and cursors and calling stored packages.

11) Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR, WHERE
CURRENT of clause and CURSOR variables.

12) Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers

2
INDEX FOR LAB MANUL

3
S.NO PROGRAMS LIST PAGE NO

1 Oracle & SQL Introduction 5-8

2 Creation, altering and droping of tables and inserting rows into a 9 - 23


table (use constraints while creating tables) examples using SELECT
command
3 Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, 24 - 34
NOTEXISTS, UNION,
INTERSET, Constraints.
4 Queries using Aggregate functions (COUNT, SUM, AVG, MAX and 35 - 53
MIN), GROUP BY, HAVING and Creation and dropping of Views.

5 Queries using Conversion functions (to_char, to_number and 54 - 57


to_date), string functions (Concatenation, lpad, rpad, ltrim, rtrim,
lower, upper, initcap, length, substr and instr), date
functions (Sysdate, next_day, add_months, last_day,
months_between, least, greatest, trunc, round, to_char, to_date)
6 i)Creation of simple PL/SQL program which includes declaration 58 - 61
section, executable section and exception –Handling section (Ex.
Student marks can be selected from the table and printed for those
who secured first class and an exception can be raised if no records
were found) ii)Insert data into student table and use COMMIT,
ROLLBACK and SAVEPOINT in PL/SQL block.
7 Develop a program that includes the features NESTED IF, CASE and 62 - 67
CASE expression. The
program can be extended using the NULLIF and COALESCE
functions.
8 Program development using WHILE LOOPS, numeric FOR LOOPS, 68 - 70
nested loops using ERROR Handling, BUILT –IN Exceptions, USE
defined Exceptions, RAISE- APPLICATION ERROR.

9 Programs development using creation of procedures, passing 71 - 73


parameters IN and OUT of PROCEDURES.

10 Program development using creation of stored functions, invoke 74 - 75


functions in SQL Statements and write complex functions.

4
11 Program development using creation of package specification, 76 - 82
package bodies, private objects, package variables and cursors and
calling stored packages.
12 Develop programs using features parameters in a CURSOR, FOR 83 - 84
UPDATE CURSOR, WHERE CURRENT of clause and CURSOR
variables.
13 Develop Programs using BEFORE and AFTER Triggers, Row and 85 - 86
Statement Triggers and
INSTEAD OF Triggers

S.NO ADDITIONAL PROGRAMS LIST PAGE NO

1 Operators In Sql 87 - 98

2 Implementation of Different types of Joins 99 - 104

BRIEF HISTORY OF ORACLE DATABASE


The current version of Oracle Database is the result of over 35 years of innovative development.

The current version of Oracle Database is the result of over 30 years of innovative development. Highlights
in the evolution of Oracle Database include the following:

 Founding of Oracle
5
In 1977, Larry Ellison, Bob Miner, and Ed Oates started the consultancy Software Development
Laboratories, which became Relational Software, Inc. (RSI). In 1983, RSI became Oracle Systems
Corporation and then later Oracle Corporation.

 First commercially available RDBMS

In 1979, RSI introduced Oracle V2 (Version 2) as the first commercially available SQL-based
RDBMS, a landmark event in the history of relational databases.

 Portable version of Oracle Database

Oracle Version 3, released in 1983, was the first relational database to run on mainframes,
minicomputers, and PCs. The database was written in C, enabling the database to be ported to
multiple platforms.

 Enhancements to concurrency control, data distribution, and scalability

Version 4 introduced multiversion read consistency. Version 5, released in 1985, supported


client/server computing and distributed database systems. Version 6 brought enhancements to disk
I/O, row locking, scalability, and backup and recovery. Also, Version 6 introduced the first version of
the PL/SQL language, a proprietary procedural extension to SQL.

 PL/SQL stored program units

Oracle7, released in 1992, introduced PL/SQL stored procedures and triggers.

 Objects and partitioning

Oracle8 was released in 1997 as the object-relational database, supporting many new data types.
Additionally, Oracle8 supported partitioning of large tables.

 Internet computing

Oracle8i Database, released in 1999, provided native support for internet protocols and server-side
support for Java. Oracle8i was designed for internet computing, enabling the database to be deployed
in a multitier environment.

 Oracle Real Application Clusters (Oracle RAC)

6
Oracle9i Database introduced Oracle RAC in 2001, enabling multiple instances to access a single
database simultaneously. Additionally, Oracle XML Database (Oracle XML DB) introduced the
ability to store and query XML.

 Grid computing

Oracle Database 10g introduced grid computing in 2003. This release enabled organizations to
virtualize computing resources by building a grid infrastructure based on low-cost commodity
servers. A key goal was to make the database self-managing and self-tuning. Oracle Automatic
Storage Management (Oracle ASM) helped achieve this goal by virtualizing and simplifying
database storage management.

 Manageability, diagnosability, and availability

Oracle Database 11g, released in 2007, introduced a host of new features that enabled administrators
and developers to adapt quickly to changing business requirements. The key to adaptability is
simplifying the information infrastructure by consolidating information and using automation
wherever possible.

 Plugging In to the Cloud

Oracle Database 12c, released in 2013, was designed for the Cloud, featuring a new Multitenant
architecture, In-Memory column store, and support for JSON documents. Oracle Database 12c helps
customers make more efficient use of their IT resources, while continuing to reduce costs and
improve service levels for users.

OVERVIEW OF SQL (STRUCTURED QUERY LANGUAGE)


Structured Query Language(SQL) is a programming language used for storing and managing data in
RDBMS. Today almost all RDBMS(MySql, Oracle, Infomix, Sybase, MS Access) uses SQL as the standard
database language. SQL is used to perform all type of data operations in RDBMS.

SQL language is divided into four types of primary language statements: DML, DDL, DCL and TCL. Using
these statements, we can define the structure of a database by creating and altering database objects, and we

7
can manipulate data in a table through updates or deletions. We also can control which user can read/write
data or manage transactions to create a single unit of work.

The four main categories of SQL statements are as follows:

1. DDL (Data Definition Language)

2. DML (Data Manipulation Language)

3. DCL (Data Control Language)

4. TCL (Transaction Control Language)

DDL (Data Definition Language):

DDL statements are used to alter/modify a database or table structure and schema. These statements handle
the design and storage of database objects.

Command Description
Create To Create New Table Or Database
Alter For Alteration
Drop To Drop A Table
Rename To Rename A Table
Truncate To Remove All Rows (Complete Data) From A Table.
DML (Data Manipulation Language):

DML statements affect records in a table. These are basic operations we perform on data such as selecting a
few records from a table, inserting new records, deleting unnecessary records, and updating/modifying
existing records.

Command Description
Insert To Insert A New Row
Select Select Records From A Table
Update To Update Existing Row
Delete To Delete A Row
TCL : Transaction Control Language

These commands are to keep a check on other commands and their affect on the database. These commands
can annul changes made by other commands by rolling back to original state. It can also make changes
permanent.

Command Description
Commit To Permanently Save
8
Rollback To Undo Change
Savepoint To Save Temporarily
DCL : Data Control Language

Data control language provides command to grant and take back authority.

Command Description
Grant Grant Permission Of Right
Revoke Take Back Permission.
Save point

EXPERIMENT1
Use The Following Sample Data For Employee And Department Tables.

EMPNO } PRIMARY KEY PRIMARY KEY DEPTNO


ENAME DNAME
JOB LOC
MGR
HIREDAT
E
SAL
COMM
DEPTNO } FOREIGN KEY

9
Sample Department data:

DEPTNO DNAME LOC

10 ACCOUNTING NEW YORK

20 RESEARCH DALLAS

30 SALES CHICAGO

40 OPERATIONS BOSTON

Sample Employee data:

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7369 SMITH CLERK 7902 17-Dec-80 800 20
7499 ALLEN SALESMAN 7698 20-Feb-81 1600 300 30
7521 WARD SALESMAN 7698 22-Feb-81 1250 500 30
7566 JONES MANAGER 7839 2-Apr-81 2975 20
7654 MARTIN SALESMAN 7698 28-Sep-81 1250 1400 30
7698 BLAKE MANAGER 7839 1-May-81 2850 30
7782 RAJU MANAGER 7839 9-Jun-81 2450 10
7788 SCOTT ANALYST 7566 19-Apr-87 4000 20
7844 TURNER SALESMAN 7698 8-Sep-81 1500 0 30
7876 ADAMS CLERK 7788 23-May-87 1100 20
7900 JAMES CLERK 7698 3-Dec-81 950 30
7902 FORD ANALYST 7566 3-Dec-81 4000 20
7934 MILLER CLERK 7782 23-Jan-82 1300 10

10
AIM: Creation, altering and droping of tables and inserting rows into a table (use constraints while
creating tables) examples using SELECT command.

Creating Tables
create command is also used to create a table. We can specify names and datatypes of various columns
along. Following is the Syntax,
create table table-name
{
column-name1 datatype1,
column-name2 datatype2,
column-name3 datatype3,
column-name4 datatype4
};

create table command will tell the database system to create a new table with given table name and column
information.

Example for Creating a database called COMPANY consisting of two tables – EMP & DEPT

SQL> Create Table Dept (Deptno Number(2) Primary Key, Dname Varchar2(14), Loc Varchar2(13) );
Result : Table created
SQL> Desc dept;
Name Null? Type
----------------------------------------- -------- ----------------------------
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)

11
LOC VARCHAR2(13)

SQL> Create Table Emp (Empno Int Primary Key, Ename Varchar(20) , Job Varchar2(10) ,Mgr Int,
Hiredate Date, Sal Int ,Comm Int, Deptno Int, foreign key(deptno) references Dept(Deptno));
Result : Table created

SQL> desc emp;


Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)

Insert Rows Into DEPT table


SQL> INSERT INTO DEPT VALUES (10, 'ACCOUNTING', 'NEW YORK');
Result: 1 row inserted

SQL> INSERT INTO DEPT VALUES (20, 'RESEARCH', 'DALLAS');


Result: 1 row inserted

SQL> INSERT INTO DEPT VALUES (30, 'SALES', 'CHICAGO');


Result: 1 row inserted

SQL> INSERT INTO DEPT VALUES (40, 'OPERATIONS', 'BOSTON');


Result: 1 row inserted

Inserting Rows Into a Table


Insert command is used to insert data into a table.
Syntax1:
INSERT into table-name values(data1,data2,..)
Example
12
Insert Rows Into EMP table

SQL> INSERT INTO EMP VALUES(7369, 'SMITH', 'CLERK', 7902,


'17-DEC-1980', 800, NULL, 20);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7499, 'ALLEN', 'SALESMAN', 7698,


'20-FEB-1981', 1600, 300, 30);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7521, 'WARD', 'SALESMAN', 7698,


'22-FEB-1981', 1250, 500, 30);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7566, 'JONES', 'MANAGER', 7839,


'2-APR-1981', 2975, NULL, 20);
Result: 1 row inserted
SQL> INSERT INTO EMP VALUES(7654, 'MARTIN', 'SALESMAN', 7698,
'28-SEP-1981', 1250, 1400, 30);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7698, 'BLAKE', 'MANAGER', 7839,


'1-MAY-1981', 2850, NULL, 30);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7782, 'CLARK', 'MANAGER', 7839,


'9-JUN-1981', 2450, NULL, 10);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7788, 'SCOTT', 'ANALYST', 7566,


09-DEC-1982', 3000, NULL, 20);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7839, 'KING', 'PRESIDENT', NULL,


'17-NOV-1981', 5000, NULL, 10);
Result: 1 row inserted
13
SQL> INSERT INTO EMP VALUES(7844, 'TURNER', 'SALESMAN', 7698,
‘8-SEP-1981', 1500, 0, 30);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7876, 'ADAMS', 'CLERK', 7788,


'12-JAN-1983', 1100, NULL, 20);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7900, 'JAMES', 'CLERK', 7698,


'3-DEC-1981', 950, NULL, 30);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7902, 'FORD', 'ANALYST', 7566,


'3-DEC-1981', 3000, NULL, 20);
Result: 1 row inserted

SQL> INSERT INTO EMP VALUES(7934, 'MILLER', 'CLERK', 7782,


'23-JAN-1982', 1300, NULL, 10);
Result: 1 row inserted

Selecting a Table

Select command is used to retrieve data from a tables. It is the most used SQL query. We can retrieve
complete tables, or partial by mentioning conditions using WHERE clause.

Syntax

SELECT expressions FROM tables WHERE conditions;

Here expression is the column that we want to retrieve.

Query for Select all Records from EMP Table


SQL> SELECT * FROM EMP;

14
Query for Select all Records from DEPT Table
SQL> SELECT * FROM DEPT;

ALTERING TABLES
alter command is used for alteration of table structures. There are various uses of alter command,
such as,

 to add a column to existing table

 to rename any existing column

 to change datatype of any column or to modify its size.

 alter is also used to drop a column.

To Add Column to existing Table

Using alter command we can add a column to an existing table.

Syntax,

SQL> alter table table-name add(column-name datatype);

15
Example for adding employee age field into temp table

SQL> ALTER TABLE EMP ADD (EAGE VARCHAR2(10));

Result: Table Altered


To Modify an existing Column

Alter command is used to modify data type of an existing column .

Syntax,

SQL> alter table table-name modify(column-name datatype);

Example for modifying eage field

SQL> ALTER TABLE EMP MODIFY (EAGE NUMBER(2));


Result: Table Altered

To Drop a Column

alter command is also used to drop columns also. Following is the Syntax,

SQL> alter table table-name drop column (column-name);

Example for droping eage field

SQL> ALTER TABLE EMP DROP COLUMN EAGE;


Result: Table Altered

DROP COMMAND

drop command completely removes a table from database. This command will also destroy the table
structure.

Syntax,

SQL> drop table table-name

Example for dropping DEPT table

SQL> drop table DEPT;


16
Result: Table dropped

IMPLEMENTATION OF INTEGRITY CONSTRAINTS

Constraints are the rules enforced on data columns on table. These are used to limit the type of data that can
go into a table. This ensures the accuracy and reliability of the data in the database.

Constraints could be column level or table level. Column level constraints are applied only to one column,
whereas table level constraints are applied to the whole table.

Following are commonly used constraints available in SQL.

 UNIQUE Constraint: Ensures that all values in a column are different.

 NOT NULL Constraint: Ensures that a column cannot have NULL value.

 PRIMARY Key: Uniquely identified each rows/records in a database table.

 CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain
conditions.

 DEFAULT Constraint: Provides a default value for a column when none is specified.

 FOREIGN Key: Uniquely identified a rows/records in any another database table.

UNIQUE Constraint

 The UNIQUE constraint uniquely identifies each record in a database table.

 The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column
or set of columns.

 A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.

 Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.

Example:

The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is
created:
17
SQL> CREATE TABLE Persons
(
P_Id int UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Result: Table Created

 To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:

SQL> CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id,LastName)
);
Result: Table Created

UNIQUE Constraint on ALTER TABLE

 To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the
following SQL:

SQL> ALTER TABLE Persons ADD UNIQUE (P_Id);


Result: Table Altered

To DROP a UNIQUE Constraint

 To drop a UNIQUE constraint, use the following SQL:

SQL> ALTER TABLE Persons DROP unique(fieldname);


Result: Table Altered

18
NOT NULL Constraint

 By default, a table column can hold NULL values.

 The NOT NULL constraint enforces a column to NOT accept NULL values.

 The NOT NULL constraint enforces a field to always contain a value. This means that you cannot
insert a new record, or update a record without adding a value to this field.

 The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL
values:

Example

SQL> CREATE TABLE PersonsNotNull


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

PRIMARY KEY Constraint

 The PRIMARY KEY constraint uniquely identifies each record in a database table.

 Primary keys must contain UNIQUE values.

 A primary key column cannot contain NULL values.

 Most tables should have a primary key, and each table can have only ONE primary key.

PRIMARY KEY Constraint on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created:

SQL> CREATE TABLE Persons


(
P_Id int NOT NULL PRIMARY KEY,
19
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple
columns, use the following SQL syntax:

SQL> CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id,LastName)
);
PRIMARY KEY Constraint on ALTER TABLE

To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the

following SQL:

SQL> ALTER TABLE Persons ADD PRIMARY KEY (P_Id);

To DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

SQL> ALTER TABLE Persons DROP primary key;

CHECK Constraint

 The CHECK constraint is used to limit the value range that can be placed in a column.

 If you define a CHECK constraint on a single column it allows only certain values for this column.

20
 If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.

CHECK Constraint on CREATE TABLE

The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is created.
The CHECK constraint specifies that the column "P_Id" must only include integers greater than 0.

SQL> CREATE TABLE Persons


(
P_Id int NOT NULL CHECK (P_Id>0),
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use
the following SQL syntax:

SQL> CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0 AND City='Sandnes')
);

CHECK Constraint on ALTER TABLE

To create a CHECK constraint on the "P_Id" column when the table is already created, use the following
SQL:

SQL> ALTER TABLE Persons ADD CHECK (P_Id>0);

To DROP a CHECK Constraint

21
To drop a CHECK constraint, use the following SQL:

SQL> ALTER TABLE Persons DROP check;

DEFAULT Constraint

The DEFAULT constraint is used to insert a default value into a column.

The default value will be added to all new records, if no other value is specified.

DEFAULT Constraint on CREATE TABLE

The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is
created:

SQL> CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
);

DEFAULT Constraint on ALTER TABLE

To create a DEFAULT constraint on the "City" column when the table is already created, use the following
SQL:

SQL> ALTER TABLE Persons MODIFY City DEFAULT 'SANDNES';

To DROP a DEFAULT Constraint

To drop a DEFAULT constraint, use the following SQL:

SQL> ALTER TABLE Persons ALTER City DROP DEFAULT;

FOREIGN KEY Constraint

22
 A foreign key is a key used to link two tables together. This is sometimes called a referencing key.

 Foreign Key is a column or a combination of columns whose values match a Primary Key in a
different table.

 The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key
in the second table.

Example

Let's illustrate the foreign key with an example. Look at the following two tables:

 The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

 The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 2
4 24562 1

 Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table.

 The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

 The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

 The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

 The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.

The following SQL creates persons table

SQL> CREATE TABLE Persons


(
P_Id int PRIMARY KEY,

23
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255) );

The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:

SQL> CREATE TABLE Orders


(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int, FOREIGN KEY(P_Id) REFERENCES Persons(P_Id) );

SQL FOREIGN KEY Constraint on ALTER TABLE

To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use
the following SQL:

SQL> ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id);

To DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL:
SQL> ALTER TABLE Orders DROP foreign key(p_id);

EXPERIMENT2

Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSET, Constraints.

Use the following sample EMP Table


SQL> SELECT * FROM emp;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


------- ------- ----- ----- ----- ----- ------ ----------
7369 SMITH CLERK 7902 17-DEC-1980 800 20
7499 ALLEN SALESMAn 7698 20-FEB-1981 1600 300 30

24
7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30
7566 JONES MANAGER 7839 02-APR-1981 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-1981 1250 1400 30
7698 BLAKE MANAGEr 7839 01-MAY-1981 2850 30
7782 CLARK MANAGEr 7839 09-JUN-1981 2450 10
7788 SCOTT ANALYST 7566 19-APR-1987 3000 20
7839 KING PRESIDENT 17-NOV-1981 5000 10
7844 TURNER SALESMAN 7698 08-SEP-1981 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-1987 1100 20
7900 JAMES CLERk 7698 03-DEC-1981 950 30
7902 FORD ANALYST 7566 03-DEC-1981 3000 20
7934 MILLER CLERK 7782 23-JAN-1982 1300 10

ALL

The ALL comparison condition is used to compare a value to a list or subquery. It must be preceded by =, !
=, >, <, <=, >= and followed by a list or subquery.

When the ALL condition is followed by a list, the optimizer expands the initial condition to all elements of
the list and strings them together with AND operators, as shown below.

Example Queries:

To find Employees data whose employee salary should above 2000 and 3000 and 4000

Sql> SELECT empno, sal FROM emp WHERE sal > ALL (2000, 3000, 4000);
Result:
EMPNO SAL
---------- ----------
7839 5000
- Transformed to equivalent statement without ALL.

SQL> SELECT empno, sal FROM emp WHERE sal > 2000 AND sal > 3000 AND sal > 4000;
Result:
EMPNO SAL
---------- ----------

25
7839 5000

When the ALL condition is followed by a subquery, the optimizer performs a two-step transformation as
shown below.

SQL> SELECT e1.empno, e1.sal FROM emp e1 WHERE e1.sal > ALL (SELECT e2.sal
FROM emp e2 WHERE e2.deptno = 20);
Result:
EMPNO SAL
---------- ----------
7839 5000

ANY

The ANY comparison condition is used to compare a value to a list or subquery. It must be preceded by =, !
=, >, <, <=, >= and followed by a list or subquery.

When the ANY condition is followed by a list, the optimizer expands the initial condition to all elements of
the list and strings them together with OR operators, as shown below.

Example Queries:

To find Employees data whose employee salary having more than 2000 or 3000 or 4000

SQL> SELECT empno, sal FROM emp WHERE sal > ANY (2000, 3000, 4000);
Result:
EMPNO SAL
---------- ----------
7566 2975
7698 2850
7782 2450
7788 3000
7839 5000
7902 3000
-- Transformed to equivalent statement without ANY.

SQL> SELECT empno, sal FROM emp WHERE sal > 2000 OR sal > 3000 OR sal > 4000;
Result:
26
EMPNO SAL
---------- ----------
7566 2975
7698 2850
7782 2450
7788 3000
7839 5000
7902 3000

When the ANY condition is followed by a subquery, the optimizer performs a single transformation as
shown below.

SQL> SELECT e1.empno, e1.sal FROM emp e1 WHERE e1.sal > ANY (SELECT e2.sal
FROM emp e2 WHERE e2.deptno = 10);
Result:
EMPNO SAL
---------- ----------
7839 5000
7902 3000
7788 3000
7566 2975
7698 2850
7782 2450
7499 1600
7844 1500

The IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);

Example Queries:
27
To find employees data whose empno is 7839 or 7902
SQL> SELECT * FROM EMP WHERE EMPNO IN(7839, 7902);
Result:
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
------
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20

EXISTS and NOT EXISTS

The EXISTS condition is used in combination with a subquery and is considered to be met, if the subquery
returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Syntax

The syntax for the EXISTS condition in SQL is:

WHERE EXISTS ( subquery );

The syntax for the EXISTS condition in SQL is:

WHERE not EXISTS ( subquery );

Example Queries:
Using EXISTS constraint.
SQL> SELECT ENAME FROM EMP E WHERE EXISTS(SELECT DEPTNO FROM DEPT D WHERE
D.DNAME=’SALES’ AND D.DEPTNO=E.DEPTNO);
Result :

Using NOT EXISTS constraint.


SQL> SELECT ENAME FROM EMP E WHERE NOT EXISTS(SELECT DEPTNO FROM DEPT
D WHERE D.DNAME=’SALES’ AND D.DEPTNO=E.DEPTNO);
Result :
28
Union

UNION is used to combine the results of two or more Select statements. However it will eliminate duplicate
rows from its result set. In case of union, number of columns and datatype must be same in both the tables.

Example Query: To combine enames whose employee deptloc is DALLAS and whose employee DNAME
is ACCOUNTING.

SQL> SELECT ENAME FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO AND


D.LOC='DALLAS' UNION
SELECT ENAME FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO AND
D.DNAME='ACCOUNTING';
Result :

Intersect

Intersect operation is used to combine two SELECT statements, but it only retuns the records which are
common from both SELECT statements. In case of Intersect the number of columns and datatype must be
same. MySQL does not support INTERSECT operator.

29
Example Query: To find enames whose employee deptloc having DALLAS and DNAME having
RESEARCH.

SQL> SELECT ENAME FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO AND


D.LOC='DALLAS'
INTERSECT
SELECT ENAME FROM EMP E, DEPT D WHERE E.DEPTNO=D.DEPTNO AND
D.DNAME='RESEARCH';
Result :

EXPERIMENT 3

AGGREGATE FUNCTIONS

The SQL aggregate functions, as their title suggests are used to retrieve minimum and maximum
values from a column, to sum values in a column, to get the average of a column values, or to
simply count a number of records according to a search condition (or lack of it). The SQL
aggregate functions are

1. COUNT()

2. SUM()

3. MAX()

4. MIN()

5. AVG()

COUNT()

The COUNT() function returns the number of rows that matches a specified criteria.

30
The most commonly used SQL aggregate function is the COUNT function.

COUNT(column_name) Syntax

The COUNT(column_name) function returns the number of values (NULL values will not be counted) of
the specified column:

SELECT COUNT(column_name) FROM table_name;

COUNT(*) Syntax

The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name;

COUNT(DISTINCT column_name) Syntax

The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified
column:

SELECT COUNT(DISTINCT column_name) FROM table_name;

The MIN() Function

The MIN() function returns the smallest value of the selected column.

Syntax
SELECT MIN(column_name) FROM table_name;

The MAX() function

The MAX() function returns the largest value of the selected column.

Syntax
SELECT MAX(column_name) FROM table_name;

The AVG() Function


The AVG() function returns the average value of a numeric column.
Syntax
SELECT AVG(column_name) FROM table_name;

31
The SUM() Function
The SUM() function returns the total sum of a numeric column.
Syntax
SELECT SUM(column_name) FROM table_name;

Example Queries on Aggregate functions


 List minimum , maximum , average salaries of employee.

SQL>select min(sal),max(sal),avg(sal) from emp;

Result :

MIN(SAL) MAX(SAL) AVG(SAL)

800 5000 2073.21429

 Find how many job titles are available in employee table.

SQL>select count (distinct job) from emp;

Result :

COUNT(DISTINCTJOB)

 Find how much amount the company is spending towards salaries.


SQL>select sum (sal) from emp;
Result:
SUM(SAL)
---------
29025
GROUP BY AND ORDER BY AND HAVING CLAUSE

The SQL GROUP BY clause can be used in a SELECT statement to collect data across multiple records and
group the results by one or more columns.

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one
or more columns.

32
GROUP BY Syntax:
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1

The HAVING clause enables you to specify conditions that filter which group results appear in the final
results.

The WHERE clause places conditions on the selected columns, whereas the HAVING clause places
conditions on groups created by the GROUP BY clause.

The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER BY
clause if used. The following is the syntax of the SELECT statement, including the HAVING clause:

HAVING clause Syntax:

SELECT column1, column2


FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

ORDER BY allows sorting by one or more columns.

 Records can be returned in ascending or descending order.

ORDER BY syntax

The general syntax is:

SELECT column-names FROM table-name ORDER BY column-names

Examples:

Consider the EMPLOYEE table

 Display total salary spent for each job category.


33
SQL> select job,sum (sal) from emp group by job;

RESULT:
JOB SUM(SAL)
--------- ----------
CLERK 4150
SALESMAN 5600
PRESIDENT 5000
MANAGER 8275
ANALYST 6000

HAVING CLAUSE Example Query

SELECT DEPTNO, MAX (SAL) FROM EMP GROUP BY DEPTNO HAVING MAX
(SAL)>(SELECT MAX(SAL) FROM EMP WHERE DEPTNO=30);
RESULT:

CREATING AND DROPING VIEWS

Views can be considered as virtual tables. Generally speaking, a table has a set of definition, and it
physically stores the data. A view also has a set of definitions, which is build on top of table(s) or other
view(s), and it does not physically store the data.

Syntax

CREATE VIEW "VIEW_NAME" AS "SQL Statement";

Example : CREATING A VIEW:

SQL> CREATE VIEW LOCATION2 AS SELECT * FROM emp;


Result: view created
SQL> CREATE VIEW LOCATION3 AS SELECT * FROM emp where empno=7900;
Result: view created
34
DROPPING A VIEW:

DROP VIEW LOCATION2;


Result: view dropped

EXPERIMENT 4
Queries using Conversion functions (to_char, to_number and to_date), string functions (Concatenation, lpad,
rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date
functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunc, round, to_char,
to_date)

DATE AND TIME FUNCTIONS

SYSDATE
Returns the current system date of the database system.
Syntax:
SYSDATE
Example: To find system date
SQL> SELECT SYSDATE FROM dual;
Output:
28-May-2016

ADD_MONTHS(Date, months_to_add)

35
Returns the month by adding n months to the month of the date specified.
Syntax:
add_months( date1, n )
Example: To add 3 months to date
SQL> Select add_months('01-Aug-03', 3) from dual;
Output:
01-Nov-03

LAST_DAY(Date)
Returns the last day of the date specified.
Syntax:
LAST_DAY(date1)
Example: To find last day of date
SQL> Select last_day('2003/03/15') from dual;
Output:
Mar 31, 2003

MONTHS_BETWEEN(Date1, Date2)
Returns the number of months between date1 and date2
Syntax:
MONTHS_BETWEEN(date1,date2)
Example: To find months between 2 dates
SQL> Select months_between ('2003/01/01'),('2003/03/01' ) from dual;
Output:
2

ADDDATE(expr,days)
When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for
DATE_ADD().
SQL> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY) from dual;;
Output:
+---------------------------------------------------------+
| DATE_ADD('1998-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1998-02-02
36
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the
function is used in a string or numeric context.
SQL> SELECT CURDATE() from dual;;
Output:
+---------------------------------------------------------+
| CURDATE() |
+---------------------------------------------------------+
| 1997-12-15 |
+-------------

CURTIME()

Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function
is used in a string or numeric context. The value is expressed in the current time zone.

SQL> SELECT CURTIME() from dual;

Output:
| CURTIME() |
+---------------------------------------------------------+
| 23:50:26 |
+---------------

DATE(expr)

Extracts the date part of the date or datetime expression expr.

SQL> SELECT DATE('2003-12-31 01:02:03') from dual;


Output:
+---------------------------------------------------------+
| DATE('2003-12-31 01:02:03') |
+---------------------------------------------------------+
| 2003-12-31

37
DAYNAME(date)

Returns the name of the weekday for date.

SQL> SELECT DAYNAME('1998-02-05') from dual;


Output:
+---------------------------------------------------------+
| DAYNAME('1998-02-05') |
+---------------------------------------------------------+
| Thursday

DAYOFMONTH(date)

Returns the day of the month for date, in the range 0 to 31.

SQL> SELECT DAYOFMONTH('1998-02-03') from dual;


Output:
| DAYOFMONTH('1998-02-03') |
|3 |
DAYOFWEEK(date)

Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index values
correspond to the ODBC standard.

SQL> SELECT DAYOFWEEK('1998-02-03') from dual;


Output:
+---------------------------------------------------------+
|DAYOFWEEK('1998-02-03') |
+---------------------------------------------------------+
|3 |

DAYOFYEAR(date)

Returns the day of the year for date, in the range 1 to 366.

SQL> SELECT DAYOFYEAR('1998-02-03') from dual;


Output:
+---------------------------------------------------------+
38
| DAYOFYEAR('1998-02-03') |
+---------------------------------------------------------+
| 34

MINUTE(time)

Returns the minute for time, in the range 0 to 59.

SQL> SELECT MINUTE('98-02-03 10:05:03') from dual;


Output:
+---------------------------------------------------------+
| MINUTE('98-02-03 10:05:03') |
+---------------------------------------------------------+
|5 |

MONTH(date)

Returns the month for date, in the range 0 to 12.

SQL> SELECT MONTH('1998-02-03') from dual;;


Output:
+---------------------------------------------------------+
| MONTH('1998-02-03') |
+---------------------------------------------------------+
|2 |

MONTHNAME(date)

Returns the full name of the month for date.

SQL> SELECT MONTHNAME('1998-02-05') from dual;


Output:
+---------------------------------------------------------+
| MONTHNAME('1998-02-05') |
+---------------------------------------------------------+
| February |

SECOND(time)

Returns the second for time, in the range 0 to 59.

39
Output:
SQL> SELECT SECOND('10:05:03') from dual;;
+---------------------------------------------------------+
| SECOND('10:05:03') |
+---------------------------------------------------------+
|3

SUBDATE(expr,days)

When invoked with the INTERVAL form of the second argument, SUBDATE() is a synonym for
DATE_SUB(). For information on the INTERVAL unit argument, see the discussion for DATE_ADD().

SQL> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY) from dual;


Output:
+---------------------------------------------------------+
| DATE_SUB('1998-01-02', INTERVAL 31 DAY) |
+---------------------------------------------------------+
| 1997-12-02

TIME(expr)

Extracts the time part of the time or datetime expression expr and returns it as a string.

SQL> SELECT TIME('2003-12-31 01:02:03') from dual;


Output:
+---------------------------------------------------------+
| TIME('2003-12-31 01:02:03') |
+---------------------------------------------------------+
| 01:02:03

YEAR(date)

Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date.

SQL> SELECT YEAR('98-02-03') from dual;


Output:
+---------------------------------------------------------+
| YEAR('98-02-03') |
+---------------------------------------------------------+
| 1998

40
TIMESTAMPADD(unit,interval,datetime_expr)

Adds the integer expression interval to the date or datetime expression datetime_expr.

SQL> SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02') from dual;


Output:
+---------------------------------------------------------+
| TIMESTAMPADD(MINUTE,1,'2003-01-02') |
+---------------------------------------------------------+
| 2003-01-02 00:01:00

TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)

Returns the integer difference between the date or datetime expressions datetime_expr1 and datetime_expr2.

SQL> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01') from dual;


Output:
+---------------------------------------------------------+
| TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01') |
+---------------------------------------------------------+
|3

NUMERIC FUNCTIONS

ABS(number)
Returns the absolute positive value of an expression.
Syntax:
ABS(expression)
Example:
SQL> SELECT ABS(-1.0), ABS(0.0) from dual;
Output:
1.0 .0

CEIL(number)
Returns the smallest integer greater than, or equal to, the specified numeric expression.
Syntax:
CEIL (expression)
Example:
SQL> SELECT CEIL ($223.45), CEIL ($-223.45) from dual;
Output:
224.00 -223.00

FLOOR(number)
Returns the largest integer less than, or equal to, the specified numeric expression.
Syntax:
41
FLOOR(expression)
Example:
SQL> SELECT FLOOR($223.45), FLOOR ($-223.45) from dual;
Output:
223.00 -224.00

MOD(number, divisor)
Returns the remainder of the division from 2 integer values.
Syntax:
MOD(dividend, divisor)
Example:
SQL> SELECT MOD(20,3) from dual;
Output:
2

POWER(number, power)
Returns the exponential value for the numeric expression.
Syntax:
POWER(number, power)
Example:
SQL> SELECT POWER(2.0, 3.0) from dual;
Output:
8.0

SIGN(number)
Returns the sign i.e. positive or negative value for the numeric expression. It returns -1 for negative
expressions, a value of 0 for zero
Syntax:
SIGN(number)
Example:
SQL> SELECT SIGN(4) from dual;
Output:
1

ROUND(number, precision)
Returns the numeric value rounded off to the next value specified.
Syntax:
ROUND(number, number of places)
Example:
SQL> SELECT ROUND(1.3456, 2) from dual;

42
SQRT(number)
Returns the square root value of the expression.
Syntax:
SQRT(number)
Example:
SQL> SELECT SQRT(4.0) from dual;
Output:
2.0

TRUNC(number, precision)
Returns a numeric value that truncate to the specific places
Syntax:
TRUNC (number,places)
Example:
SQL> SELECT TRUNC (1.3456, 2) from dual;
Output:
1.34

ACOS(X)

This function returns the arccosine of X. The value of X must range between -1 and 1 or NULL will be
returned. Consider the following example:

SQL> SELECT ACOS(1) from dual;


Output:
+---------------------------------------------------------+
| ACOS(1) |
| 0.000000

ASIN(X)

The ASIN() function returns the arcsine of X. The value of X must be in the range of -1 to 1 or NULL is
returned.

SQL> SELECT ASIN(1) from dual;


Output:
+---------------------------------------------------------+
| ASIN(1) |
+---------------------------------------------------------+
| 1.5707963267949

43
ATAN(X)

This function returns the arctangent of X.

SQL> SELECT ATAN(1) from dual;


Output:
+---------------------------------------------------------+
| ATAN(1) |
+---------------------------------------------------------+
| 0.78539816339745
COS(X)

This function returns the cosine of X. The value of X is given in radians.

SQL>SELECT COS(90) from dual;


Output:
+---------------------------------------------------------+
| COS(90) |
+---------------------------------------------------------+
| -0.44807361612917

COT(X)

This function returns the cotangent of X. Consider the following example:

SQL>SELECT COT(1) from dual;


Output:
+---------------------------------------------------------+
| COT(1) |
+---------------------------------------------------------+
| 0.64209261593433

SIN(X)
This function returns the sine of X. Consider the following example:
SQL>SELECT SIN(90) from dual;
Output:
+---------------------------------------------------------+
| SIN(90) |
+---------------------------------------------------------+
| 0.893997

TAN(X)

This function returns the tangent of the argument X, which is expressed in radians.

SQL>SELECT TAN(45) from dual;

44
Output:
+---------------------------------------------------------+
| TAN(45) |
+---------------------------------------------------------+
| 1.619775 |
+-----------

EXP(X)

This function returns the value of e (the base of the natural logarithm) raised to the power of X.

SQL>SELECT EXP(3) from dual;


Output:
+---------------------------------------------------------+
| EXP(3) |
+---------------------------------------------------------+
| 20.085537

GREATEST(n1,n2,n3,..........)

The GREATEST() function returns the greatest value in the set of input parameters (n1, n2, n3, a nd so on).
The following example uses the GREATEST() function to return the largest number from a set of numeric
values:

SQL>SELECT GREATEST(3,5,1,8,33,99,34,55,67,43) from dual;


Output:
+---------------------------------------------------------+
| GREATEST(3,5,1,8,33,99,34,55,67,43) |
+---------------------------------------------------------+
| 99 |
+------------------------------------------------

LEAST(N1,N2,N3,N4,......)

The LEAST() function is the opposite of the GREATEST() function. Its purpose is to return the least-valued
item from the value list (N1, N2, N3, and so on). The following example shows the proper usage and output
for the LEAST() function:

SQL>SELECT LEAST(3,5,1,8,33,99,34,55,67,43) from dual;


Output:
+---------------------------------------------------------+
| LEAST(3,5,1,8,33,99,34,55,67,43) |
|1
|

45
LOG
LOG returns the logarithm, base n2, of n1. The base n1 can be any positive value other than 0 or 1 and n2
can be any positive value.

Example

The following example returns the log of 100:

SQL> SELECT LOG(10,100) "Log base 10 of 100" FROM DUAL;


Output:
Log base 10 of 100
------------------
2

STRING FUNCTIONS

ASCII
The SQL function ASCII converts a character in the numeric ascii value. If the string is larger as one
character then the ascii value of the first characters is return.
Syntax:
ASCII( string )

Examples:

SQL> SELECT ASCII('A') from dual;

Output:

Return Values: 65

CHR()

The function CHR converts an integer value in a single character.

Syntax
: CHR( expression )

Examples:

46
SQL> SELECT CHR( 65 ) from dual;
Output:
Return Values: A

CONCAT(string1, string2)
Combines result from several different fields.
Syntax:
CONCAT(string1, string2)
Example:
SQL> SELECT CONCAT(empfirst_name, emplast_name) FROM employee

INITCAP(string)
Returns a string with each word's first character in uppercase and the rest in lowercase.
Syntax:
INITCAP(character-expression)
Example:
SQL> SELECT initcap(empfirst_name) FROM emp12;
Output:
Analyst

LENGTH(string)
Returns the length of the string. Also called as LEN()in sql server.
Syntax:
LENGTH(string)
Example:
SQL> select LENGTH (empfirst_name) from employee Where emp_id=’1’
Output:
6

LPAD(string, #,padding_char)
Used to pad the string to left to length n characters. string_pad parameter is optional. If not specified, string
will be padded spaces to the left-side of string.
Syntax:
lpad ('string', n [, 'string_pad')

47
Example:
SQL> Select lpad('tech', 7) from dual;
Output:
‘ tech’

RPAD(string, #,padding_char)

Used to pad the string to right to length n characters.string_pad parameter is optional. If not specified, string
will be padded spaces to the right-side of string.
Syntax:
rpad ('string', n [, 'string_pad')
Example:
SQL> Select rpad('tech', 7) from dual;
Output:
‘tech ’

LTRIM(string,searchString)
Used to remove all white spaces from the beginning of the string.
Syntax:
Ltrim(string)
Example:
SQL> SELECT LTRIM(' Sample ') from dual;
Output:
‘Sample ’

RTRIM(string,searchString)
Used to remove all white spaces at the end of the string.
Syntax:
rtrim(string)
Example:
SQL> SELECT RTRIM(' Sample ') from dual;
Output:
‘ Sample’

REPLACE(string,searchString,replacement)

48
Used to replace the string1, having string2 with string3.
Syntax:
REPLACE(string1, string2, string3)
Example:
SQL> SELECT REPLACE(branch, 'st', 'saint') FROM company;

SUBSTR(string, start, length)


Displays the string Starting with the th character in string and select the next characters.
Syntax:
SUBSTR(str,pos,len):
Example:
SQL> SELECT SUBSTR(‘San Diego’,2,4) from dual;
Output:
‘an D’

UPPER(string)
Returns a string in lowercase converted to uppercase
Syntax:
UPPER(string):
Example:
SQL> SELECT UPPER(‘sAnd’) from dual;
Output: SAND
LOWER(string)
Returns a string in uppercase converted to lowercase
Syntax:
LOWER(string):
Example:
SQL> SELECT LOWER(‘sANd’) from dual;
Output:
sand

BIN(N)
Returns a string representation of the binary value of N, where N is a longlong (BIGINT) number.
SQL> SELECT BIN(12) from dual;
Output:
+---------------------------------------------------------+
49
| BIN(12) |
+---------------------------------------------------------+
| 1100

INSERT(str,pos,len,newstr)
Returns the string str, with the substring beginning at position pos and len characters long replaced by the
string newstr.
SQL> SELECT INSERT('Quadratic', 3, 4, 'What')v from dual;
Output:
| INSERT('Quadratic', 3, 4, 'What') |
+---------------------------------------------------------+
| QuWhattic

INSTR(str,substr)

Returns the position of the first occurrence of substring substr in string str.

SQL> SELECT INSTR('foobarbar', 'bar') from dual;


Output:
+---------------------------------------------------------+
| INSTR('foobarbar', 'bar') |
|4

LEFT(str,len)

Returns the leftmost len characters from the string str, or NULL if any argument is NULL.

SQL> SELECT LEFT('foobarbar', 5) from dual;


Output:
+---------------------------------------------------------+
| LEFT('foobarbar', 5) |
+---------------------------------------------------------+
| fooba

50
REPEAT(str,count)

Returns a string consisting of the string str repeated count times. If count is less than 1, returns an empty
string. Returns NULL if str or count are NULL.

SQL> SELECT REPEAT('SQL', 3) from dual;


Output:
+---------------------------------------------------------+
| REPEAT('SQL', 3) |
+---------------------------------------------------------+
| SQLSQLSQL

REVERSE(str)

Returns the string str with the order of the characters reversed.

SQL> SELECT REVERSE('abcd') from dual;


Output:
+---------------------------------------------------------+
| REVERSE('abcd') |
+---------------------------------------------------------+
| dcba

RIGHT(str,len)

Returns the rightmost len characters from the string str, or NULL if any argument is NULL.

SQL> SELECT RIGHT('foobarbar', 4) from dual;


Output:
+---------------------------------------------------------+
| RIGHT('foobarbar', 4) |
+---------------------------------------------------------+
| rbar

STRCMP(str1, str2)

Compares two strings and returns 0 if both strings are equal, it returns -1 if the first argument is smaller than
the second according to the current sort order otherwise it returns 1.
51
SQL> SELECT STRCMP('MOHD', 'MOHD') from dual;
Output:
+---------------------------------------------------------+
| STRCMP('MOHD', 'MOHD') |
+---------------------------------------------------------+
|0

COVERSION FUNCTIONS

1. TO_CHAR

The TO_CHAR function converts a DATETIME, number.

Syntax

TO_CHAR(datetime-exp, [datetime-fmt,] [option setting])

or

TO_CHAR(num-exp, [num-fmt,] [nlsparams])

Example:
SQL> SELECT TO_CHAR(1210.73, '9999.9') from dual;
Result: ' 1210.7'
SQL> SELECT TO_CHAR(1210.73, '$9,999.00') from dual;
Result: ' $1,210.73'

SQL> SELECT TO_CHAR(21, '000099') from dual;


Result: ' 000021'
SQL> SELECT TO_CHAR(sysdate, 'yyyy/mm/dd') from dual;
Result: '2003/07/09'

SQL> SELECT TO_CHAR(sysdate, 'Month DD, YYYY') from dual;


Result: 'July 09, 2003'

2. TO_NUMBER function

The TO_NUMBER function converts a character string of type CHAR or VARCHAR2 into a number.

The Syntax for the TO_NUMBER Function

52
TO_NUMBER(character_string, format, NLS_Params)

The following example converts the string 97.13 to a number using TO_NUMBER():

SQL> SELECT TO_NUMBER('97.13') FROM dual;


Output:
TO_NUMBER('97.13')
------------------
97.13

3. TO_DATE

Convert an expression to a date value.

Syntax

to_date(char[,'format'[,nls_lang])

char String expression that will be converted to a date


format Date format to use.
nls_lang The international language to use.

to_date will convert either a character string or an expression into a date value.

The 'format' must be a valid DATE format: YYYY=year, MM=month, DD=Day, HH=Hour, Mi=Minute
If no format is specified Oracle will assume the default date format has been supplied in char.

Example 1

SQL>SELECT TO_DATE('20100105', 'YYYYMMDD') FROM DUAL;

Result:

2010 01 05 00:00:00

Example 2

SQL> SELECT TO_DATE('1999-JAN-05', 'YYYY-MON-DD') FROM DUAL;

Result:

53
1999 01 05 00:00:00

EXPERIMENT 5

5. i)Creation of simple PL/SQL program which includes declaration section, executable section and
exception –Handling section (Ex. Student marks can be selected from the table and printed for those who
secured first class and an exception can be raised if no records were found)
ii) Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.

Introduction to PL/SQL

The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as
procedural extension language for SQL and the Oracle relational database.

54
PL/SQL is a very secure functionality tool for manipulating, controlling, validating, and restricting
unauthorized access data from the SQL database.

Using PL/SQL we can improve application performance. It also allows to deal with errors so we can
provide user friendly error messages.

PL/SQL have a great functionality to display multiple records from the multiple tables at the same time.

PL/SQL is capable to send entire block of statements and execute it in the Oracle engine at once.

Advantages PL/SQL

Procedural language support : PL/SQL is a development tools not only for data manipulation futures but
also provide the conditional checking, looping or branching operations same as like other programming
language.

Reduces network traffic : This one is great advantages of PL/SQL. Because PL/SQL nature is entire
block of SQL statements execute into oracle engine all at once so it's main benefit
is reducing the network traffic.

Error handling : PL/SQL is dealing with error handling, It's permits the smart way handling the
errors and giving user friendly error messages, when the errors are encountered.

Declare variable : PL/SQL gives you control to declare variables and access them within the block. The
declared variables can be used at the time of query processing.

Intermediate Calculation : Calculations in PL/SQL done quickly and efficiently without using Oracle
engines. Thisimproves the transaction performance.

Portable application : Applications are written in PL/SQL are portable in any Operating system.
PL/SQL applications are independence program to run any computer.

PL/SQL is block structured language divided into three logical blocks.

BEGIN block and END; keyword are compulsory, and other two block DECLARE and EXCEPTION are
optional block. END; is not a block only keyword to end of PL/SQL program.

PL/SQL block structure

55
Figure - PL/SQL block Structure

AIM: Creation of simple PL/SQL program which includes declaration section, executable section and
exception –Handling section (Ex. Student marks can be selected from the table and printed for those who
secured first class and an exception can be raised if no records were found)

SQL> SET SERVEROUTPUT ON


SQL> Declare
2 empname varchar2(20);
3 salary integer;
4 eno integer:=&eno;
5 Begin
6 Select ename,sal into empname,salary
7 From EMP
8 Where empno=eno;
9 Dbms_output.put_line(empname||' '||salary);
10 Exception
11 When no_data_found then
12 Dbms_output.put_line('No empno found');
13 End;
14 /
Enter value for eno: 4

56
old 4: eno integer:=&eno;
new 4: eno integer:=4;
No empno found

PL/SQL procedure successfully completed.

COMMIT, ROLLBACK and SAVEPOINT

Oracle PL/SQL transaction oriented language. Oracle transactions provide a data integrity. PL/SQL
transaction is a series of SQL data manipulation statements that are work logical unit. Transaction is an
atomic unit all changes either committed or rollback.

At the end of the transaction that makes database changes, Oracle makes all the changes permanent save
or may be undone. If your program fails in the middle of a transaction, Oracle detect the error and
rollback the transaction and restoring the database.

You can use the COMMIT, ROLLBACK, SAVEPOINT, and SET TRANSACTION command to control
the transaction.

1. COMMIT : COMMIT command to make changes permanent save to a database during the current
transaction.

2. ROLLBACK : ROLLBACK command execute at the end of current transaction and undo/undone
any changes made since the begin transaction.

3. SAVEPOINT : SAVEPOINT command save the current point with the unique name in the
processing of a transaction.

4. AUTOCOMMIT : Set AUTOCOMMIT ON to execute COMMIT Statement automatically.

5. SET TRANSACTION : PL/SQL SET TRANSACTION command set the transaction properties
such as read-write/read only access.

AIM: Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.

Begin
insert into student(sid,sname,branch,sage,marks) values (512,'gourav','cse',22,89.4);
Savepoint A;
57
insert into student(sid,sname,branch,sage,marks) values (524,'gireesh','ece',21,90.5);
Savepoint B;
insert into student(sid,sname,branch,sage,marks) values (540,'goutam','eee',20,92.6);
Savepoint C;
Rollback to B;
Commit;
End;

SELECT * FROM STUDENT WHERE SNAME=’GOUTAM’;

ROLLBACK TO SAVEPOINT A;

SELECT * FROM STUDENT WHERE SNAME=’GIREESH’;

SELECT * FROM STUDENT WHERE SNAME=’GOURAV’;

EXPERIMENT 6
Develop a program that includes the features NESTED IF, CASE and CASE expression. The
program can be extended using the NULLIF and COALESCE functions.

PL/SQL Conditional Control

58
PL/SQL IF THEN ELSE conditional control statements. PL/SQL Conditional Control two type: IF
THEN ELSE statement and CASE statement,

PL/SQL IF statement check condition and transfer the execution flow on that matched block depending
on a condition. IF statement execute or skip a sequence of one or more statements. PL/SQL IF statement
four different type,

1. IF THEN Statement

2. IF THEN ELSE Statement

3. IF THEN ELSIF Statement

4. Nested IF THEN ELSE Statement

IF THEN Statement

IF THEN Statement write in following syntax format:

IF ( condition ) THEN

statement

END IF;
IF THEN ELSE Statement

IF THEN ELSE Statement write in following syntax format:

IF ( condition ) THEN

statement;

ELSE

statement;

END IF;

IF THEN ELSIF Statement

IF THEN ELSIF Statement write in following syntax format:

IF ( condition-1 ) THEN

statement-1;

ELSIF ( condition-2 ) THEN


59
statement-2;

ELSIF ( condition-3 ) THEN

statement-3;

ELSE

statement;

END IF;

Nested IF THEN ELSE Statement

Logically IF THEN ELSIF Statement and Nested IF THEN ELSE Statement both are same. Nested IF
THEN ELSE Statement write in following syntax format:

IF ( condition-1 ) THEN

statement-1;

ELSE

IF ( condition-2 ) THEN

statement-2;

ELSE

IF ( condition-3 ) THEN

statements-3;

END IF;

END IF;

END IF;

CASE Statement

PL/SQL simple CASE statement evaluates selector and attempt to match one or more WHEN condition.

Syntax

CASE selector

WHEN value-1
60
THEN statement-1;

WHEN value-2

THEN statement-2;

ELSE

statement-3;

END CASE

AIM:
Develop a program that includes the features NESTED IF, CASE and CASE expression. The
program can be extended using the NULLIF and COALESCE functions.

Declare
vno number:=&anynumber;
vresult varchar2(20);
Begin
If vno<10 then
vno:=vno+1;
else
if vno>10 then
vno:=vno-1;
else
vno:=vno+10;
end if;
end if;
case
when vno>0 then
dbms_output.put_line(‘The given number became’||vno);
when vno<0 then
dbms_output.put_line(‘The given number became’||vno);
end case;
vresult:=case when mod(vno,2)=0
then
vno||’is an even number’
else
61
vno||’is an odd number’
end;
dbms_output.put_line(vresult);
end;

Result:

EXPERIMENT 7

Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR

62
Handling, BUILT –IN Exceptions, USER defined Exceptions, RAISE- APPLICATION ERROR.

Syntax for WHILE LOOP:

WHILE<condition> LOOP
<action>

ENDLOOP;

Program:

DECLARE

no NUMBER := 0;

BEGIN

WHILE no < 10 LOOP

no := no + 1;

END LOOP;

DBMS_OUTPUT.PUT_LINE('Sum :' || no);

END;

Result
Sum : 10

PL/SQL procedure successfully completed.

Syntax for For Loop :

FOR variable IN[REVERSE] start –end LOOP


<Action>
ENDLOOP;

Program:

BEGIN

63
FOR no IN 1 .. 5 LOOP

DBMS_OUTPUT.PUT_LINE('Iteration : ' || no);

END LOOP;

END;

Result
Iteration : 1
Iteration : 2
Iteration : 3
Iteration : 4
Iteration : 5

PL/SQL procedure successfully completed.

Syntax for Exception Handling


The General Syntax for exception handling is as follows. Here you can list down as many as exceptions
you want to handle. The default exception will be handled using WHEN others THEN:

DECLARE

<declarations section>

BEGIN

<executable command(s)>

EXCEPTION

<exception handling goes here >

WHEN exception1 THEN

exception1-handling-statements

WHEN exception2 THEN

exception2-handling-statements

WHEN exception3 THEN

64
exception3-handling-statements

........

WHEN others THEN

exception3-handling-statements

END;

Example:
Let us write some simple code to illustrate the concept. We will be using the CUSTOMERS table we had
created and used in the previous chapters:

DECLARE

c_id customers.id%type := 8;

c_name customers.name%type;

c_addr customers.address%type;

BEGIN

SELECT name, address INTO c_name, c_addr

FROM customers

WHERE id = c_id;

DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);

DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION

WHEN no_data_found THEN

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

WHEN others THEN

dbms_output.put_line('Error!');

END;

65
When the above code is executed at SQL prompt, it produces the following result:

No such customer!

PL/SQL procedure successfully completed.

The above program displays the name and address of a customer whose ID is given. Since there is no
customer with ID value 8 in our database, the program raises the run-time exception NO_DATA_FOUND,
which is captured inEXCEPTION block.

Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal database error,
but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is the
simple syntax of raising an exception:

DECLARE

exception_name EXCEPTION;

BEGIN

IF condition THEN

RAISE exception_name;

END IF;

EXCEPTION

WHEN exception_name THEN

statement;

END;

You can use above syntax in raising Oracle standard exception or any user-defined exception. Next section
will give you an example on raising user-defined exception, similar way you can raise Oracle standard
exceptions as well.

User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A user-defined
exception must be declared and then raised explicitly, using either a RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.
66
The syntax for declaring an exception is:

DECLARE

my-exception EXCEPTION;

Example:
The following example illustrates the concept. This program asks for a customer ID, when the user enters
an invalid ID, the exception invalid_id is raised.

DECLARE

c_id customers.id%type := &cc_id;

c_name customers.name%type;

c_addr customers.address%type;

-- user defined exception

ex_invalid_id EXCEPTION;

BEGIN

IF c_id <= 0 THEN

RAISE ex_invalid_id;

ELSE

SELECT name, address INTO c_name, c_addr

FROM customers

WHERE id = c_id;

DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);

DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

END IF;

EXCEPTION

WHEN ex_invalid_id THEN

dbms_output.put_line('ID must be greater than zero!');

WHEN no_data_found THEN

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

WHEN others THEN

dbms_output.put_line('Error!');

END;

When the above code is executed at SQL prompt, it produces the following result:

Enter value for cc_id: -6 (let's enter a value -6)

old 2: c_id customers.id%type := &cc_id;

new 2: c_id customers.id%type := -6;

ID must be greater than zero!

PL/SQL procedure successfully completed.

EXPERIMENT 8
Programs development using creation of procedures, passing parameters IN and OUT of PROCEDURES

68
PL/SQL Procedures

PL/SQL procedures create using CREATE PROCEDURE statement. The major difference between
PL/SQL function or procedure, function return always value where as procedure may or may not return
value.

When you create a function or procedure, you have to define IN/OUT/INOUT parameters parameters.

1. IN : IN parameter referring to the procedure or function and allow to overwritten the value of
parameter.

2. OUT : OUT parameter referring to the procedure or function and allow to overwritten the value of
parameter.

3. IN OUT : Both IN OUT parameter referring to the procedure or function to pass both IN OUT
parameter, modify/update by the function or procedure and also get returned.

IN/OUT/INOUT parameters you define in procedure argument list that get returned back to a result.
When you create the procedure default IN parameter is passed in argument list. It's means value is passed
but not returned. Explicitly you have define OUT/IN OUT parameter in argument list.

Syntax for procedures:

CREATE OF REPLACE PROCEDURE procedurename


( argument , IN, OUT, IN , OUT - datatype,….) , IS | AS -

[local declarations ];
BEGIN

PL/SQL subprogram body;


[EXCEPTION
Exception PL/SQL block; ]
END;

Program:

69
i) Program development using creation of procedures passing parameters IN of Procedure.

create or replace procedure EmpProcedure(vename in varchar,vempno in number) is vsal number;


Begin
select sal into vsal from emp where empno=vempno;
Dbms_output.put_line('Salary before updation is '||vsal);
update emp set sal=sal+sal*0.1 where empno=vempno;
select sal into vsal from emp where empno=vempno;
Dbms_output.put_line('Salary after updation is '||vsal);
End;

To execute a stored procedure:


SQL> exec EmpProcedure('RAJU',7782);

ii) Program development using creation of procedures passing parameters IN and OUT of Procedure:
create or replace procedure query_emp(p_id in emp.empno%type,p_name out emp.ename%type,p_sal out
emp.sal%type,p_deptno out emp.deptno%type) is
Begin
select ename,sal,deptno into p_name, p_salary , p_deptno from emp where empno=p_id;
End query_emp;
______________
Variable gn varchar2(15)
Variable gs number
Variable gc number

To execute a stored procedure:


SQL> exec query_emp(7900, :gn, :gs, :gc)
SQL> print gn gs gc

70
GN
--------
WARD
GS
----------
422.96
GC
----------
500

EXPERIMENT 9

71
Program development using creation of stored functions, invoke functions in SQL Statements and write
complex functions.

Aim:

Program development using creation of stored functions, invoke functions in SQL Statements and
write complex functions.

Syntax for functions :

CREATE OR REPLACE FUNCTION function_name


*(argument INdata type, …….)+ RETURN datatype
{ IS | AS}
[Local declarations/Calculation/etc.,]

BEGIN

PL/SQL sub program body;


[EXCEPTION

Exception handlers] END


[name];

BEGIN

----PL/SQL code to call function


[EXCEPTION
----calling program exception handler ]

END;

Program:

1. Program development using creation of stored functions, invoke functions in SQL


Statements and write complex functions.

72
create or replace function counttup (vdep in emp.deptno%type)
return number
is
emptot number;
Begin
select count(*) into emptot from emp where deptno=vdep;
return emptot;
End;

To view the output:


SQL> select counttup(30) from dual;

Program for function:


create or replace function get_sal
( p_id in emp.empno%type)
return number
is
vsal emp.sal%type ;
Begin
select sal
into vsal
from emp
where empno = p_id;
return vsal;
end get_sal;

To execute:
variable gsal number
execute :gsal :=get_sal(7900)

73
Function:
create or replace function get_sal
( p_id in emp.empno%type)
return number
is
vsal emp.sal%type ;
Begin
select sal into vsal from emp where empno = p_id;
return vsal;
end get_sal;

To execute:
variable gsal number
execute :gsal :=get_sal(7900)

EXPERIMENT 10
Aim:

74
Program development using creation of package specification, package bodies, private objects, package
variables and cursors and calling stored packages.
Syntax for package specifications:

CREATE OR REPLACE PACKAGE package_name AS

FUNCTION function_name (list of arguments ) RETURN data type;

PROCEDURE procedure_name ( list of arguments);

END package_name;

Syntax for package body :

CREATE OR REPLACE PACKAGE BODY package_name AS

FUNCTION function _name (list of arugments) RETURN data type {IS|AS}


[local declaration of function ]

BEGIN

------ code of function


[EXCEPTION

------exception handler of function ] END


function_name;

PROCEDURE procedure_name (list of arguments) { IS | AS} [Local


declarations/Calculation/etc.,]
BEGIN

-----code of procedure
[EXCEPTION

Exception handlers] END


procedure_name;
75
* ……… similarly other functions and procedures+

END package_name;

q) create a general package to convert the given distances.

SQL> CREATE OR REPLACE PACKAGE distance_consts IS


mile_2_kilo CONSTANT NUMBER := 1.6093;
kilo_2_mile CONSTANT NUMBER := 0.6214;
yard_2_meter CONSTANT NUMBER := 0.9144;
meter_2_yard CONSTANT NUMBER := 1.0936;
PROCEDURE meter_to_yard
(p_meter IN NUMBER, p_yard OUT NUMBER);
PROCEDURE yard_to_meter
(p_yard IN NUMBER, p_meter OUT NUMBER);
PROCEDURE kilo_to_mile
(p_kilo IN NUMBER, p_mile OUT NUMBER);
PROCEDURE mile_to_kilo
(p_mile IN NUMBER, p_kilo OUT NUMBER);

END distance_consts;

SQL> CREATE OR REPLACE PACKAGE BODY distance_consts IS

PROCEDURE meter_to_yard
(p_meter IN NUMBER, p_yard OUT NUMBER)
IS
BEGIN
p_yard := p_meter * distance_consts.meter_2_yard;
END meter_to_yard;

PROCEDURE yard_to_meter
(p_yard IN NUMBER, p_meter OUT NUMBER)
IS
BEGIN
p_meter:= p_yard * distance_consts.yard_2_meter;
76
END yard_to_meter;

PROCEDURE kilo_to_mile
(p_kilo IN NUMBER, p_mile OUT NUMBER)
IS
BEGIN
p_mile := p_kilo * distance_consts.kilo_2_mile;
END kilo_to_mile;

PROCEDURE mile_to_kilo
(p_mile IN NUMBER, p_kilo OUT NUMBER)
IS
BEGIN
p_kilo := p_mile * distance_consts.mile_2_kilo;
END mile_to_kilo;

end distance_consts;

sql> set serveroutput on


declare
yard NUMBER;
begin
distance_consts.meter_to_yard (1, yard);
dbms_output.put_line('meter - to yard is' || to_char(yard));
end;

sql> variable meter number


execute distance_consts.yard_to_meter(1,:meter)
print meter

sql> variable mile number


execute distance_consts.kilo_to_mile(1,:mile)
print mile

77
sql> variable kilo number
execute distance_consts.kilo_to_mile(2,:kilo)
print kilo
Q) Create a package specification and body called job_pack. The package contains add_job, upd_job, and
del_job procedures, as well as q_job.

SQL> CREATE OR REPLACE PACKAGE job_pack IS


PROCEDURE add_job
(p_jobid IN jobs.job_id%TYPE,p_jobtitle IN jobs.job_title%TYPE);
PROCEDURE upd_job
(p_jobid IN jobs.job_id%TYPE,p_jobtitle IN jobs.job_title%TYPE);
PROCEDURE del_job
(p_jobid IN jobs.job_id%TYPE);
FUNCTION q_job
(p_jobid IN jobs.job_id%TYPE)
RETURN VARCHAR2;
END job_pack;

Sql> CREATE OR REPLACE PACKAGE BODY job_pack IS


PROCEDURE add_job
(p_jobid IN jobs.job_id%TYPE,p_jobtitle IN jobs.job_title%TYPE)
IS
BEGIN
INSERT INTO jobs (job_id, job_title)
VALUES (p_jobid, p_jobtitle);
END add_job;
PROCEDURE upd_job
(p_jobid IN jobs.job_id%TYPE,p_jobtitle IN jobs.job_title%TYPE)
IS
BEGIN
UPDATE jobs
SET job_title = p_jobtitle
WHERE job_id = p_jobid;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20202,'No job updated.');
END IF;
78
END upd_job;

PROCEDURE del_job
(p_jobid IN jobs.job_id%TYPE)
IS
BEGIN
DELETE FROM jobs
WHERE job_id = p_jobid;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR (-20203,'No job deleted.');
END IF;
END del_job;

FUNCTION q_job
(p_jobid IN jobs.job_id%TYPE)
RETURN VARCHAR2
IS
v_jobtitle jobs.job_title%TYPE;
BEGIN
SELECT job_title
INTO v_jobtitle
FROM jobs
WHERE job_id = p_jobid;
RETURN (v_jobtitle);
END q_job;
END job_pack;

Q)Invoke ADD_JOB ny passing values IT_SYSN and SYSTEMS ANALYST as parameters

Sql> EXECUTE job_pack.add_job('IT_SYSAN','Systems Analyst')

Q) Query the jobs table to see the results


Sql) SELECT *
FROM jobs
WHERE job_id = 'IT_SYSAN'

79
Q) Create and invoke a package that contains private and public constructs with package specification and
package body called EMP_PACK that contains your VALID_DEPTID function as a private construct

SQL> CREATE OR REPLACE PACKAGE emp_pack IS


PROCEDURE new_emp
(p_lname employees.last_name%TYPE,
p_fname employees.first_name%TYPE,
p_email employees.email%TYPE,
p_job employees.job_id%TYPE DEFAULT 'SA_REP',
p_mgr employees.manager_id%TYPE DEFAULT 145,
p_sal employees.salary%TYPE DEFAULT 1000,
p_comm employees.commission_pct%TYPE DEFAULT 0,
p_deptid employees.department_id%TYPE DEFAULT 80);
END emp_pack;

SQL> CREATE OR REPLACE PACKAGE BODY emp_pack IS


FUNCTION valid_deptid
(p_deptid IN departments.department_id%TYPE)
RETURN BOOLEAN
IS
v_dummy VARCHAR2(1);
BEGIN
SELECT 'x'
INTO v_dummy
FROM departments
WHERE department_id = p_deptid;
RETURN (TRUE);
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN(FALSE);
END valid_deptid;
PROCEDURE new_emp
(p_lname employees.last_name%TYPE,
p_fname employees.first_name%TYPE,
p_email employees.email%TYPE,
p_job employees.job_id%TYPE DEFAULT 'SA_REP',
80
p_mgr employees.manager_id%TYPE DEFAULT 145,
p_sal employees.salary%TYPE DEFAULT 1000,
p_comm employees.commission_pct%TYPE DEFAULT 0,
p_deptid employees.department_id%TYPE DEFAULT 80)
IS
BEGIN
IF valid_deptid(p_deptid) THEN
INSERT INTO employees (employee_id, last_name, first_name,
email, job_id, manager_id, hire_date, salary, commission_pct,
department_id)
VALUES (employees_seq.NEXTVAL, p_lname, p_fname, p_email,
p_job, p_mgr, TRUNC (SYSDATE, 'DD'), p_sal, p_comm,
p_deptid);
ELSE
RAISE_APPLICATION_ERROR (-20205,
'Invalid department number. Try again.');
END IF;
END new_emp;
END emp_pack;
Q) Invoke the new_emp procedure , using 15 as department number.

SQL> EXECUTE emp_pack.new_emp(p_lname=>'Harris',p_fname=>'Jane', p_email=>'JAHARRIS',


p_deptid => 15)

Q> Invoke the new_emp procedure , using 80 as department number.


SQL> EXECUTE emp_pack.new_emp(p_lname =>'Smith', p_fname=>'David', p_email=>'DASMITH',
p_deptid=>80)

Q) Create a package called CHK_PACK that contains the procedure CHK_HIREDATE and
CHK_DEPT_MGR. Make both constructs public .The procedure CHK_HIREDATE checks wether an
employee hire date is within the given range. The procedure CHK_DEPT_MGR procedure check whether
manager and employee work in the same department.

81
SQL> CREATE OR REPLACE PACKAGE chk_pack IS
PROCEDURE chk_hiredate
(p_date in employees.hire_date%type);
PROCEDURE chk_dept_mgr
(p_empid in employees.employee_id%type,
p_mgr in employees.manager_id%type);
END chk_pack;
/

SQL> CREATE OR REPLACE PACKAGE BODY chk_pack IS


PROCEDURE chk_hiredate(p_date in employees.hire_date%type)
IS
v_low date := add_months (sysdate, - (50 * 12));
v_high date := add_months (sysdate,3);
BEGIN
IF TRUNC(p_date) NOT BETWEEN v_low and v_high
OR p_date IS NULL THEN
RAISE_APPLICATION_ERROR(-20200,'Not a valid hiredate');
END IF;
END chk_hiredate;
PROCEDURE chk_dept_mgr(p_empid in employees.employee_id%type,
p_mgr in employees.manager_id%type)
IS
v_empnr employees.employee_id%type;
v_deptid employees.department_id%type;
BEGIN
BEGIN
SELECT department_id
INTO v_deptid
FROM employees
WHERE employee_id = p_empid;
EXCEPTION
WHEN no_data_found
THEN RAISE_APPLICATION_ERROR(-20000, 'Not a valid emp id');
END;
BEGIN
82
SELECT employee_id /*check valid combination
deptno/mgr for given employee */
INTO v_empnr
FROM employees
WHERE department_id = v_deptid
AND employee_id = p_mgr
AND job_id like '%MAN';
EXCEPTION
WHEN no_data_found
THEN RAISE_APPLICATION_ERROR (-20000,
'Not a valid manager for this department');
END;
END chk_dept_mgr;
END chk_pack;
/

Q> Test the CHK_HIREDATE.

SQL> EXECUTE chk_pack.chk_hiredate('01-JAN-47')

SQL> EXECUTE chk_pack.chk_hiredate(NULL)

Sql> EXECUTE chk_pack.chk_dept_mgr(117,100)

EXPERIMENT 11
Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR, WHERE
CURRENT of clause and CURSOR variables

83
Aim:
Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR, WHERE
CURRENT of clause and CURSOR variables.

Syntax for declaration of a cursor :

CURSOR <cursor-name> [parameter_list]


[RETURN return_type]
IS query
[FOR UPDATE [OF (column_list)][NOWAIT]];

Syntax for opening a cursor :

OPEN <cursor-name>;

Syntax to Fetch the records from the cursor:

Fetch cursorname into variable1,variable2,…..

Syntax for parameterized declaration of a cursor :

CURSOR cursor_name ( variable_name datatype) IS


<SELECT statement…>

Program:

1. Create a Cursor to find employee with given job and deptno. Develop programs using features
parameters in a CURSOR, FOR UPDATE CURSOR, WHERE CURRENT of clause and CURSOR
variables.

DECLARE
cursor sal_cursor is
select e.ename ,e.salary,e.deptno from employee e where e.deptno in (10,20,30) for update of salary
nowait;
Begin
savepoint a;
84
for emp_record in sal_cursor
loop
if emp_record.deptno=10 then
update employee
set salary=emp_record.salary+emp_record.salary*0.1 where current of sal_cursor;
end if;
if emp_record.deptno=20 then
update employee
set salary=emp_record.salary+emp_record.salary*0.2
where current of sal_cursor;
end if;
if emp_record.deptno=30 then
update employee
set salary=emp_record.salary+emp_record.salary*0.3 where current of sal_cursor;
end if;
end loop;
End;

PL/SQL procedure successfully completed.

EXPERIMENT 12

Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and INSTEAD OF
Triggers

85
Aim:
Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and INSTEAD OF
Triggers.

Syntax for Trigger:

CREATE [OR REPLACE] TRIGGER trigger_name


{BEFORE | AFTER }

,|DELETE |*OR+ INSERT |*OR+ UPDATE | *OF column_name,……..+

ON table_name

[REFERENCING { OLD AS old, NEW AS new }]


[FOR EACH ROW [WHEN condition ] DECLARE

Variable declaration; Constant


declaration; BEGIN

PL/SQL subprogram body;


[EXCEPTION

Exception PL/SQL block; ] END;

Program:

Trigger:
SQL> create or replace trigger tg2 after insert on emp for each row when ( new.sal > 10000)
Begin
dbms_output.put_line(' salary out of range ');
End;

To view the Output


SQL> INSERT INTO EMP VALUES(1234,'SREE','HRD',144,'23-DEC-02',10200,100,10);

86
SQL> create or replace trigger tg2 after insert on emp for each row when ( new.sal > 10000)
Begin
dbms_output.put_line(' salary out of range ');
End;

To view the Output


SQL> INSERT INTO EMP VALUES(1234,'SREE','HRD',144,'23-DEC-02',10200,100,10);

SQL> create or replace trigger k1 after insert on emp for each row when ( new.hiredate > sysdate)
Begin
dbms_output.put_line( ' Wrong date ');
End;

To view the Output


SQL> INSERT INTO EMP VALUES(1234,'SREE','HRD',144,'29-mar-04',1000,null,10);

Trigger
SQL> create or replace trigger tg2 after insert on emp for each row when(new.salary>10000)
Begin
dbms_output.put_line(' salary out of range ');
End;

To view the Output


SQL> INSERT INTO EMP VALUES(1234,'SREE',671,1,'23-DEC-02',10200,100,10);

ADDITIONAL EXPERIMENTS

OPERATORS IN SQL

87
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to
perform operation(s), such as comparisons and arithmetic operations.

Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple
conditions in a statement.

 Arithmetic operators

 Comparison operators

 Logical operators

Arithmetic Operators

Arithmetic operators can perform arithmetical operations on numeric operands involved. Arithmetic
operators are addition(+), subtraction(-), multiplication(*) and division(/). The + and - operators can also be
used in date arithmetic.

Operator Meaning
+ (Add) Addition
- (Subtract) Subtraction
* (Multiply) Multiplication
/ (Divide) Division
Returns the integer remainder of a division. For example, 17 % 5 = 2 because the remainder of
% (Modulo)
17 divided by 5 is 3.

Syntax :

SELECT <Expression>[arithmetic operator]<expression>...


FROM [table_name]
WHERE [expression];

1. plus (+) operator

The SQL plus (+) operator is used to add two or more expressions or numbers.

Example:

SQL> select 10+ 20;

+--------+

88
| 10+ 20 |

+--------+

| 30 |

Example :

SELECT SALARY + BONUS FROM EMPLOYEE_PAY_TBL;

The SALARY column is added with the BONUS column for a total for each row of data

minus (-) operator

The SQL minus (-) operator is used to subtract one expression or number from another expression or
number.

Example:

SQL> select 10 - 20;

+--------+

| 10 - 20 |

+--------+

| -10 |

Example:

SELECT SALARY - BONUS FROM EMPLOYEE_PAY_TBL;

The BONUS column is subtracted with the SALARY column.

multiply ( * ) operator

The SQL multiply ( * ) operator is used to multiply two or more expressions or numbers.

Example:

SQL> select 10 * 20;

+---------+
89
| 10 * 20 |

+---------+

| 200 |

Example:

SELECT SALARY * BONUS FROM EMPLOYEE_PAY_TBL;

The BONUS column is multiplied with the SALARY column.

Divide ( / ) operator

The SQL divide ( / ) operator is used to divide one expressions or numbers by another.

Example:

SQL> select 10 / 5;

+--------+

| 10 / 5 |

+--------+

| 2.0000 |

Example:

SELECT SALARY / BONUS FROM EMPLOYEE_PAY_TBL;

The salary column is divided by bonus column.

modulo ( % ) operator

The SQL MODULO operator returns the remainder (an integer) of the division.

Example:

SQL> select 12 % 5;

+---------+

| 12 % 5 |
90
+---------+

| 2|

+---------+

Logical Operators

There are three Logical Operators namely, AND, OR, and NOT. These operators compare two conditions at
a time to determine whether a row can be selected for the output. When retrieving data using a SELECT
statement, you can use logical operators in the WHERE clause, which allows you to combine more than one
condition.

Logical
Description
Operators
For the row to be selected at least one of
OR
the conditions must be true.
For a row to be selected all the specified
AND
conditions must be true.
For a row to be selected the specified
NOT
condition must be false.

AND operator

AND operator is used to set multiple conditions with Where clause.

Example of AND

Consider the following Emp table

eid name age salary


401 Anu 22 5000
402 Shane 29 8000
403 Rohan 34 12000
404 Scott 44 10000
405 Tiger 35 9000

SELECT * from Emp WHERE salary < 10000 AND age > 25

The above query will return records where salary is less than 10000 and age greater than 25.

Result:

91
eid name age salary
402 Shane 29 8000
405 Tiger 35 9000

OR operator

OR operator is also used to combine multiple conditions with Where clause. The only difference between
AND and OR is their behaviour. When we use AND to combine two or more than two conditions, records
satisfying all the condition will be in the result. But in case of OR, atleast one condition from the conditions
specified must be satisfied by any record to be in the result.

Example of OR

Consider the following Emp table

eid Name age salary

401 Anu 22 5000

402 Shane 29 8000

403 Rohan 34 12000

404 Scott 44 10000

405 Tiger 35 9000

SELECT * from Emp WHERE salary > 10000 OR age > 25

The above query will return records where either salary is greater than 10000 or age greater than 25.

Example:

402 Shane 29 8000


403 Rohan 34 12000
404 Scott 44 10000
405 Tiger 35 9000

"NOT" Logical Operator:

If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT. NOT results
in the reverse of a condition. That is, if a condition is satisfied, then the row is not returned.

92
For example: If you want to find out the names of the employees who do not having age 44, the query
would be like:

SELECT * from Emp WHERE not age = 44;


Result:

eid Name age salary

401 Anu 22 5000

402 Shane 29 8000

403 Rohan 34 12000

405 Tiger 35 9000

Comparison Operators

Comparison operators are used in the WHERE clause to determine which records to select.

Comparison Operator Description


= Equal
<> Not Equal
!= Not Equal
> Greater Than
>= Greater Than or Equal
< Less Than
<= Less Than or Equal
IN ( ) Matches a value in a list
BETWEEN Within a range (inclusive)
LIKE Pattern matching with % and _
Greater than ( > ) operator

The greater than operator is used to test whether an expression (or number) is greater than another one.

Example:

SQL> SELECT * FROM CUSTOMERS WHERE SALARY > 5000;


Less than ( < ) operator

The less than operator is used to test whether an expression (or number) is less than another one.

Example:

93
SQL> SELECT * FROM CUSTOMERS WHERE SALARY < 2000;
Equal to ( = ) operator

The equal to operator is used for equality test within two numbers or expressions.

Example:

SQL> SELECT * FROM CUSTOMERS WHERE SALARY = 2000;


Not equal to ( <> ) operator

The not equal to operator is used for inequality test between two numbers or expression.

Example:

SQL> SELECT * FROM CUSTOMERS WHERE SALARY <> 2000;


Greater than or equal to ( >= ) operator

The greater than equal to operator is used to test whether an expression (or number) is either greater than or
equal to another one.

Example:

SQL> SELECT * FROM CUSTOMERS WHERE SALARY >= 6500;


Less than or equal to ( <= ) operator

The less than equal to operator is used to test whether an expression (or number) is either less than or equal
to another one.

Example:

SQL> SELECT * FROM CUSTOMERS WHERE SALARY <= 6500;

LIKE CLAUSE
Like clause is used as condition in SQL query. Like clause compares data with an expression using wildcard
operators. It is used to find similar data from the table.

Wildcard operators

There are two wildcard operators that are used in like clause.

94
 Percent sign % : represents zero, one or more than one character.

 Underscore sign _ : represents only one character.

Example of LIKE clause

Consider the following Student table.

s_id s_Name age

101 Adam 15

102 Alex 18

103 Abhi 17

SELECT * from Student where s_name like 'A%';

The above query will return all records where s_name starts with character 'A'.

Result:

s_id s_Name age

101 Adam 15

102 Alex 18

103 Abhi 17

Example

SELECT * from Student where s_name like '_d%';

The above query will return all records from Student table where s_name contain 'd' as second character.

Result:
95
s_id s_Name age

101 Adam 15

Example

SELECT * from Student where s_name like '%x';

The above query will return all records from Student table where s_name contain 'x' as last character.

Result:

s_id s_Name age

102 Alex 18

The IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

SQL IN Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);

Example of The IN Operator

Consider the following Student table.

s_id s_Name age

101 Adam 15

102 Alex 18

103 Abhi 17

96
Example

SELECT * FROM student WHERE s_Name IN ('adam','alex');


Result:

s_id s_Name age

101 Adam 15

102 Alex 18

BETWEEN Operator

The BETWEEN operator is used to select values within a range. The BETWEEN operator selects values
within a range. The values can be numbers, text, or dates.

SQL BETWEEN Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

BETWEEN Operator Example

Consider the following Student table.

s_id s_Name age

101 Adam 15

102 Alex 18

103 Abhi 17

Example

SELECT * FROM student WHERE age BETWEEN 10 AND 16;

Result:

97
s_id s_Name age

101 Adam 15

NOT BETWEEN Operator Example

To display the products outside the range of the previous example, use NOT BETWEEN:

Example

SELECT * FROM student WHERE age not BETWEEN 10 AND 16;


Result:

s_id s_Name age

102 Alex 18

103 Abhi 17

IMPLEMENTATION OF DIFFERENT TYPES OF JOINS


 Allows us to combine information from two tables
 Join is used to fetch data from two or more tables, which is joined to appear as single set of data
 Join is used for combining column from two or more tables by using common attribute.
 Join Keyword is used in SQL queries for joining two or more tables.

Types of Join

98
The following are the types of JOIN that we can use in SQL.

 Cross Join

 Natural Join

 Inner Join

 Outer Join

 The class table,

ID NAME
1 abhi
2 adam
4 alex

 The class_info table,

ID Address
1 DELHI
2 MUMBAI
3 CHENNAI

Cross JOIN or Cartesian Product

This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a table which
consists of records which combines each row from the first table with each row of the second table.

Cross JOIN Syntax is,

SELECT column-name-list
from table-name1
CROSS JOIN
table-name2;

Cross JOIN query will be,

SQL> SELECT * from class, cross JOIN class_info;

99
Result:

ID NAME ID Address
1 Abhi 1 DELHI
2 adam 1 DELHI
4 Alex 1 DELHI
1 Abhi 2 MUMBAI
2 adam 2 MUMBAI
4 Alex 2 MUMBAI
1 Abhi 3 CHENNAI
2 adam 3 CHENNAI
4 Alex 3 CHENNAI

INNER Join or EQUI Join

This is a simple JOIN in which the result is based on matched data as per the equality condition specified in
the query.

Inner Join Syntax is,

SELECT column-name-list
from table-name1
INNER JOIN
table-name2
WHERE table-name1.column-name = table-name2.column-name;

Example of Inner JOIN

Inner JOIN query will be,

SQL> SELECT * from class, class_info where class.id = class_info.id;

Result:

ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI

100
Natural JOIN

Natural Join is a type of Inner join which is based on column having same name and same datatype present
in both the tables to be joined.

Natural Join Syntax is,

SELECT *
from table-name1
NATURAL JOIN
table-name2;

Example of Natural JOIN

Natural join query will be,

SQL> SELECT * from class NATURAL JOIN class_info;

Result:

ID NAME Address
1 Abhi DELHI
2 Adam MUMBAI

In the above example, both the tables being joined have ID column(same name and same datatype), hence
the records for which value of ID matches in both the tables will be the result of Natural Join of these two
tables.

Outer JOIN

Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,

 Left Outer Join

 Right Outer Join

 Full Outer Join


101
Left Outer Join

The left outer join returns a result table with the matched data of two tables then remaining rows of the left
table and null for the right table's column.

Left Outer Join syntax is,

SELECT column-name-list
from table-name1
LEFT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;

Example of Left Outer Join

Left Outer Join query will be,

SQL> SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id=class_info.id);

Result:

ID NAME ID Address
1 Abhi 1 DELHI
2 Adam 2 MUMBAI
4 Alex null null

Right Outer Join

The right outer join returns a result table with the matched data of two tables then remaining rows of the
right table and null for the left table's columns.

Right Outer Join Syntax is,

select column-name-list
from table-name1
RIGHT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
102
Example of Right Outer Join

Right Outer Join query will be,

SQL> SELECT * FROM class RIGHT OUTER JOIN class_info on (class.id=class_info.id);

Result:

ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
null null 3 CHENNAI

Full Outer Join

The full outer join returns a result table with the matched data of two table then remaining rows of both left
table and then the right table.

Full Outer Join Syntax is,

select column-name-list
from table-name1
FULL OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;

Example of Full outer join is,

Full Outer Join query will be like,

SQL> SELECT * FROM class FULL OUTER JOIN class_info on (class.id=class_info.id);

Result:

ID NAME ID Address
1 abhi 1 DELHI
2 adam 2 MUMBAI
null null 3 CHENNAI
4 alex null null
103
104

S-ar putea să vă placă și