You are on page 1of 87

INTRODUCTION OF SQL

SQL(Structured Query Language) is a database computer language designed for the


retrieval and management of data in relational database management systems(RDBMS),
database schema creation and modification, and database object access control management.SQL
is a standard supported by all the popular relational database management systems in the market
place. The basic data structure in RDBMS is a table. SQL provides you the features to define
tables, define constraints on tables, query for data in table, and change the data in table by
adding, modifying, and removing data.
SQL also supports grouping of data in multiple rows, combining tables and other
features. All these put together, SQL is a high_level query language standard to access and alter
data in RDBMS.

History of SQL:
The first version of SQL was developed at IBM by Donald D.Chamberlin and
Raymond F.Boyce in the early 1970s.This version, initially called SEQUEL ,was designed to
manipulate and retrieve data stored in IBM’s original relational database product, system R.IBM
patented their version of SQL in 1985,while the SQL language was not formally standardized
until 1986,by the American National Standards Institute(ANSI) as SQL-86.Subsequent versions
of the SQL standards have been released by ANSI and as International Organization for
standardization (ISO)standards.

Originally designed as a declarative query and data manipulation language, variations of


SQL have been created by SQL database management system (DBMS) vendors that add
procedural constructs, control_of_flow statements, user-defined data types, and various other
language extensions. With the release of the SQL:1999 standard, many such extensions were
formally adopted as part of the SQL language via the SQL Persistent Stored Modules
(SQL/PSM) portion of the standard.

Various Data Types:

1. Character Data types:


Char – Fixed length character string that can varies between 1 – 2000 bytes

1
Varchar / Varchar2 - variable length character string, size ranges from 1 – 4000
bytes. It saves the disk space (only length of the entered value will be assigned as
the size of column)
Long – variable length character string, maximum size is 2 GB
2. Number Data types: Can store +ve, -ve, zero, fixed point, floating point with 38
precision.
Number – {p=38,s=0}
Number(p) – fixed point
Number(p,s) – floating point (p=1 to 38, s =-84 to 127)

3. Date Data type: used to store date and time in the table.
DB uses its own format of storing in fixed length of 7 bytes for century, date,
month, year, hour , minutes, seconds.
Default data type is “dd-mon-yy”
4. Raw Data type: used to store byte oriented data like binary data and byte string.
5. Other:
CLOB – stores character object with single byte character
BLOB – stores large binary objects such as graphics, video, sounds
BFILE – stores file pointers to the LOB’s

EX.NO : 1
DATA DEFINITION LANGUAGES (DDL)
DATE :

AIM

To create and modify a table using Data Definition Language (DDL) commands.

DDL COMMANDS
CREATE - used for creating tables.
ALTER - used for removing an existing table.
RENAME - used to change the name of the table

2
DESC - used to view the table structure.

DESCRIPTION:

1. CREATE COMMAND:
The CREATE command is used for creating tables to store data.
Rules:
1. Oracle reserved words cannot be used.
2. Underscore, numerals, letters are allowed but not blank space.
3. Maximum length for the table name is 30 characters.
4. Two different tables should not have same name.
5. We should specify a unique column name.
6. We should specify proper data type along with width.
7. We can include ‘not null’ conditions when needed. By default it is ’null’.

i) Create a new table:


SYNTAX:
create table <tablename> (attribute_name1 datatype(size), attribute_name2
datatype(size), attribute_name3 datatype(size),…. attribute_name n datatype(size));

EXAMPLE :

create table customer (cust_name varchar2(15), social_security_no number(11),


cust_street varchar2(7), cust_city varchar2(10));

ii) Create a table from an existing table with all fields


SYNTAX:
create table <traget table name> as select * from <source table name>;

EXAMPLE:
create table emp1 as select * from emp;

iii) Create a from an existing table with selected fields


SYNTAX:
create table <traget table name> as select column name1,….
from <source table name>;

EXAMPLE:
create table emp2 as select empno, ename from emp;

iv) Create a new table from an existing table without any record:
SYNTAX:
create table <traget table name> as select * from <source table name>
where <false condition>;
EXAMPLE:

3
create table emp3 as select * from emp where 1>2;

2. ALTER COMMAND:
The ALTER command is used to modify the definition (structure) of a table by modifying
the definition of its columns.

SYNTAX:
alter table <table name> add (new columnname data type (size));
alter table <table name> modify (columnname data type (new size));
alter table <table name> modify (columnname data type (new size));
alter table<table name> drop (column name);

EXAMPLE:
alter table student add(address varchar2(15),marks number(4));
alter table customer modify (cust_street varchar2(10));
alter table customer drop(acc_no);

3. DROP COMMAND:
This command is used for removing an existing table..

SYNTAX:
drop table <table_name>;

EXAMPLE:
drop table student;

4. TRUNCATE COMMAND:
If there is no further use of records stored in a table and the structure has to be
retained then the records alone can be deleted.

SYNTAX:
truncate table <table_name>;
EXAMPLE:
truncate table student;

5. RENAME COMMAND:
The RENAME command is used to change the name of the table .

SYNTAX:
rename <Old table name> to <New table name>;

EXAMPLE:
rename student to vcet_student;

EXAMPLE QUERIES:

SQL> create table loan(loan_number varchar2(10),branch_name varchar2(10),


4
amount number(10));
Table created.

SQL> desc loan;


Name Null? Type
------------------------ ---------------- -----------------------------------
LOAN_NUMBER NOT NULL VARCHAR2(10)
BRANCH_NAME VARCHAR2(10)
AMOUNT NUMBER(10)

SQL> alter table loan add city varchar2(10);


Table altered.

SQL> desc loan;


Name Null? Type
-------------------------- -------- ----------------------------
LOAN_NUMBER NOT NULL VARCHAR2(10)
BRANCH_NAME VARCHAR2(10)
AMOUNT NUMBER(10)
CITY VARCHAR2(10)

SQL> alter table loan modify(city varchar2(30));


Table altered.

SQL> desc loan;


Name Null? Type
------------------------- -------- ----------------------
LOAN_NUMBER NOT NULL VARCHAR2(10)
BRANCH_NAME VARCHAR2(10)
AMOUNT NUMBER(10)
CITY VARCHAR2(30)

SQL> alter table loan drop column city;


Table altered.

SQL> desc loan;

Name Null? Type


----------------------------------------- -------- ----------------------------
LOAN_NUMBER NOT NULL VARCHAR2(10)
BRANCH_NAME VARCHAR2(10)
AMOUNT NUMBER(10)

SQL> rename loan to loan1;


Table renamed.

5
SQL> desc loan1;
Name Null? Type
----------------------------------------- -------- ----------------------------
LOAN_NUMBER NOT NULL VARCHAR2(10)
BRANCH_NAME VARCHAR2(10)
AMOUNT NUMBER(10)

SQL> drop table loant;


Table dropped.

SQL> create table loant(loan_number varchar2(10),branch_name varchar2(10),amount


number(10));
Table created.

SQL> truncate table loant;


Table truncated

RESULT:

Thus the DDL commands are verified successfully.

EX.NO : 02
DATA MANIPULATION LANGUAGES (DML)
DATE :

AIM:
To manipulate the tables using DML commands.

DML COMMANDS:
1. Insert
2. Select
3. Update
4. Delete

6
DESCRIPTION:

1. INSERT COMMAND

This is used to add one or more rows to a table. The values are separated by commas and
the data types char and date are enclosed in apostrophes. The values must be entered in the same
order as they are defined.

i) Inserting a single row into a table:

SYNTAX:
insert into <table name> values (value list)

EXAMPLE:

insert into s values(‘s3’,’sup3’,’blore’,10)

ii) Inserting more than one record using a single insert commands:

SYNTAX:
insert into <table name> values (&col1, &col2, ….)

EXAMPLE:
insert into stud values(&reg, ‘&name’, &percentage);

iii) Skipping the fields while inserting:

insert into <tablename(coln names to which datas to be inserted)> values


(list of values);

2. SELECT COMMAND
It is used to retrieve information from the table. It is generally referred to as querying the
table. We can either display all columns in a table or only specify column from the table.
i) The retrieval of all rows from a table:

SYNTAX:
Select * from tablename; .

EXAMPLE:
Select * from IT;

ii) The retrieval of specific columns from a table:


It retrieves the specified columns from the table.

SYNTAX:

7
Select column_name1, …..,column_namen from table name;

EXAMPLE:
Select empno, empname from emp;

iii) Elimination of duplicates from the select clause:


It prevents retriving the duplicated values .Distinct keyword is to be used.

SYNTAX:
Select DISTINCT col1, col2 from table name;

EXAMPLE:
Select DISTINCT job from emp;

iv) Select command with where clause:


To select specific rows from a table we include ‘where’ clause in the select
command. It can appear only after the ‘from’ clause.

SYNTAX:
Select column_name1, …..,column_namen from table name where condition;

In the syntax:
WHERE  restricts the query to rows that meet a condition
Condition is composed of column names, expressions,constants, & comparison
operator
The WHERE clause can compare values in columns, literal values, arithmetic
expressions, or functions.

It consists of three elements:


• Column name
• Comparison condition
• Column name, constant, or list of values
Other Comparison Conditions
Operator Meaning
BETWEEN Between two values (inclusive),
IN Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value

EXAMPLE:
Select empno, empname from emp where sal>4000;

v) Select command with order by clause:


SYNTAX:
Select column_name1, …..,column_namen from table name where condition
order by colmnname [ASC/DESC];
8
Where ASC  Ascending order (It is optional)
DESC  descending order

EXAMPLE:
Select empno, empname from emp order by empno;

vi) Select command to create a table:


SYNTAX:
create table tablename as select * from existing_tablename;

EXAMPLE:
create table emp1 as select * from emp;

vii) Select command to insert records:


SYNTAX:
insert into tablename ( select columns from existing_tablename);

EXAMPLE:
insert into emp1 ( select * from emp);

3. UPDATE COMMAND
It is used to alter the column values in a table. A single column may be updated or
more than one column could be updated.

SYNTAX:
update tablename set field=values where condition;

EXAMPLE:
Update emp set sal = 10000 where empno=135;

4. DELETE COMMAND
After inserting row in a table we can also delete them if required. The delete
command consists of a from clause followed by an optional where clause.

SYNTAX:
Delete from table where conditions;

EXAMPLE:
delete from emp where empno=135;

EXAMPLE QUERIES:
SELECT ALL ATTRIBUTES FROM A RELATION:
SQL> select * from account;
ACCOUNT_NU BRANCH_NAME BALANCE

9
---------- --------------- ----------
A-101 Downtown 500
A-102 Perryridge 400
A-201 Brighton 900
A-215 Mianus 700
A-222 Redwood 700
A-305 Round Hill 350
A-217 Brighton 750
7 rows selected.
SQL> select * from branch;
BRANCH_NAME BRACH_CITY ASSEST
--------------- ------------------------------ ----------
Brighton Brooklyn 7100000
Downtown Brooklyn 9000000
Mianus Horseneck 400000
North Town Rye 3700000
Perryridge Horseneck 1700000
Pownal Bennington 300000
Redwood Palo Alto 2100000
Round Hill Horseneck 8000000
8 rows selected.
SQL> select * from depositor;
CUSTOMER_NAME ACCOUNT_NU
Hayes A-102
Johnson A-101
Johnson A-201
Jones A-217
Lindsay A-222
Smith A-215
Turner A-305
7 rows selected.

SQL> select * from loan;


LOAN_N BRANCH_NAME AMOUNT
------ --------------- ----------
L-11 Round Hill 900
L-14 Downtown 1500
L-15 Perryridge 1500
L-16 Perryridge 1300
L-17 Downtown 1000
L-23 Redwood 2000
L-93 Mianus 500
7 rows selected.
SQL> select * from borrower;
CUSTOMER_NAME LOAN_N
-------------------- ------

10
Adams L-16
Curry L-93
Hayes L-15
Johnson L-14
Jones L-17
Smith L-11
Smith L-23
Williams L-17
8 rows selected.
SELECTING A PARTICULAR ATTRIBUTE FROM THE TABLE:
SQL> SELECT ACC_NO FROM ACCOUNT;
ACC_NO
--------------------
A-101
A-215
A-102
A-305
A-201
A-222
A-217
7 rows selected.
SQL> SELECT BALANCE*0.5 FROM ACCOUNT;
BALANCE*0.5
-----------
250
600
198
173.25
600
600
600
7 rows selected.

SELECTING ATTRIBUTES USING WHERE CONDITIONS:


SQL> SELECT * FROM ACCOUNT WHERE BALANCE>1000;
ACCOUNT BALANCE BRANCHNAME
---------------- --------- --------------------
A-215 1200 Mianus
A-201 1200 brighton
A-222 1200 redwood
A-217 1200 brighton

1. SQL> SELECT * FROM ACCOUNT WHERE BALANCE = 1000;


no rows selected
2. SQL> SELECT * FROM ACCOUNT WHERE BALANCE=1200 AND
ACCOUNT='A-215';

11
ACCOUNT BALANCE BRANCHNAME
-------------------- ---------- --------------------
A-215 1200 Mianus

3. SQL> SELECT * FROM ACCOUNT WHERE BALANCE=1200 OR


ACCOUNT='A-222';
ACCOUNT BALANCE BRANCHNAME
-------------------- ---------- --------------------
A-215 1200 Mianus
A-201 1200 brighton
A-222 1200 redwood
A-217 1200 brighton

4. SQL> SELECT * FROM ACCOUNT WHERE BALANCE IN(100,1200);


ACCOUNT BALANCE BRANCHNAME
-------------------- ---------- --------------------
A-215 1200 Mianus
A-201 1200 brighton
A-222 1200 redwood
A-217 1200 brighton

5. SQL> SELECT * FROM ACCOUNT WHERE BALANCE NOT IN(100,1200);


ACCOUNT BALANCE BRANCHNAME
-------------------- ---------- --------------------
A-101 500 downtown
A-102 396 perryridge
A-305 346.5 roundhill

6. SQL> SELECT * FROM ACCOUNT WHERE BALANCE BETWEEN 1000 AND


5000;
ACCOUNT BALANCE BRANCHNAME
-------------------- ---------- --------------------
A-215 1200 Mianus
A-201 1200 brighton
A-222 1200 redwood
A-217 1200 brighton

7. SQL> SELECT * FROM ACCOUNT WHERE BRANCHNAME LIKE 'b%';


ACCOUNT BALANCE BRANCHNAME
-------------------- ---------- --------------------
A-201 1200 brighton
A-217 1200 brighton

8. SQL> SELECT * FROM ACCOUNT WHERE BRANCHNAME LIKE '%n';


ACCOUNT BALANCE BRANCHNAME

12
-------------------- ---------- --------------------
A-101 500 downtown
A-201 1200 brighton
A-217 1200 brighton
9. SQL> SELECT * FROM ACCOUNT WHERE BRANCHNAME LIKE 'b%n';
ACCOUNT BALANCE BRANCHNAME
-------------------- ---------- --------------------
A-201 1200 brighton
A-217 1200 brighton
SQL> update account set balance=1000 where balance>500;
4 rows updated.
SQL> select * from account;
ACCOUNT_NU BRANCH_NAME BALANCE
---------- --------------- ----------
A-101 Downtown 500
A-102 Perryridge 400
A-201 Brighton 1000
A-215 Mianus 1000
A-222 Redwood 1000
A-305 Round Hill 350
A-217 Brighton 1000
7 rows selected.
Delete all the rows:
SQL> delete from account;
7 rows deleted.
SQL> select * from account;
*
ERROR at line 1:
ORA-00942: table or view does not exist
Delete the particular rows using the WHERE clause.
SQL> delete from account where balance=350;
1 row deleted;
SQL> select * from account;
ACCOUNT_NU BRANCH_NAME BALANCE
---------- --------------- ----------
A-101 Downtown 500
A-102 Perryridge 400
A-201 Brighton 1000
A-215 Mianus 1000
A-222 Redwood 1000
A-217 Brighton 1000
6 rows selected.

RESULT:
Thus the DML commands are executed successfully.

13
EX.NO : 03 INTEGRITY CONSTRAINT
DATE :

AIM:

To create and modify a table using Data Definition Language (DDL) commands with
constraints.

DESCRIPTION:
An integrity constraint is a mechanism used by Oracle to prevent invalid data entry into
the table. It has enforcing the rules for the columns in a table. The types of the integrity
constraints are:
1. Domain Integrity
2. Entity Integrity
3. Referential Integrity
1. DOMAIN INTEGRITY
a) NOT NULL – It will not allow null values.
SYNTAX : create table <table name>(columnname data type (size) constraint
constraint_name not null);

b) CHECK - Use the CHECK constraint when you need to enforce integrity rules that
can be evaluated based on a condition (logical expression)

SYNTAX :
create table <table name>(columnname data type (size) constraint
constraint_name check (check_condition));

2. ENTITY INTEGRITY
a) UNIQUE – Avoid duplicate values

SYNTAX :
create table <table name>(columnname data type (size) constraint
constraint_name unique);

b) Composite UNIQUE – Multicolumn unique key is called composite unique


key.

SYNTAX :
create table <table name>(columnname1 data type (size),
columnname2 data type (size), constraint constraint_name
unique (columnname1, columnname2));

14
c) PRIMARY KEY – It will not allow null values and avoid duplicate values.
SYNTAX :
create table <table name>(columnname data type (size) constraint
constraint_name primary key);
d) Composite PRIMARY KEY – Multicolumn primary key is called composite
primary key
SYNTAX :
create table <table name>(columnname1 data type (size),
columnname2 data type (size), constraint constraint_name
primary key (columnname1, columnname2));

3.REFERENTIAL INTEGRITY
Reference key (foreign key) – Its represent relationships between tables.
Foreign key is a column whose values are derived from the primary key of the
same or some other table.
SYNTAX :
create table <table name>(columnname data type (size) constraint
constraint_name references parent_table_name);

To view the Constraints


select * from user_constraints where table_name =”TABLE NAME”;

Adding keys for an existing table


Alter table <table name >add constraint <constraint name>
primary key (column name);

Dropping the keys


Alter table <table name>drop constraint <constraint name>;

EXAMPLES QUERIES:

NOT NULL CONSTRAINTS:

SQL> CREATE TABLE STUD(ROLLNO NUMBER(6) NOT NULL,


NAME VARCHAR2(10), BRANCH VARCHAR2(6));

Table created.

SQL> DESC STUD;


Name Null? Type
------------------------ -------- ----------------------------
ROLLNO NOT NULL NUMBER(6)
NAME VARCHAR2(10)
BRANCH VARCHAR2(6)

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');

15
Enter value for rollno: 501
Enter value for name: ABHILASH
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'ABHILASH','CSE')

1 row created.

SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')

1 row created.

SQL> SELECT * FROM STUD;

ROLLNO NAME BRANCH


---------- ---------- ------
501 ABHILASH CSE
502 ABI CSE

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno:
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(,'BHAVYA','CSE')
INSERT INTO STUD VALUES(,'BHAVYA','CSE')
*
ERROR:CANNOT INSERT NULL INTO("SCOTT",'STUD',ROLLNO)

UNIQUE CONSTRAINTS

SQL> CREATE TABLE STUD(ROLLNO NUMBER(6) UNIQUE ,NAME


VARCHAR2(10),BRANCH VARCHAR2(6));

Table created.

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno: 501
Enter value for name: abhilash
Enter value for branch: cse

16
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'abhilash','cse')

1 row created.

SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')

1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C001290) violated

PRIMARY KEY CONSTRAINTS

SQL> CREATE TABLE STUD(ROLLNO NUMBER(6) PRIMARY KEY ,NAME


VARCHAR2(10), BRANCH VARCHAR2(6));

Table created.

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno: 501
Enter value for name: abhilash
Enter value for branch: cse
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'abhilash','cse')

1 row created.

SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')

17
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C001290) violated

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno:
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(,'BHAVYA','CSE')
INSERT INTO STUD VALUES(,'BHAVYA','CSE')
*
ERROR:CANNOT INSERT NULL INTO("SCOTT",'STUD',ROLLNO)

SQL> SELECT * FROM STUD;

ROLLNO NAME BRANCH


---------- ---------- ----------------
501 ABHILASH CSE
502 ABI CSE

CHECK CONSTRAINTS

SQL> create table stud(rno number(5),name varchar2(10),sal number(10)


constraint no_ck check(sal between 10000 and 30000));
Table created.
SQL> insert into stud values(&rno,'&name',&sal);
Enter value for rno: 567
Enter value for name: sachin
Enter value for sal: 29000
old 1: insert into stud values(&rno,'&name',&sal)
new 1: insert into stud values(567,'sachin',29000)

1 row created.
SQL> /
Enter value for rno: 565
Enter value for name: rohit

18
Enter value for sal: 35000
old 1: insert into stud values(&rno,'&name',&sal)
new 1: insert into stud values(565,'rohit',35000)
insert into stud values(565,'rohit',35000)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.NO_CK) violated

FOREIGN KEY CONSTRAINTS

SOL>create table adm(stuid number(6) constraint stuid_pk primary key, sname


varchar2(15), per number(5));
Table created.
SQL> insert into adm values(&stuid,'&sname',&per);
Enter value for stuid: 1
Enter value for sname: abi
Enter value for per: 80
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(1,'abi',80)

1 row created.
SQL> /
Enter value for stuid: 2
Enter value for sname: rohit
Enter value for per: 89
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(2,'rohit',89)
1 row created.
SQL> /
Enter value for stuid: 3
Enter value for sname: sachin
Enter value for per: 99
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(3,'sachin',99)

1 row created.
SQL> /
Enter value for stuid: 4
Enter value for sname: naveen
Enter value for per: 70
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(4,'naveen',70)
1 row created.

SQL> select * from adm;

19
STUID SNAME PER
---------- --------------- ----------
1 abi 80
2 rohit 89
3 sachin 99
4 naveen 70

SQL> create table course(stuid number(6) constraint sid_fk references


adm(stuid),branch varchar2(5),sec varchar2(10));
Table created.

SQL> insert into course values(&stuid,'&branch','&sec');


Enter value for stuid: 1
Enter value for branch: cse
Enter value for sec: a
old 1: insert into course values(&stuid,'&branch','&sec')
new 1: insert into course values(1,'cse','a')
1 row created.
SQL> /
Enter value for stuid: 5
Enter value for branch: cse
Enter value for sec: b
old 1: insert into course values(&stuid,'&branch','&sec')
new 1: insert into course values(5,'cse','b')
insert into course values(5,'cse','b')
*ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SID_FK) violated - parent key not found
SQL> delete from adm where stuid=1;
*
ERROR at line 1:
ORA-02292: integrity constraint (SCOTT.SID_FK) violated - child record found
SQL> delete from course where stuid=1;
1 row deleted.
SQL> delete from adm where stuid=1;
1 row deleted.
SQL>select * from adm;
STUID SNAME PER
----- --------------- - ----------
2 rohit 89
3 sachin 99
4 naveen 70

RESULT:
Thus the DDL commands using constraint are executed successfully.

20
EX.NO :04
SQL FUNCTIONS
DATE :
AIM:
To verify the usage of data using built in functions.

DESCRIPTION:
Functions are a very powerful feature of SQL. Function accept zero or more arguments
and both return one or more results. Both are used to manipulate individual data items. Operators
differ from functional in that they follow the format of function_name (arg..). A argument is a
user defined variables or constants. Most operators accept at most 2 arguments while the
structure of functions permit to accept 3 or more arguments.
Function can be classifies into
 single row function and
 group functions.

SQL Functions can be used to do the following:


• Perform calculations on data
• Modify individual data items
• Manipulate output for groups of rows
• Format dates and numbers for display
• Convert column data types
SQL functions sometimes take arguments and always return a value.

Single Row Functions:


A single row function or scalar function returns only one value for every row queries in
table. Single row function can appear in a select command and can also be included in a where
clause. The single row function can be broadly classified as,
 Data Function
 Numeric Function
 Character Function
 Conversion function
 Miscellaneous/General Function

Features of single-row functions include:


• Acting on each row returned in the query
• Returning one result per row
• Possibly returning a data value of a different type than that referenced
• Possibly expecting one or more arguments
• Can be used in SELECT, WHERE, and ORDER BY clauses; can be nested

SYNTAX:

21
Function _name (column / expression, [arg 1, arg 2, …]

Function _name  is the name the function


Column  is any named database column
Expression  is any character string or calculated expression
arg 1, arg 2,  is any argument to be used by the function.

Date Function:
Date functions accept DATE input and may return a value of date type a number.

1. Add_months: This function returns a date after adding a specified date with specified
number of months.
Syntax: Add_months(d,n); where d- date, n- number of months
Eg: select add_months(systemdate,2) from dual;

2. Last_day: It displays the last date of that month.


Syntax: Last_day(d) ; where d- date
Eg: select last_day(‘4-jan-2011’) from dual;

3. Month_between : It gives the difference in number of months between d1 & d2.


Syntax: month_between(d1,d2); where d1 & d2 – dates
Eg: select month_between(‘1-jan-2011’,’1-feb-2011’) from dual;

4. Round(d,[fmt]); This function returns the date, which is rounded to the unit specified by
the format model.
Syntax: round(d,[fmt]);
Where d- date, [fmt] – optional. By default date will be rounded to the nearest
day.
Eg: select round(to_date(‘1-jan-2011’,’dd-mm-yy’),’year’) from dual;
Select round(‘1-jan-2011’’year’) from dual;
5. Next_day(d.day-name); This function returns the first date which is day_name that comes
after the date d
Syntax: Next_day(d.day-name); where day_name – valid day
Eg: select next_day(‘1-jan-2011’,’saturday) from dual;

6. Sysdate : This function returns the current date and time.


Syntax : sysdate
Eg: select sysdate from dual;

Character functions:
This function accept character input and can return both character and number values.

22
initcap(char)  Converts alpha character values to uppercase for the first
letter of each word, all other letters in lowercase.

lower(char)  Converts alpha character values to lowercase.


upper(char)  Converts alpha character values to uppercase
ltrim(char [,set])  Removes character from left of char if they are in
‘set’ till a character not found in set is encountered.
Rrim(char [,set])  Removes character from right of char if they are in
‘set’ till a character not found in set is encountered.
Replace(char, search string, replace string)  Returns char replacing search
string with replace string.

concat(column1|expression1,column2|expression2)  Concatenates the first


character value to the second character value;
equivalent to concatenation operator (||)
substr(char,m[,n])  Returns specified characters from character value
starting at character position m, n characters long (If m
is negative, the count starts from the end of the
character value. If n is omitted, all characters to the end
of the string are returned.)

23
Number functions:

This functions accept numeric input and return numeric values.

Conversion Function:
This function converts a value from one data type to another. This function is categorized as :
 To_char( )
 To_date( )
 To_number( )

1. to_char ( ) : This function converts date/number to a varchar2 type in a form specified


by date format. If format is negelected then it converts date to varchar2 in the default
date format.

Syntax : to_char(d/n,[format]);

Eg: select to_char( sysdate,’dd-mm-yy’) from dual;


Select to_char(balane,’9,99,999.99’) from account;

2. to_date( ): This function converts character to date data format specified in the from
character.
Syntax :to_date (d,[format]);

24
Eg: select to_date(‘jan 1 2011’,’mm-dd-yy’) from dual;

3. to_number ( ): This function converts char, a value of CHAR or VARCHAR2 data


type to number in the format specified by the format model fmt.

Syntax: to_number(char [,fmt]);


Eg: Select to-number(pin) from place;

Miscellaneus/ General Functions:


1. uid : This function returns the integer value(id) corresponding to the user currently
logged in.
Eg: select uid from dual;
2. user : This function returns the logins user name.
Eg: select user from dual;
o/p; it47
3. nvl : The null value function is mainly used in the case where we want to consider
null values as zero.
Syntax: nvl (exp1, exp2)
If exp1 is null, return exp2. If exp1 is not null, return exp1.
Eg: select cusid, shipdate, nvl(total,0) from order;
4. vsize : It returns the number of bytes in expression.
Eg: select vsize(‘it’) from dual;
o/p ; 2

GROUP FUNCTIONS:
Group functions or aggregate functions operate on sets of rows to give one result per
group.

SYNTAX:

SELECT [column,] group_function(column), ... FROM table


[WHERE condition]
[GROUP BY column]
[ORDER BY column];
EXPLANATIONS
• DISTINCT makes the function consider only non duplicate values; ALL makes it consider
every
value including duplicates. The default is ALL and therefore does not need to be specified.
• The data types for the functions with an expr argument may be CHAR, VARCHAR2,
NUMBER,
or DATE.
• All group functions ignore null values. To substitute a value for null values, use the NVL,
NVL2,
or COALESCE functions.

25
• The Oracle server implicitly sorts the result set in ascending order when using a GROUP BY
clause. To override this default ordering, DESC can be used in an ORDER BY clause.

TYPES OF GROUP FUNCTION:


• AVG
• COUNT
• MAX
• MIN
• STDDEV
• SUM
• VARIANCE

Function Description

1. avg: It returns average value of n.


Syntax: avg([distinct|all]n)
Eg: select avg(balance) from account where branch_name='Brighton';
2. Max : It returns the maximum value of expr.
Syntax: max([distinct|all]expr)
Eg: select max(balance) from account;
3. Min: It returns the maximum value of expr.
Syntax: min([distinct|all]expr)
Eg: select min(balance) from account;
4. Sum : It returns sum of value of n.
Syntax: sum([distinct|all]n)
Eg: select sum(balance) from account;
5. Count : It returns the number of rows returned by the query.
Syntax: count([distinct|all]expr)
Eg: select count(balance) from account;

GROUP BY Clause: This allows us to use simultaneous column name and group functions
If the SQL statement does not contain a WHERE clause then the GROUP BY clause is
specified immediately after the FROM clause.
If the SQL statement contain where a clause then the GROUP BY clause is specified
after the WHERE clause.

SYNTAX:

SELECT column, group_function(column) FROM table [WHERE condition]


[GROUP BY group_by_expression] [ORDER BY column];

group_by_expression  specifies columns whose values determine


basis for grouping rows

HAVING clause : This is used to specify conditions on rows retrieved by using


group by clause.

26
EXAMPLES OF SINGLE ROW FUNCTIONS:

SQL> select sysdate from dual;


SYSDATE
--------------
22-JUL-2014

SQL> select user from dual;


USER
--------
ITR63

SQL> select userenv('terminal') from dual;


USERENV('TERMINAL’)
IT2

SQL> select loan_number,round(amount,0) from loan;


LOAN_NUMBER ROUND(AMOUNT,0)
---------------------- ---------------------------
L-11 900
L-14 1500
L-15 1500
L-16 1300
L-17 1000
L-23 2000
L-93 500

SQL> select round(7643.5461,-3) from dual;


ROUND(7643.5461,-3)
----------------------------
8000
SQL> select upper(customer_name) from customer;
UPPER (CUSTOMER_NAME)
--------------------------------------
ADAMS
BROOKS
CURRY
GLENN
GREEN
5 rows selected.
SQL> select lower(customer_name) from customer;
LOWER(CUSTOMER_NAME)
---------------------------------------
adams
brooks

27
curry
glenn
green
5 rows selected.

SQL> select initcap(customer_name) from customer;


INITCAP(CUSTOMER_NAME)
----------------------------------------
Adams
Brooks
Curry
Glenn
Green
5 rows selected.

SQL> select trunc(4646.787878,2) from dual;


TRUNC (4646.787878,2)
------------------------------
4646.78

SQL> select customer_name,length(customer_name) as namelength from customer where


length(customer_name)>6;
CUSTOMER_NAME NAMELENGTH
-------------------------- ---------------------
Johnson 7
Lindsay 7

SQL> select months_between('02-dec-14','06-apr-14') from dual;

MONTHS_BETWEEN('02-DEC-14','06-APR-14')
---------------------------------------
7.87096774

SQL> select add_months('8-aug-14',2) from dual;

ADD_MONTH
---------
08-OCT-14

SQL> select next_day('06-oct-14','wednesday') from dual;

NEXT_DAY(
---------
08-OCT-14

SQL> select next_day('06-oct-14', 2 'monday')from dual;

28
NEXT_DAY(
---------
13-OCT-14

SQL> select last_day('05-feb-14') from dual;

LAST_DAY(
---------
28-FEB-14

SQL> select last_day('08-aug-14')from dual;

LAST_DAY(
---------
31-AUG-14

SQL> select round(to_date('07/21/14','mm/dd//yy'),'month') from dual;

ROUND(TO_
---------
01-AUG-14

SQL> select trunc(to_date('07/21/14','mm/dd/yy'),'month') from dual;

TRUNC(TO_
---------
01-JUL-14

EXAMPLES OF GROUP FUNCTIONS:

SQL> select * from employee;


id name dept age salary location
---- ----------- ---------------- ---------------- --------------- -------------------
100 Ramesh Electrical 24 25000 Bangalore
101 Hrithik Electronics 28 35000 Bangalore
102 Harsha Aeronautics 28 35000 Mysore
103 Soumya Electronics 22 20000 Bangalore
104 Priya InfoTech 25 30000 Mangalore

SQL> select count (*) from employee;


COUNT(*)
-------------
5

29
SQL> select count (*) from employee where dept = ‘Electronics’;
COUNT(*)
-------------
2

SQL> select sum(salary) from employee;


SUM(salary)
-------------------
145000

SQL> select dept, sum(salary) from employee group by dept;


dept salary
---------------- --------------
Electrical 25000
Electronics 55000
Aeronautics 35000
InfoTech 30000

SQL> select location, dept, sum(salary) from employee group by location, dept;

location dept salary


------------- --------------------------
Bangalore Electrical 25000
Bangalore Electronics55000
Mysore Aeronautics 35000
Mangalore InfoTech 30000

SQL> select dept, sum(salary) from employee group by dept having


sum(salary) > 25000;
dept salary
---------------- --------------
Electronics 55000
Aeronautics 35000
InfoTech 30000

RESULT:
Thus the data are manipulated using SQL functions .

30
EX.NO :05
SET OPERATORS
DATE :

AIM:
To verify the usage of data using set operators.
DESCRIPTION:
The Set operators combine the result of 2 queries into a single result. The following are
the operators:
 Union
 Union all
 Intersect
 Minus
The rules to which the set operators are strictly adhere to:
 The queries which are related by the set operators should have a same number of
column and column definition.
 Such query should not contain a type of long.
 Labels under which the result is displayed are those from the first select
statement.
Union:
Returns all distinct rows selected by both queries.
SYNTAX:
Query1 Union Query2;
Union all
Returns all rows selected by either including the dulicates.
SYNTAX:
Query1 Union all Query2;
Intersect:
Returns rows selected that are common to both queries.
SYNTAX:
Query1 Intersect Query2;
Minus:
Returns all distinct rows selected by the first query and are not by the second
SYNTAX:
Query1 Minus Query2;

EXAMPLES QUERIES:
To find all the bank customers having a loan, an account, or both at the bank.
SQL> select customer_name from depositor union select customer_name from
2 borrower;
CUSTOMER_NAME
--------------------
Adams
Curry
Hayes
Johnson
Jones
Lindsay

31
Smith
Turner
Williams
9 rows selected.

To retain all duplicates:


SQL> select customer_name from depositor union all select customer_name from
2 borrower;
CUSTOMER_NAME
--------------------
Hayes
Johnson
Johnson
Jones
Lindsay
Smith
Turner
Adams
Curry
Hayes
Johnson
Jones
Smith
Smith
Williams
15 rows selected.

To find all customer who have a loan and a account at the bank.
SQL> select distinct customer_name from depositor intersect
2 select distinct customer_name from borrower;

CUSTOMER_NAME
-------------------------
Hayes
Johnson
Jones
Smith

To retain all duplicates:


SQL> select customer_name from depositor intersect select customer_name from
2 borrower;
CUSTOMER_NAME
--------------------
Hayes
Johnson
Jones

32
Smith

To find all customers who have an account but no loan at the bank
SQL> select customer_name from depositor minus select customer_name from
borrower;
CUSTOMER_NAME
--------------------
Lindsay
Turner

EX.NO :06
SUBQUERIES
DATE :

RESULT:
Thus the data are manipulated using set operators.

AIM:
To perform the queries using subqueries.
DESCRIPTION:
The query within another is known as a subquery. A statement containing subquery is
called parent statement. The rows returned by subquery are used by the parent statement.

TYPES:
1. Subqueries that return several values:
Subqueries can also return more than one value. Such results should be made use
along with the operators in and any.
Eg: Select ename, eno from employee where salary <any (select salary from
employee where deptno=10);
2. Multiple queries:
Here more than one sunquery is used. These multiple subqueries are combined by
means of ‘and’ & ‘or’ keywords.

3. Correlated subquery:
A subquery is evaluated once for the entire parent statement whereas a correlated
subquery is evaluated once per w processed by the parent statement.

33
Eg: selec from emp x where x.salary > (select avg(salary) fro emp where
deptno=x.deptno); selects the employee details that the salary of employee is >
the average salary of his own department.

NESTED SUBQUERIES

1. CREATE – Creating a new table from an existing table


SYNTAX:
create table <table name> as select columnname1,columnname2,..,from existing table
name;

EXAMPLE:
SQL> select * from customer;
CUST_NAME CUST_STREET CUST_CITY
----------------------------------------------------------------------------------------
Jonny Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Lindsay Park Pittsfield
SQL> create table consumer as select * from customer;
Table created.

2. INSERT:
SYNTAX:
Insert into <table name> select <column name> from <existing table name>where predicate.

EXAMPLE:
SQL> insert into consumer as select * from customer;
5 rows created.

SQL> select * from consumer;

CUST_NAME CUST_STREET CUST_CITY


----------------------------------------------------------------------------------------
Jonny Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Lindsay Park Pittsfield

SQL> select * from branch;


BRANCH_NAME BRANCH_CITY ASSETS
----------------------------------------------------------------------------------------
Downtown Brooklyn 12000
Redwood Palo 210000

34
Perryridge Horseneck 17000
Minus Horseneck 29000
Brighon Brooklyn 60000

SQL> insert into customer values(‘Sonia’,’Park’,’Palo’);


1 row created.
SQL> select * from customer;
CUST_NAME CUST_STREET CUST_CITY
----------------------------------------------------------------------------------------
Jonny Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Lindsay Park Pittsfield
Sonia Park Palo
6 rows selected.

3. DELETE:
SYNTAX:
Delete from <table name> where condition = (select statement)

EXAMPLE:
SQL> delete from consumer where cust_city=(select branch city from branch
where branch_name=’northtown’);
1 row deleted.
SQL> select * from customer;
CUST_NAME CUST_STREET CUST_CITY
----------------------------------------------------------------------------------------
Jonny Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Lindsay Park Pittsfield

4. UPDATE:
SYNTAX:
Update <table name> set column name = value where condition= (select statement)

EXAMPLE:
SQL> update consumer set customer_street=’main’ where customer_name in
(select customer_name from customer where customer_street=’North’);
2 row updated.

SQL> select * from customer;


CUST_NAME CUST_STREET CUST_CITY

35
----------------------------------------------------------------------------------------
Jonny Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Lindsay Park Pittsfield

5. SELECT:
Find all the information of customer who has an account number is A-101.

SQL> select * from customer where customer_name in(select customer_name


from depositor where account_no=101);

CUST_NAME CUST_STREET CUST_CITY


----------------------------------------------------------------------------------------
Jonny Main Harrison

Find all customers who have a loan from the bank, find their names and loan numbers.

SQL> select customer_name, loan_no from borrower where loan_no in (select


loan_no from loan);

CUST_NAME LOAN_NO
--------------------------------------------------------------
Jonny 101
Lindsay 102
Curry 103

Find all customers who are borrowers from the bank and who appear in the list of
depositor.

SQL> select distinct customer_name from borrower where customer_name in


(select customer_name from depositor);

CUST_NAME
--------------------------------
Jonny

Find all customers who do have a loan at the bank, but do not have an account at the bank.

SQL> select distinct customer_name from borrower where customer_name not in


(select customer_name from depositor);

CUST_NAME
--------------------------------
Curry

36
Lindsay

Find the names of all branches with customers who have an account in the bank and who
live in Harrison city.

SQL> select branch_name from account where account_number in(select


account_number from depositor where customer_name in(select customer_name from customer
where customer_city=’Harrison’);

BRANCH_NAME
--------------------------------
Downtown
Mianus

select rows from borrower such that the loan numbers are lesser than any Loan number
where the branch name is “Perryridge”.

SQL> select * from borrower where loan_number<any(select loan_number


from loan where branch_name=’Perryridge’);

CUST_NAME LOAN_NO
--------------------------------------------------------------
Jonny 101
Lindsay 102

select rows from borrower such that the loan numbers are greater than all Loan number
where the branch name is “downtown”.

SQL> select * from borrower where loan_number>all(select loan_number


from loan where branch_name=’ Downtown’);

CUST_NAME LOAN_NO
------------------- ---------------------
Lindsay 102
Curry 103

ANOTHER EXAMPLE:

SQL>select * from dept;


DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS

37
30 SALES CHICAGO
40 OPERATIONS BOSTON

SQL> select empno, ename, job, sal, deptno from emp;


EMPN ENAME JOB SAL DEPTNO
---------- ---------- --------- ---------- ----------
7369 SMITH CLERK 800 20
7499 ALLEN SALESMAN 600 30
7521 WARD SALESMAN 1250 30
7566 JONES MANAGER 2975 20
7654 MARTIN SALESMAN 1250 30
7698 BLAKE MANAGER 2850 30
7782 CLARK MANAGER 2450 10
7788 SCOTT ANALYST 3000 20
7839 KING PRESIDENT 5000 10
7844 TURNER SALESMAN 1500 30
7876 ADAMS CLERK 1100 20
7900 JAMES CLERK 950 30
7902 FORD ANALYST 3000 20
7934 MILLER CLERK 1300 10

Select empno, ename ,job, salary, from table whose location is located in chicago.

SQL> select empno,ename,job,sal,deptno from emp where deptno in (select deptno


from dept where loc = 'chicago');
EMPNO ENAME JOB SAL DEPTNO
---------- ---------- --------- ---------- ----------
7900 JAMES CLERK 950 30
7844 TURNER SALESMAN 500 30
7698 BLAKE MANAGER 2850 30
7654 MARTIN SALESMAN 1250 30
7521 WARD SALESMAN 250 30
7499 ALLEN SALESMAN 1600 30
6 rows selected.
select ename, deptno from table whose job is clerk and department no is greater than 20
SQL> select ename, deptno from (select ename, deptno from emp
where job = 'clerk' ) where deptno > 20;
ENAME DEPTNO
---------- ----------
JAMES 30

Select the empname, each employee’s salary, and find the difference of salary of each
employee from the maximum salary of the employees.
SQL> select ename,(select max(sal) from emp) "maxsal", sal,((select max(sal) from emp ) – sal)
"difference" from emp;

38
ENAME MAXSAL SAL DIFFERENCE
---------- ---------- ---------- ----------
SMITH 5000 800 4200
ALLEN 5000 1600 3400
WARD 5000 1250 3750
JONES 5000 2975 2025
MARTIN 5000 1250 3750
BLAKE 5000 2850 2150
CLARK 5000 2450 2550
SCOTT 5000 3000 2000
TURNER 5000 1500 3500
ADAMS 5000 1100 3900
JAMES 5000 950 4050
FORD 5000 1300 3700
14 rows selected.

select all employees whose salary is less than the average of all the employees' salaries in
the same department.

SQL> select ename ,sal ,deptno from emp a where a.sal < (select avg(sal) from emp b
where a.deptno = b.deptno) order by deptno;

ENAME SAL DEPTNO


---------- ---------- ----------
CLARK 2450 10
MILLER 300 10
SMITH 800 20
ADAMS 1100 20
WARD 1250 30
MARTIN 1250 30
TURNER 1500 30
JAMES 950 30
8 rows selected.

Update whose salary is less than their department's average.

SQL> update emp a set sal = (select avg(sal) from emp b where a.deptno = .deptno)
where sal < (select avg(sal) from emp c where a.deptno = c.deptno);
8 rows updated.

SQL> select ename, sal, deptno from emp order by deptno, ename;
ENAME SAL DEPTNO
---------- ---------- ----------
CLARK 2916.67 10
KING 5000 10

39
MILLER 2916.67 10
ADAMS 2175 20
FORD 3000 20
JONES 2975 20
SCOTT 3000 20
SMITH 2175 20
ALLEN 1600 30
BLAKE 2850 30
JAMES 1566.67 30
MARTIN 1566.67 30
TURNER 1566.67 30
WARD 1566.67 30
14 rows selected.

Delete the highest earning employees in each department.

SQL> delete from emp a where a.sal = (select max(sal) from emp b here a.deptno =
b.deptno);
4 rows deleted.

SQL> select ename, sal, deptno from emp order by deptno, ename;
ENAME SAL DEPTNO
---------- ---------- ----------
CLARK 2916.67 10
MILLER 2916.67 10
ADAMS 2175 20
JONES 2975 20
SMITH 2175 20
ALLEN 1600 30
JAMES 1566.67 30
MARTIN 1566.67 30
TURNER 1566.67 30
WARD 1566.67 30
10 rows selected.

40
RESULT:
Thus the subqueries are executed successfully
EX.NO :08
JOIN OPERATIONS
DATE :

AIM:
To perform the data using join operations.
DESCRIPTION:
The join concept is to combine data spread across tables. A join is actually performed by
the ‘where’ clause which combines specified rows of tables.
When data from more than one table in the database is required, a join condition is used.
Rows in one table can be joined to rows in another table according to common values existing in
corresponding columns, that is, usually primary and foreign key columns. To display data from
two or more related tables, write a simple join condition in the WHERE clause.

Join Syntax:
Select columns from table1, table2 where logical expression;
Prefix the column name with the table name when the same column name appears in more than
one table.

SELECT table1.column, table2.column FROM table1, table2;

Types of Joins:
1. Simple join
2. Self join
3. Outer join
1. Simple join:
It is the most common types on join. It retrieves the rows from 2 tables having a
common column and is further classified into
a) Equi – join: A join, which is based on equalities, is called equi join.
Eg: select * from item, cust where item.id= cust.id;
In the above eg. , item.id = cust.id performs the join statement. It retrieves
rows from the both tables provided they both have the same id as specified by
the where clause. Since the where clause uses the comparison operator (=) to

41
perform a join, it is said to be equi join. It combines the matched rows of
tables.
b) Non Equi-join: It specifies the relationship between columns belonging to
different tables by making use of relational operators other than ‘=’.
Eg: select * from item, cust where item.id < cust.id

Table Aliases:
Table aliases are used to make multiple table queries shorted and more readable.
We give an aliase name to the table in the ‘from’ clause and use it instead of the name
throughout the query.

2. Self join:
Joining of a table to itself is known as self-join. It joins one row in a table to
another. It can compare each row of the table to itself and also with other rows of
the same table.
Eg; select * from emp x, emp y where x.salary >= (select avg(salary) from x.emp
where x.deptno= y.deptno);
3. Outer join:
It extends the result of a simple join. An outer join returns all the rows returned by
simple join as well as those rows from one table that do not match any row from
the table. The symbol (+) represents outer join.
Eg: select ename, job, dname from emp, dept where emp.deptno (+) =
Dept.deptno;

Outer Joins Syntax


• You use an outer join to also see rows that do not meet the join condition.
• The Outer join operator is the plus sign (+).
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column(+) = table2.column;
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column = table2.column(+);

Using outer joins to return records with no direct match.


The missing rows can be returned if an outer join operator is used in the join condition. The
operator is a plus sign enclosed in parentheses (+), and it is placed on the “side” of the join that is
deficient in information. This operator has the effect of creating one or more null rows, to which
one or more rows from the nondeficient table can be joined.
In the syntax:
table1.column = is the condition that joins (or relates) the tables together.

42
table2.column (+) is the outer join symbol, which can be placed on either side of the
WHERE clause condition, but not on both sides. (Place the outerjoin symbol following
the name of the column in the table withoutthe matching rows.

Outer Join Restrictions


• The outer join operator can appear on only one side of the expression—the side that has
information missing. It returns those rows from one table that have no direct match in the other
table.
• A condition involving an outer join cannot use the IN operator or be linked to another condition
by the OR operator..
EXAMPLES:
1. INNER JOIN:
SQL> select *from loan inner join borrower on loan.loan_number = borrower.loan_number;
LOAN_N BRANCH_NAME AMOUNT CUSTOMER_NAME LOAN_N
------ --------------- ---------- -------------------- ------
L-16 Perryridge 1300 Adams L-16
L-93 Mianus 1500 Hayes L-15
L-11 Round Hill 900 Smith L-11
L-23 Redwood 2000 Smith L-23

2.LEFT OUTER JOIN:


SQL> select * from loan left outer join borrower on loan.loan_number
=borrower.loan_number;
LOAN_N BRANCH_NAME AMOUNT CUSTOMER_NAME LOAN_N
------ --------------- ---------- -------------------- ------
L-16 Perryridge 1300 Adams L-16
L-93 Mianus 500 Curry L-93
L-15 Perryridge 1500 Hayes L-15
L-11 Round Hill 900 Smith L-11
L-23 Redwood 2000 Smith L-23
L-14 Downtown 1500
L-17 Downtown 1000

7 rows selected.
3. RIGHT OUTER JOIN:
SQL> select * from loan right outer join borrower on
loan.loan_number=borrower.loan_number;
LOAN_N BRANCH_NAME AMOUNT CUSTOMER_NAME LOAN_N
------ --------------- ---------- -------------------- ------
L-11 Round Hill 900 Smith L-11
L-15 Perryridge 1500 Hayes L-15
L-16 Perryridge 1300 Adams L-16
L-23 Redwood 2000 Smith L-23
43
L-93 Mianus 500 Curry L-93

4. FULL OUTER JOIN:


SQL> select * from loan full outer join borrower on
loan.loan_NUMBER=BORROWER.LOAN_NUMBER;
LOAN_N BRANCH_NAME AMOUNT CUSTOMER_NAME LOAN_N
------ --------------- ---------- -------------------- ------
L-16 Perryridge 500 Curry L-93
L-15 Perryridge 1500 Hayes L-15
L-11 Round Hill 900 Smith L-11
L-23 Redwood 2000 Smith L-23
L-14 Downtown 1500
L-17 Downtown 1000
7 rows selected.

RESULT:

Thus SQL statements using joins are executed.

EX.NO :09
VIEW, SEQUENCE, SYNONYM AND INDEX
DATE :

AIM:
To verify the usage of objects such as view, sequence and index.

DESCRIPTION:

A view is the tailored presentation of data contained in one or more tables and cam also
be said as restricted view to the data in the tables. A view is a virtual table or a stored query

44
which takes the output of a query and treats is as a table. The table upon which a view is created
is called as base table.

A view is a logical table based on a table or another view. A view contains no data of its
own but is like a window through which data from tables can be viewed or changed. The tables
on which a view is based are called base tables. The view is stored as a Select statement in the
data dictionary.

Advantages of a view:
1. Additional level of table security.
2. Hides data complexity.
3. Simplifies the usage by combining multiple tables into a single table.
4. Provides datas in different perspective.

SYNTAX:
CREATE [OR REPLACE ] VIEW <view name> [column alis names] AS <query>
[with <options > conditions];
Eg: Create or replace view emp_view as select * from emp;

QUERIES:
1. SQL> Create view branch_total_loan(branch_name,total_loan) as
Select branch_name, sum(amount) from loan group by branch_name;

View created
2. SQL>Create view all_customer as (select branch_name, customer_name from
Depositor, account where depositor.account_number = account.account_number)
Union (select Branch_name,customer_name from borrower,loan where
borrower.loan_number = loan.loan_number;

View created
SQL> desc all_customer;
Name Null? Type
----------------------------------------- -------- ----------------------------
BRANCH_NAME VARCHAR2(15)
CUSTOMER_NAME VARCHAR2(15)

SQL> update all_customer set branch_name= ‘erode’


Where branch_name = ‘Downtown’;
SQL> select * from all_customer;
SQL> Drop view all_customer;

ii) SEQUENCE:- Automatic generation of primary or unique key integer value.

SYNTAX:
Create sequence <seq_name>increment by n start with n [maxvalue n]
[Minvalue n] [Cycle/no cycle] [Cache/no cache].
45
SQL> create sequence seq1 increment by 1 start with 100 maxvalue 105
minvalue 100 cycle cache 4;

Create a table called university-having fields NO NUMBER (5), NAME VARCHAR2(20).And


apply the following query to find use of the sequence.

SQL>insert into university values (seq1.nextval,’&name’).


Insert the following 8 names like (anna, msu, mku, madras.barathidhasan, barathiyar, Annamalai,
Azhagappa)

Display all values from university:

SQL>Select * from university:


If you want to see the next current available value from the sequence apply the following
SQL>Select seq1.currval from dual;

If you want to see the next value from the sequence apply the following
SQL>Select seq1.nextval from dual;

iii) SYNONYM: Which is used as an alias name (alternative name) for a table, view or
sequence.

SYNTAX:
CREATE synonym<synonym_name>for<table_name>

EXAMPLE:
create synonym uni for university;

SQL>create table customer(cname varchar2(20),cstreet varchar2(20),ccity


varchar2(20),salary number(6));
Table created.

SQL>insert into customer values(‘&cname’,’&cstreet’,’&ccity’,’&salary);


Enter value for cname:Sonia
Enter value for cstreet:Main
Enter value for ccity:Hyd
Enter value for salary:10000
Old 1:insert into customer values(‘&cname’,’&cstreet’,’&ccity’,’&salary);
new 1:insert into customer values(‘Sonia’,’Main’,’Hyd’,’10000)
1 row created.
SQL> select * from customer;
CNAME CSTREET CCITY SALARY
------------- ----------------- --------------- -----------------
Sonia Main Hyd 10000
Mena Sun Slm 15000

46
Rathna Sub Slm 10000
Swetha Down Hyd 12000

SQL> create view custall(custname,custcity)as(select cname,ccity from customer);


View created.

SQL> select * from custall;


CUSTNAME CCITY
------------- ---------------
Sonia Hyd
Mena Slm
Rathna Slm
Swetha Hyd

SQL> create sequence seq 1 increment by 2 start with 100 maxvalue 110
minvalue 100 cache 4;
Sequence created.

SQL> create table university(num number(5),name varchar2(20));


Table created.

SQL>insert into university values(seq 1.nextval,’&name’);


Enter value for name:anna
Old 1:insert into university values(seq 1.nextval,’&name’);
new 1:insert into university values(seq 1.nextval,’anna’)
1 row created.
SQL>/
Enter value for name:msu
Old 1:insert into university values(seq 1.nextval,’&name’);
new 1:insert into university values(seq 1.nextval,’mus’)
1 row created.

SQL>/
Enter value for name:mku
Old 1:insert into university values(seq 1.nextval,’&name’);
new 1:insert into university values(seq 1.nextval,’mku’)
1 row created.

SQL> select * from university;


NUM NAME
------------ -----------------
100 anna
102 msu
104 mku
106 madras
108 barathidasan

47
5 rows selected.

SQL> select seq1.currval from dual;


CURRVAL
------------------
108
SQL> select seq1.nextval from dual;
NEXTVAL
------------------
110
SQL> create synonym uni for university;
Synonym created.

SQL> select * from uni;


NUM NAME
100 anna
102 msu
104 mku
106 madras
108 barathidasan
5 rows selected.

RESULT:

Thus the data objects such as view ,synonyms index and sequence are executed
successfully.

EX.NO : 10
TRANSACTION CONTROL LANGUAGE(TCL)
DATE :

AIM:
To verify the usage of data using transaction control commands.

DESCRIPTION:
All changes made to the database is defined as a transaction. It is a logical unit of work.
The transaction can be made permanent to a database only if they are committed.
The Transaction Control Language commands are:
 COMMIT
 ROLLBACK
 SAVEPOINT

48
The transaction begins with an executable SQL statement and ends explicitly with either
rollback or commit statements implicitly, i.e., automatically when a DDL statement is used.

With COMMIT and ROLLBACK statements, you can:


• Ensure data consistency
• Preview data changes before making changes permanent
• Group logically related operations statements.

Statement Description:
COMMIT : This command is used to make all transaction changes permanent to the
database.

SAVEPOINT : It is not a command. It is only a marker. Savepoints are used to divide a


lengthy transaction into smaller one.

ROLLBACK : This command is used to undo all the changes made in the current
transaction. We can either rollback the entire transaction or rollback a transaction to a savepoint.

SYNTAX:
1. COMMIT;
2. SAVEPOINT id;
3. ROLLBACK ; OR ROLLBACK TO SAVEPOINT id;

If you omit the TO SAVEPOINT clause, the ROLLBACK statement rolls back the entire
transaction. As savepoints are logical, there is no way to list the savepoints you have created.

EXAMPLES:

SAVE POINT:

SQL> select * from loan;


LOANNO BRANCHNAME LOANAMOUNT
-------------------- -------------------- -----------
L-17 Downtown 1000
L-23 redwood 2000
L-15 perryridge 1500
L-14 downtown 1500
L-93 mianus 500
L-11 roundhill 500
L-16 perryridge 1300

7 rows selected.

SQL> delete from loan where loanno='L-17';


1 row deleted.

49
SQL> select * from loan;

LOANNO BRANCHNAME LOAANAMOUNT


-------------------- -------------------- -----------
L-23 redwood 2000
L-15 perryridge 1500
L-14 downtown 1500
L-93 mianus 500
L-11 roundhill 500
L-16 perryridge 1300
6 rows selected.

ROLLBACK:

SQL> rollback;
Rollback complete.

SQL> select * from loan;

LOANNO BRANCHNAME LOANAMOUNT


L-17 Downtown 1000
L-23 redwood 2000
L-15 perryridge 1500
L-14 downtown 1500
L-93 mianus 500
L-11 roundhill 500
L-16 perryridge 1300
7 rows selected.

COMMIT:
SQL> select * from loan;
LOANNO BRANCHNAME LOANAMOUNT
L-23 redwood 2000
L-15 perryridge 1500
L-14 downtown 1500
L-93 mianus 500
L-11 roundhill 500
L-16 perryridge 1300
L-17 downtown 1000
7 rows selected.

SQL> delete from loan where loanno='L-17';


1 row deleted.

SQL> select * from loan;

50
LOANNO BRANCHNAME LOAANAMOUNT
L-23 redwood 2000
L-15 perryridge 1500
L-14 downtown 1500
L-93 mianus 500
L-11 roundhill 500
L-16 perryridge 1300

6 rows selected.

RESULT:

Thus the Transaction control statements are known and used.

EX.NO : 11
DATA CONTROL LANGUAGE (DCL)
DATE :

AIM:
To verify the usage of data using data control commands.

DESCRIPTION;

Data Control Language provide users with privilege commands. The database objects
(table, view etc) of a user can’t be accessed by another user without the permission of the owner
user. The owner can allow other user to access his objects as per his direction. The permission
given by a user (owner) to another is called a privilege.

The data control commands are:


1. GRANT : this command is used to create users and grant access to the
database.
2. REVOKE: this command is used to revoke the granted permission given by
the grantor.
There are two types of privileges used :
System privilege and
Object privilege.
The system privilege are create table, create view, create procedure, alter table, alter view,…
The object privileges are insert, update, delete, select,….

CREATE USER:
SYNTAX:
CREATE USER < user_name> IDENTIFIED BY password;

51
GRANT:
SYNTAX:
GRANT system privilege TO user;
GRANT object privilege [,object privilege] ON object to user [WITH GRANT
OPTION];

WITH GRANT OPTION this option enables the grantee( to whom the privilege is granted)
to grant the same privilege to another user.

REVOKE:
SYNTAX:
REVOKE ALL/object privilege [,object privilege] ON object_name FROM user;

ALL  specifies all object privileges

EXAMPLES:

1. SYSTEM PRIVILIGES:

CREATE USER:
CREATE USER scott IDENTIFIED BY tiger;
User created.

GRANT:
SQL> grant create table to it5;
Grant succeeded.

SQL> create user it100 identified by deepa;


User created.

SQL> grant all privilege to it5;


Grant succeeded.

REVOKE:
SQL> revoke create table from it5;
Revoke succeeded.

SQL> revoke all privilege from it5;


Revoke succeeded.

OBJECT PRIVILEGES:

GRANT:

52
SQL> grant select on loan to it1;
Grant succeeded.

SQL> grant update on loan to it3;


Grant succeeded.

SQL> grant delete on loan to it3;


Grant succeeded.

REVOKE:
SQL> revoke select on loan from it1;
Revoke succeeded.

SQL> revoke update on loan from it3;


Revoke succeeded.

SQL> revoke delete on loan from it3;

Revoke succeeded.

RESULT:
Thus the DCL commands are executed.

53
EX.NO : 12
SIMPLE PL/SQL PROGRAMS
DATE :

AIM :
To write and Execute Simple PL/SQL Programs.

PL/SQL BLOCK STRUCTURE:

DECLARE:
Declarations of memory variables used later.
BEGIN:
SQL executable statements for manipulating table data.
EXCEPTIONS:
SQL and/or PL/SQL code to handle errors that may crop up
During the execution of the above code block.
END;

1. Conditional Control:
A sequence of statements can be executed based on some condition using IF.
Syntax:
If<condition> then <Action>
Else <Action>
End if;
2. Iterative Control:
A sequence of statements can be executed any number of times using loop
constructs.

a) Simple loop
Syntax:
Loop
Statements;
End loop;

b) While loop

Syntax:
While<condition>
Loop
Statements;
End loop;

54
c) For loop
Syntax:
For counter in[reverse] lower bound .. upper bound
Loop
statements
End loop;

PL/SQL PROGRAMS:
1. Write a pl/sql block code to add the two numbers.

SQL> set serveroutput on


SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:=a+b;
9 dbms_output.put_line('sum of '||a||' and '||b||' is :'||c);
10 end;
11 /
PL/SQL procedure successfully completed.

OUTPUT:
Enter value for a: 12
old 6: a:=&a;
new 6: a:=12;
Enter value for b: 23
old 7: b:=&b;
new 7: b:=23;
sum of 12 and 23 is :35

2. Write a pl/sql block code to find the largest of three numbers.

SQL> set serveroutput on


SQL> declare
a number;
b number;
c number;
begin
dbms_output.put_line('enter a');
a:=&a;
dbms_output.put_line('enter b');

55
b:=&b;
dbms_output.put_line('enter c');
c:=&c;
if(a>b)and(a>c)then
dbms_output.put_line('A is maximum');
elsif(b>a)and(b>c)then
dbms_output.put_line('B is maximum');
else
dbms_output.put_line('C is maximum');
end if;
end;
/
PL/SQL procedure successfully completed.

OUTPUT:

Enter value for a: 12


old 8: a:=&a;
new 8: a:=12;
Enter value for b: 45
old 10: b:=&b;
new 10: b:=45;
Enter value for c: 11
old 12: c:=&c;
new 12: c:=11;
enter a
enter b
enter c
B is maximum

3. Write a pl/sql block code to reverse the given number.

declare
b varchar2(10) := '&b';
c varchar2(10);
l number(2);
i number(2);
g number(2);
d varchar2(10);
begin
l:=length(b);
g:=l;
for i in 1..l
loop
c:=substr(b,g,1);
g := g - 1;

56
d := d || c;
end loop;
dbms_output.put_line('revised string is');
dbms_output.put_line(d);
end;
PL/SQL procedure successfully completed.

SQL> /
Enter value for b:database
old 2: b varchar(10):= ‘&b’;
new 2: b varchar2(10):= ‘database’;
reversed string is
esabatad

4. Write a pl/sql block code to find the sum 100 numbers.


SQL>declare
a number;
s1 number default 0;
begin
a:=1;
loop
s1:=s1+a;
exit when (a=100);
a:=a+1;
end loop;
dbms_output.put_line(‘sum bt 1 to 100 is ‘||s1);
end;
/
PL/SQL procedure successfully completed.

OUTPUT:
sum bt 1 to 100 is 5050

5. Write a pl/sql block code to find the sum of odd number using user i/p.

SQl> declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
for n in 1..endvalue

57
loop
if mod(n,2)=1
then
sum1:=sum1+n;
end if;
end loop;
dbms_output.put_line('sum = '||sum1);
end;
/
PL/SQL procedure successfully completed.

OUTPUT:

Enter value for endvalue: 5


old 6: endvalue:=&endvalue;
new 6: endvalue:=5;
sum = 9

.
6. Write a pl/sql block code to find the sum of odd number using while loop.

SQL> declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
while(n<endvalue)
loop
sum1:=sum1+n;
n:=n+2;
end loop;
dbms_output.put_line('sum of odd numbers bt 1 and '||endvalue||' is '||sum1);
end;
/
PL/SQL procedure successfully completed.

OUTPUT:

Enter value for endvalue: 5


old 6: endvalue:=&endvalue;
new 6: endvalue:=5;
sum of odd numbers bt 1 and 5 is 4

7. Write a pl/sql block code to find the Fibonacci series.

58
SQL> declare
2 a number(3);
3 b number(3);
4 c number(3);
5 n number(3):=&n;
6 negative exception;
7 begin
8 if n<2 then
9 raise negative;
10 end if;
11 a:=0;
12 b:=1;
13 dbms_output.put_line(‘Fibonacci series is’);
14 dbms_output.put_line(a);
15 dbms_output.put_line(b);
16 for i in 3..n
17 loop
18 c:=a+b;
19 dbms_output.put_line(c);
20 a:=b;
21 b:=c;
22 end loop;
23 exception
24 when negative then
25 dbms_output.put_line(‘n should be greater than l’);
26 end;
SQL> /
Enter value for n:10
old 5: n number(3):=&n;
new 5:n number(3):=10;
Fibonacci
0
1
1
2
3
5
8
13
21
34
PL/SQL procedure successfully completed

8. Write a pl/sql block code to find the net salary.


SQL> declare
2 ename varchar2(15);

59
3 basic number;
4 da number;
5 hra number;
6 pf number;
7 netsalary number;
8 begin
9 ename:=&ename;
10 basic:=&basic;
11 da:=basic*(41/100);
12 hra:=basic*(15/100);
13 if(basic<3000)
14 then
15 pf:=basic*(5/100);
16 elsif(basic>=3000 and basic<=5000)
17 then
18 pf:=basic*(8/100);
19 else
20 pf:=basic*(10/100);
21 end if;
22 netsalary:=basic+da+hra+pf;
23 dbms_output.put_line('employee name:'||ename);
24 dbms_output.put_line('providend fund:'||pf);
25 dbms_output.put_line('net salary:'||netsalary);
26 end;
27 /
PL/SQL procedure successfully completed.

OUTPUT:
Enter value for ename: 'sudha'
old 9: ename:=&ename;
new 9: ename:='sudha';
Enter value for basic: 100000
old 10: basic:=&basic;
new 10: basic:=100000;
employee name:sudha
providend fund:10000
net salary:166000

9. EXAMPLE FOR LOOP


SQL> declare
2 begin
3 for i in 1..10
4 loop
5 dbms_output.put_line(to_char(i));
6 end loop;
7 end;

60
8 /
PL/SQL procedure successfully completed.

OUTPUT:
1
2
3
4
5
6
7
8
9
10

10. Example for while

SQL> declare
2 i number:=0;
3 j number:=0;
4 begin
5 while i<=100 loop
6 j:=j+1;
7 i:=i+2;
8 end loop;
9 dbms_output.put_line(to_char(i));
10 end;
11 /

PL/SQL procedure successfully completed.

OUTPUT:
102

11. EXAMPLE FOR LOOP USING EXIT

SQL> declare
2 a number:=100;
3 begin
4 loop
5 a:=a+25;

61
6 exit when a=250;
7 end loop;
8 dbms_output.put_line(to_char(a));
9 end;
10 /
PL/SQL procedure successfully completed.

OUTPUT:

250

12. Write a pl/sql block code to find the given is prime or not.

SQL> declare
2 no number(3):=&no;
3 a number(4);
4 b number(2);
5 begin
6 for i in 2..no-1
7 loop
8 a:=no MOD i;
9 if a=0
10 then
11 GOTO out;
12 end if;
13 end loop;
14 <<out>>
15 if a=1
16 then
17 dbms_output.put_line(no||' is a prime');
18 else
19 dbms_output.put_line(no||' is not prime');
20 end if;
21 end;
22 /
PL/SQL procedure successfully completed.

OUTPUT:

Enter value for no: 7


old 2: no number(3):=&no;
new 2: no number(3):=7;
7 is a prime

62
13. Write a pl/sql code block to calculate the area of circle for a value of radius varying
from 3 to 7. Store the radius and the corresponding values of calculated area in an
empty table named area, consisting of two columns radius and area

SQL> create table areas ( radius number(3), area number(7,2));


Table creted.

SQL> declare
2 pi constant number(4,2):=3.14;
3 radius number(5);
4 area number(14,2);
5 begin
6 radius:=3;
7 while radius<=7
8 loop
9 area:=pi*power(radius,2);
10 insert into areas values(radius,area);
11 radius:=radius+1;
12 end loop;
13 end;
14 /
PL/SQL procedure successfully completed.

OUTPUT:

SQL> select * from areas;

RADIUS AREA
---------- ----------
3 28.26
4 50.24
5 78.5
6 113.04
7 153.86

RESULT:

Thus the simple PL/SQL programs are executed successfully.

63
EX.NO : 13
PL/SQL PROGRAM USING CURSORS
DATE :

AIM:
To write a PL/SQL program using cursor.

DESCRPTION:
Oracle allocated an area of memory known as context area for the processing of
SQL statement. The context area contains information necessary to complete the processing,
including the number of rows processed by the statement and a pointer to the parsed
representation of the statement.
A cursor is pointer to the context area. Through the cursor, a PL/SQL program can
control the context area and what happens to it as the statement is processed.
The cursor can be classified into
Implicit cursor
Explicit cursor
Cursors are declared implicitly by PL/SQL for all SQL data manipulation statements,
including the select statements that return one row.

If a query returns more than one row, explicit cursor should be used to access the rows in
the context area.

CURSOR MANAGEMENT:

The steps involved in declaring a cursor and manipulating data in Active Dataset.:
1. Declare a cursor that specifies the SQL Statement that it to be processed.
Syntax:
cursor cursorname is SQL statement;
Example:
Declare Cursor c_emp is
Select emp_code, salary from employee Where depm=3;
2. OPENING A CURSOR: The cursor is initialized with open statement. This defines a
private SQ private SQL area, execute the query associated with the cursor, populates the active
Data Set Data Set row pointer to first record.
Syntax:
open cursor_name;
Example:
Open c_emp;

3. FETCHING A RECORD FROM CURSOR: The fetch statement retrieves the current
row and advances the cursor to the next row. It’s executed repeatedly until all rows
have been retrieved.
Syntax: fetch cursorname into variable1,variable2,------
Example:
fetch c_emp into str_emp_code,num_salary;

64
The % type attribute is used in the declaration of a variable when attributes must be picked
from a table.
The current program will result into a n indefinite loop as there is no exit provided
from the loop. The exit can be provided using explicit cursor variables.

4. CLOSING A CURSOR: The close statement disables the cursor and active set become
undefined. It will release the memory occupied by cursor and it’s data set.
Syntax:
close cursorname;

EXAMPLE:
declare
cursor c_emp is
select emp_code ,salary from employee
where deptno=20;
str_emp_code employee.emp_code %type;
num_salary employee.salary %type;
begin
open c_emp;
loop
fetch c_emp into str_emp_code,num_salary;
end loop;
end;

SOME ATTRIBUTES:
1. %ROWCOUNT:
Return the no of rows fetched from the active set.It is set to zero when the cursor
is opened.
Syntax: cursorname %rowcount;

2.%NOTFOUND:
Evaluates to true if the last fetch has field because no more rows were available
or to false, if the fetch returned a row.

Syntax:cursorname%notfound;
3.%FOUND:
Is the logical opposite of %notfound. It evaluates to true, if the last fetch succeeded
because a row was available or to false, if the last fetch field because no more rows
were available.
Syntax: cursorname%found;

4. %ISOPEN:
Evaluate to true, if an explicit cursor is open % on to false if it is closed.
Syntax: cursorname %isopen;

65
PROGRAM:

1.Write a pl/sql block code for finding the salary of each employee using cursor.

TABLE CREATION

SQL> create table salary(empno number(3) primary key,empname varchar2(7),desg


varchar2(10),dept varchar(4),basic number(5),da number(4),dedect number(5));

Table created.

INSERTING VALUES

SQL> insert into salary values(101,'Nithya','Lecturer','IT',8000,5,1000);


1 row created.

SQL> insert into salary values(102,'Sham','Lecturer','ECE',7900,5,2000);


1 row created.

SQL> insert into salary values(103,'Priya','Lecturer','CT',8500,4,1000);


1 row created.

SQL> insert into salary values(104,'Sakthi','Labassi','EEE',6000,5,2000);


1 row created.

SQL> insert into salary values(105,'Raji','Labassi','E&I',6200,3,1000);


1 row created.

SQL> select * from salary;

EMPNO EMPNAME DESG DEPT BASIC DA DEDUCT


-------- ---------------- ----------- ---------- --------- -------- ----------
101 Nithya Lecturer IT 8000 5 1000
102 Sham Lecturer ECE 7900 5 2000
103 Priya Lecturer CT 8500 4 2000
104 Sakthi Labassi EEE 6000 5 2000
105 Raji Labassi E&I 6200 3 1000

SQL> set serveroutput on


1 declare
2 eno number(4);
3 ename varchar2(7);
4 netsal number(8);
5 cursor cus_salary is select empno, empname, basic+da*basic/100-dedect from salary;
6 begin

66
7 dbms_output.put_line('empno'||'name'||'net salary');
8 dbms_output.put_line('.............................');
9 open cus_salary;
10 loop
11 fetch cus_salary into eno,ename,netsal;
12 exit when cus_salary%notfound;
13 dbms_output.put_line(eno||' '||ename||' '||netsal);
14 end loop;
15 close cus_salary;
16* end;

SQL> /

PL/SQL procedure successfully completed.

Empno name netsalary


................. ..................... --------------------
101 Nithya 7400
102 Sham 6295
103 Priya 7840
104 Sakthi 4300
102 Raji 5386

2. Display the names ,department number ,salary of the first 10 employees


getting the highest salary.

Declare
cursor c_emp is
select ename,deptno,salary .from employee
order by salary disc
str_name employee.name%type;
num_deptno employee.deptno%type;
num_salary employee.salary%type;
begin
open c_emp;
dbms_output.put_line(‘NAME DEPARTMENT SALARY’);
dbms_output.put_line(‘----------------------------------------------------‘);
loop
fetch c_emp into str_name,num_deptno,num_salary;
dbms_output.put_lines(str_name||’’||num_deptno||’
’ ||num_salary);
exit when c_emp %rowcount=10;
end loop;
close c_emp;
end

67
SQL>/
ENAME DEPARTMENT SALARY
----------- --------------------------- -------------
surya 20 20000
malathy 18 15000
ivan 20 10000
sonia 20 10000
pradeep 18 7000
PL/SQL procedure successfully completed.

SQL>DECLARE
2 dacno depositer.account_number%type;
3 aacno account.account_number%type;
4 bal account.balance%type;
5 cname depositer.customer_name%type;
6 CURSOR c is SELECT customer_name,account_number FROM depositer;
7 CURSOR c1 is SELECT balance,account_number FROM account;
8 BEGIN
9 OPEN c;
10 OPEN c1;
11 FETCH c INTO cname,dacno;
12 FETCH c1 INTO bal,aacno;
13 LOOP
14 LOOP
15 IF (dacno=aacno) THEN
16 dbms_output.put_line('CUSTOMER NAME');
17 dbms_output.put_line(cname);
18 dbms_output.put_line('BALANCE');
19 dbms_output.put_line(bal);
20 FETCH c INTO cname,dacno;
21 ELSE
22 FETCH c INTO cname,dacno;
23 END IF;
24 EXIT WHEN c%notfound;
25 END LOOP;
26 CLOSE c;
27 OPEN c;
28 EXIT WHEN c1%notfound;
29 FETCH c1 INTO bal, aacno;
30 END LOOP;
31 CLOSE c;
32 CLOSE c1;
33* END;
/
PL/SQL procedure successfully completed.

68
OUTPUT:

CUSTOMER NAME
Johnson
BALANCE
500
CUSTOMER NAME
Hayes
BALANCE
1600
CUSTOMER NAME
Johnson
BALANCE
900
CUSTOMER NAME
Smith
BALANCE
700
CUSTOMER NAME
Jones
BALANCE
752
CUSTOMER NAME
Lindsay
BALANCE
700
CUSTOMER NAME
Lindsay
BALANCE
700
PL/SQL procedure successfully completed.

RESULT:

Thus the cursor is created, executed and the output is verified.

69
EX.NO : 14
PL/SQL PROGRAM USING FUNCTIONS
DATE :

AIM:
To write and execute program using function.

DESCRIPTION:
Function is a subprogram that computes a value.

SYNTAX:
create [or replace] function <function name> (parameter1,parameter2,……)
return <data type>
is
[constant/variable declaration]
begin
executable statements
return <return values>
exception[exception handling statements]
return <return values>
end;

PROGRAM:

To create a recursive function to find the factorial of a given number using PL/SQL
function.

SQL> CREATE OR REPLACE FUNCTION fact(no number)


2 RETURN number
3 IS
4 a number;
5 BEGIN
6 IF(no=0 or no=1)
7 THEN
8 RETURN(1);
9 ELSE
10 a:=no*fact(no-1);
11 RETURN(a);
12 END IF;
13 END;
14 /

Function created.

OUTPUT:

70
SQL> select fact (5) from dual;

FACT (5)
-------------
120
(OR)
SQL>create or replace function fact(n number)return number is
2 begin
3 if n=1 then
4 return 1;
5 else
6 return n* fac(n-1);
7 end if;
8 end fac;
SQL>/
Function created.

SQL>declare
2 n number(4):=&n;
3 n1 number (8);
4 begin
5 n1:=fac(n);
6 dbms_output.put_line(‘factorial of’|| n ||’is’|| n1);
7 end;
8
SQL>/
Enter the value for n:6
Old 2: n number(4):=&n;
New 2:n number(4):=6;
Factorial of 6 is 720
PL/SQL Procedure successfully completed.

2. FIND THE NUMBER OF CUSTOMERS AT A GIVEN BRANCH.

SQL > create or replace function counting(bn varchar2)


2 return number is
3 a number;
4 cursor c is select count(accountnumber) from account where branchname=bn;
5 begin
6 open c;
7 fetch c into a;
8 return(a);
9 close c;
10 end;
/

71
Function created.

OUTPUT:

SQL> select counting('brighton') from dual;

COUNTING('BRIGHTON')
--------------------
2

SQL> select counting('perryridge') from dual;

COUNTING('PERRYRIDGE')
----------------------
1

RESULT:

Thus the PL/SQL program using function was executed successfully.

72
EX.NO : 15
PL/SQL PROGRAM USING PROCEDURE
DATE :

AIM:
To write and execute program using procedure.

DESCRIPTION:
A procedure is a subprogram that performs a specific action.

SYNTAX:
CREATE [OR REPLACE] procedure procedure name [(parameter1,parameter2,…)]
IS
[CONSTANT/ variable declarations]
BEGIN
Exception statements
[Exception handling statements]
End [procedure name];

PROGRAM:
1. Write a pl/sql block code, if the balance is less than 5000 print the min balance
otherwise update the account table with the given interest.

SQL> CREATE OR REPLACE PROCEDURE interest(ir1 real,ir2 real)


2 IS old_bal number(9);
3 c_id account.account_number%type;
4 CURSOR a IS SELECT balance,account_number FROM account;
5 BEGIN
6 OPEN a;
7 LOOP
8 FETCH a INTO old_bal,c_id;
9 EXIT WHEN a% NOTFOUND;
10 IF old_bal<5000
11 THEN
12 DBMS_OUTPUT.PUT_LINE('BAL LESS THAN MIN '||c_id);
13 ELSIF old_bal BETWEEN 5000 AND 10000
14 THEN
15 UPDATE account SET balance=old_bal+(old_bal*ir1) where account_number=c_id;
16 ELSE
17 UPDATE account SET balance=old_bal+(old_bal*ir2) where account_number=c_id;
18 END IF;
19 END LOOP;
20 CLOSE a;
21* END;

SQL> /

73
Procedure created.

SQL> select * from account;

ACCOUNT_NU BRANCH_NAM BALANCE


---------- ---------- ----------
A-101 Downtown 2846
A-102 Pbridge 9094
A-201 Brighton 5108
A-215 Mianus 3982
A-217 Brighton 4272
A-222 Redwood 3982
A-305 RoundHill 7949
7 rows selected.

SQL> set serverout on;


SQL> call interest(.05,.1);
BAL LESS THAN MIN A-101
BAL LESS THAN MIN A-215
BAL LESS THAN MIN A-217
BAL LESS THAN MIN A-222

Call completed.

SQL> select * from account;

ACCOUNT_NU BRANCH_NAM BALANCE


---------- ---------- ----------
A-101 Downtown 2846
A-102 Pbridge 9549
A-201 Brighton 5363
A-215 Mianus 3982
A-217 Brighton 4272
A-222 Redwood 3982
A-305 RoundHill 8346

7 rows selected.

RESULT:

Thus the procedure is created, executed and the output is verified.

74
EX.NO : 16
TRIGGER
DATE :

AIM:
To write and execute the program to verify the use of triggers.

DESCRIPTION:
Trigger is a stored procedure that is fired when an insert, update or delete
statement is issued against the associated table.

SYNTAX:

Create Or Replace Trigger <Trigger Name> [Before /After] [Insert /update/delete] on


<Tablename> [For Each statement/for each row] [ When <Condition>]
DECLARE
Declaration statements;
BEGIN
Executable statements;
EXCEPTION
Exception handling statements;
END;

EXAMPLES:
1.
SQL> create table stu(name varchar2(15),roll_no number(5) primary key,
sem varchar2(5),dep varchar2(5));
Table created.

SQL> create table stu1 as(select * from stu);


Table created.

SQL>1 create or replace trigger database after insert on stu


2 for each row
3 begin
4 insert into stu1 values(:new.name,:new.roll_no,:new.sem,:new.dep);
5 DBMS_OUTPUT.PUT_LINE('STU1 ALSO UPDATED BY TRIGGER');
6 end;
Trigger created.

SQL> insert into stu values('&name',&roll_no,'&sem','&dep');


Enter value for name: Latha
Enter value for roll_no: 27
Enter value for sem: fifth
Enter value for dep: IT
old 1: insert into stu values('&name',&roll_no,'&sem','&dep')

75
new 1: insert into stu values('Latha',27,'fifth',' IT')
1 row created.

SQL> /
Enter value for name: Revathi
Enter value for roll_no: 43
Enter value for sem: sixth
Enter value for dep: CSE
old 1: insert into stu values('&name',&roll_no,'&sem','&dep')
new 1: insert into stu values('Revathi',43,'sixth','CSE')
1 row created.

SQL> select * from stu;

NAME ROLL_NO SEM DEP


-------- ------------- ----- -----
Latha 27 fifth IT
Revathi 43 sixth CSE
Mahe 28 Sixth EEE
Moni 32 third ECE

SQL> select * from stu1;

NAME ROLL_NO SEM DEP


-------- ------------- ----- -----
Latha 27 fifth IT
Revathi 43 sixth CSE
Mahe 28 Sixth EEE
Moni 32 third ECE

SQL> create or replace trigger database before delete on stu


2 for each row
3 begin
4 delete from stu1 where stu1.roll_no=:old.roll_no;
5 DBMS_OUTPUT.PUT_LINE('STU1 ALSO UPDATED BY TRIGGER');
6 end;
7 /
Trigger created.

SQL> delete from stu where roll_no=43;


1 row deleted.

76
SQL> select * from stu;

NAME ROLL_NO SEM DEP


-------- ------------- ----- -----
Latha 27 fifth IT
Mahe 28 Sixth EEE
Moni 32 third ECE

SQL> select * from stu1;

NAME ROLL_NO SEM DEP


-------- ------------- ----- -----
Latha 27 fifth IT
Mahe 28 Sixth EEE
Moni 32 third ECE

2. To create a trigger for student details.

INPUT VALUES: BEFORE EXECUTING TRIGGERS:

Create First Table:


SQL>create table student(regno number(5),name varchar2(10),dept varchar2(10),percentage
number(10));

Table Created

Insert the required values,

SQL> select *from student;

REGNO NAME DEPT PERCENTAGE


---------- ---------- ---------- ----------
101 aa cse 80
204 cc it 75
103 dd cse 60
304 ff ece 70
4 rows selected

Create Second Table:


SQL>create table bckupstu(regno number(10),name varchar2(10),dept varchar2(10),percentage
number(10));

Table Created

77
SQL>edit trig1.sql;

create or replace trigger t1 after delete on student


for each row
begin
insert into bckupstu values(:old.regno,:old.name,:old.dept,:old.percentage);
end;

SQL>edit trig2.sql;

create or replace trigger t2 after update of regno on student


for each row
begin
insert into bckupstu values(:old.regno,:old.name,:old.dept,:old.percentage);
end;

SQL>edit trig3.sql;

create or replace trigger t3 before insert or update of name on student


for each row
begin
:new.name:=upper(:new.name);
end;

Output Values:
SQL> get trig1.sql;
Trigger Created.

SQL> delete from student where regno=204;


1 row deleted.

SQL> select *from student;

REGNO NAME DEPT PERCENTAGE


---------- ------------------ ----------
101 aa cse 80
103 dd cse 60
304 ff ece 70

SQL> select *from bckupstu;

REGNO NAME DEPT PERCENTAGE


---------- ---------- ---------- ----------
204 cc it 75

78
1 row selected

SQL> get trig2.sql;


Trigger Created.
SQL> update student set regno=404 where regno=304;

1 row updated.

SQL> select *from student;

REGNO NAME DEPT PERCENTAGE


---------- ---------- ---------- ----------
101 aa cse 80
204 cc it 75
103 dd cse 60
404 ff ece 70
SQL> select *from bckupstu;

REGNO NAME DEPT PERCENTAGE


---------- ---------- ---------- ----------
204 cc it 75
304 ff ece 70

SQL> get t3.sql;


Trigger Created.

SQL> insert into student values(405,'ee','ece',65);

1 row created.

SQL> select *from student;

REGNO NAME DEPT PERCENTAGE


---------- ---------- ---------- ----------
101 aa cse 80
103 dd cse 60
404 ff ece 70
405 EE ece 65

SQL> update student set name='gg' where name ='aa';

1 row updated.

SQL> select *from student;

79
REGNO NAME DEPT PERCENTAGE
---------- ---------- ---------- ----------
101 GG cse 80
103 dd cse 60
304 ff ece 70
405 EE ece 65

4 rows selected

2. SQL> create table orders30(order_id number(5),quantity number(4),cost_per_item


number(6,2),total_cost number(8,2));

Table created.

SQL> create table orders_audit(order_id number,quantity_before number,quantity_after


number,username varchar2(20));

Table created.

SQL> insert into orders30(order_id,quantity,cost_per_item)


values(&order_id,&quantity,&cost_per_item);
Enter value for order_id: 100
Enter value for quantity: 5
Enter value for cost_per_item: 10
old 1: insert into orders30(order_id,quantity,cost_per_item)
values(&order_id,&quantity,&cost_per_
new 1: insert into orders30(order_id,quantity,cost_per_item) values(100,5,10)

1 row created.

SQL> /
Enter value for order_id: 101
Enter value for quantity: 4
Enter value for cost_per_item: 20
old 1: insert into orders30(order_id,quantity,cost_per_item)
values(&order_id,&quantity,&cost_per_
new 1: insert into orders30(order_id,quantity,cost_per_item) values(101,4,20)

1 row created.
SQL> /
Enter value for order_id: 102
Enter value for quantity: 5
Enter value for cost_per_item: 30
old 1: insert into orders30(order_id,quantity,cost_per_item)
values(&order_id,&quantity,&cost_per_

80
new 1: insert into orders30(order_id,quantity,cost_per_item) values(102,5,30)

1 row created.

SQL> create or replace trigger orders_after_update


2 AFTER UPDATE
3 ON orders30
4 for each row
5 declare
6 v_username varchar2(10);
7 begin
8 select user into v_username
9 from dual;
10 insert into orders_audit
11 (order_id,
12 quantity_before,
13 quantity_after,
14 username)
15 values
16 (:new.order_id,
17 :old.quantity,
18 :new.quantity,
19 v_username);
20 end;
21 /

Trigger created.

SQL> update orders30 set quantity=25 where order_id=101;

1 row updated.

SQL> select *from orders_audit;

ORDER_ID QUANTITY_BEFORE QUANTITY_AFTER USERNAME


---------- --------------- -------------- ---------------------------------------------------------
101 4 25 CSE3090

3. Create a trigger to delete an account from depositer when deleted in account.


PROGRAM:

SQL> create or replace trigger datbase before delete on account


2 for each row

81
3 begin
4 delete from depositer where depositer.accountnumber=:old.accountnumber;
5 end;
6 /
Trigger created.

OUTPUT:
SQL> delete from account where accountnumber='A-101';
1 row deleted.

SQL> select * from account;

ACCOUNTNUMBER BRANCHNAME BALANCE


-------------------- -------------------- ----------
A-215 mianus 1389.15
A-102 perryridge 396
A-305 roundhill 346.5
A-201 brighton 1389.15
A-222 redwood 1389.15
A-217 brighton 1389.15

6 rows selected.

SQL> select * from depositer;

CUSTOMERNAME ACCOUNTNUMBER
-------------------- --------------------
smith A-215
hayes A-102
turner A-305
johnson A-201
jones A-217
lindsay A-222

6 rows selected.

RESULT:

Thus the trigger is created, executed and output is verified.

82
EX.NO : 17
Database Design and implementation (Mini Project)
DATE :

AIM
To implement Library Management System by using Visual Basic as front end & Oracle
as back end.

ABSTRACT
In this project we have used visual basic as front end and oracle as back end. Visual Basic
is a flexible and user friendly interface and it can also easily interact with the back end. This
project stores the details of Books stored in an Library.
By using this project, the details of a Book such as Book Name, Book Code, Author can
be stored. We can update the records ,which exists in the database easily and quickly.
Books can be reserved by using this Project.
Also for a particular Author the books written by them can be displayed .We can update
the records into the database. We can also view the records, which already exist in the database
easily and quickly.

PROGRAM (FRONT END):

Private Sub Command1_Click()


If Text1.Text = "" And Text2.Text = "" Then
Frame1.Visible = True
End If
End Sub

Private Sub Command2_Click()


Unload Me
End Sub

Private Sub Command3_Click()


Form3.Show
End Sub

Private Sub Command4_Click()


Form2.Show
End Sub

Private Sub Command5_Click()


Form4.Show
End Sub

Private Sub Command1_Click()

83
Dim a As String
rs.Index = "Key"
a = Val(InputBox("Enter Book Code"))
rs.Seek "=", Val(a)
If rs.NoMatch = True Then
MsgBox "Invalid Code"
Else
Text1.Text = rs.Fields("Book Name")
Text2.Text = rs.Fields("Book Code")
Text3.Text = rs.Fields("Author")
End If
End Sub

Private Sub Command2_Click()


Data1.Recordset.AddNew
End Sub

Private Sub Command3_Click()


Data1.Recordset.MoveNext
If Data1.Recordset.EOF Then
Data1.Recordset.MoveFirst
End If
End Sub

Private Sub Command4_Click()


Data1.Recordset.MovePrevious
If Data1.Recordset.BOF Then
Data1Recordset.MoveLast
End If
End Sub

Private Sub Command5_Click()


Data1.Recordset.Update
MsgBox "Saved"
End Sub

Private Sub Command6_Click()


Form1.Show
Unload Me
End Sub

Private Sub Command1_Click()


Dim str As String
rs.Index = "key"
str = Val(InputBox("Enter the code"))
rs.Seek "=", Val(str)

84
If rs.NoMatch = True Then
MsgBox "Invalid code"
Else
Text1.Text = rs.Fields("Member Name")
Text2.Text = rs.Fields("MemberCode")
Text3.Text = rs.Fields("Age")
End If
End Sub

Private Sub Command2_Click()


Data1.Recordset.AddNew
End Sub

Private Sub Command3_Click()


Data1.Recordset.MoveNext
If Data1.Recordset.EOF Then
Data1.Recordset.MoveFirst
End If
End Sub

Private Sub Command4_Click()


Data1.Recordset.MovePrevious
If Data1.Recordset.BOF Then
Data1Recordset.MoveLast
End If
End Sub

Private Sub Command5_Click()


Data1.Recordset.Update
MsgBox "Saved"
End Sub

Private Sub Command6_Click()


Form1.Show
Unload Me
End Sub

Private Sub Command1_Click()


Form1.Show
Unload Me
End Sub

Private Sub Command2_Click()


Data1.Recordset.AddNew
End Sub
Private Sub Command3_Click()

85
Dim str As String
rs.Index = "Key"
str = Val(InputBox("Enter Member Code"))
rs.Seek "=", Val(str)
If rs.NoMatch = True Then
MsgBox "Invalid Code"
Else
Text1.Text = rs.Fields("Member Name")
Text2.Text = rs.Fields("Member Code")
Text3.Text = rs.Fields("Book Name")
Text4.Text = rs.Fields("Book Code")
Text5.Text = rs.Fields("DOI")
Text6.Text = rs.Fields("DOR")
End If
End Sub

Private Sub Command4_Click()


Data1.Recordset.MoveNext
If Data1.Recordset.EOF Then
Data1.Recordset.MoveFirst
End If
End Sub

Private Sub Command5_Click()


MsgBox "Saved"
End Sub

Private Sub Command6_Click()


Data1.Recordset.MovePrevious
If Data1.Recordset.BOF Then
Data1Recordset.MoveLast
End If
End Sub

86
OUTPUT

RESULT:

Thus the implementation of Library Management Systems is done successfully using


Visual Basic as Front end and Oracle as Back end.

87

You might also like