You are on page 1of 141

CMC Limited

1
CONFIDENTIAL

CONTENTS
Introduction to DBMS CODD rules SQL * PLUS COMMANDS SQL

Sub Languages Operators Functions Constraints Group by, order by and having clauses Data base objects Data dictionary in Oracle Creating users Joins Sub queries

PL/SQL
ANONYMOUS BLOCKS Cursors Triggers Procedures Functions Packages
2
CONFIDENTIAL

CMC Limited

Day wise schedule


Day 1 Introduction to DBMS, CODD rules, SQL* PLUS Commands, Sub languages of SQL Operators, functions, group by, order by and having clauses Constraints, data base objects Data base objects, PL/SQL anonymous blocks Cursors, functions, procedures, packages and triggers

Day 2

Day 3 Day 4 Day 5

CMC Limited

3
CONFIDENTIAL

BASICS
Data
It is a collection of raw facts and figures

In order to use the data, the data needs to be preserved or stored in a definite location for every piece of data has an objective and a purpose Storage areas
Pen drive Floppy CD ROM drive Manual storage

Data base
Place holder for storing the data to overcome the flaws with respect to data storage in the above mentioned areas In order to store data in a data base, we need to define a data structure

Files Tables

CMC Limited

4
CONFIDENTIAL

Disadvantages with file systems


Data redundancy

Data is in secured
Data base will be dependent on the programming logic

Hardware cost was intensifying


Concurrent access anamolies

CMC Limited

5
CONFIDENTIAL

Advantages with tables


In a table, rows need not be stored in a sequential manner In a table, the data in the cells is atomic In tables, data redundancy can be minimized or controlled by imposing certain constraints like primary key The usage of tables in a data base has been standardized as relational data base management system

CMC Limited

6
CONFIDENTIAL

Codd rules
In order to qualify a data base as RDBMS it needs to satisfy or comply with come standards referred to as codd rules No of codd rules : 12

CMC Limited

7
CONFIDENTIAL

12 Rules of Codd
1. 2. 3. 4. 5. 6. Information rule Guaranteed access rule Systematic representation of null values Active online catalog based on relational model Data sub language rule High level insert,update and delete

7.
8. 9.

View updation rule


Physical data independence Logical data independence

10. Data integrity rule

11. Distribution rule


12. No sub version rule

CMC Limited

8
CONFIDENTIAL

Information rule
Each and every data item must be physically represented or stored in the form of rows and columns in a table

CMC Limited

9
CONFIDENTIAL

Guaranteed access rule


Each and every data item must be logically represented as a combination of a column name, table name and a primary key Conclusions
In order to resolve the ambiguity in column names, we have to use the table name in conjunction with a column name Primary key has to be imposed on atleast 1 column in every table for ensuring dependency between non key attributes and the primary key column so that the entire row in that table can be uniquely identified

CMC Limited

10
CONFIDENTIAL

Systematic representation of null values


A null value is a value which signifies a missing or in appropriate information in a column of a table Null values are independent of data type 1 null value is not equal to another null value Null value enhance the memory management in oracle It has to be a default value to be supplied by the system in a table in case a missing information has been encountered
CMC Limited
11
CONFIDENTIAL

Active online catalog based on relational model


Data dictionary has to be mandatorily defined in any propretitory data base package Data dictionary is used for capturing the information with respect to data base objects Data dictionary accommodates meta data

CMC Limited

12
CONFIDENTIAL

Views of data dictionary


All_objects User_objects All_views User_views All_sequences User_sequences All_triggers User_triggers

All_synonyms
User_synonyms

CMC Limited

13
CONFIDENTIAL

High level insert, update and delete


Insert, update and delete are row wise operations and not column wise

CMC Limited

14
CONFIDENTIAL

Data sub language rule


Any DBMS is supposed to implement or comply at least one of the following sub languages to store, use and manipulate data in a data base
Data definition language Data manipulation language Transaction control language DDL + DML + TCL =

SQL
15

CMC Limited

CONFIDENTIAL

View updating rule


All the views that are theoretically updatable must be practically updated by the system
View is a virtual table Any up dations made on a view must be reflected on the base table and vice versa

CMC Limited

16
CONFIDENTIAL

Physical data independence


Data base must be independent of programming logic ie changes made to a data base must not effect the logic in a program

CMC Limited

17
CONFIDENTIAL

Logical data independence Application logic must be independent of data base ie changes made to a application logic must not effect the data base

CMC Limited

18
CONFIDENTIAL

Distribution rule
Data base must be distributed on a network

CMC Limited

19
CONFIDENTIAL

Data integrity rule


Primary key Unique Check

Default
Foreign key

Not null
20
CONFIDENTIAL

CMC Limited

SQL * PLUS COMMANDS(ORACLE Proprietary)


Ch /<old name> /<new name>
Changes the old table name to new table name Clears the screen contents Display the previous SQL command Executes the previous SQL command

Cl scr L

RUN
Display and execute the previous SQL command

I WHERE EMPNO = 7369;


Adds a new line to the previous SQL command

Save <file name>


Creates a file for the previous SQL command Extension is .SQL Path : D:\oracle\product\10.2.0\db_1\BIN

Get <file name>


Display the contents of the file created

CMC Limited

21
CONFIDENTIAL

CMC Limited

22
CONFIDENTIAL

DESCRIPTION
SQL is a non procedural query language devised by IBM in the year 1970 for implementing their DB product by name DB2
Using SQL queries, we cannot create a procedure or a function They are not storable in a data dictionary

SQL is a universally acceptable standard for implementing any proprietary data base
Oracle SQL server SYBASE FOX PRO MY SQL

CMC Limited

23
CONFIDENTIAL

SUB LANGUAGES
DATA definition language(defines a data structure)
Create Alter Truncate Drop

Data manipulation language(defines the way of maniuplating data in a structure)


Insert Update Delete Select

Transaction control language


Grant Revoke

CMC Limited

24
CONFIDENTIAL

Create
Create table <table name> (<col> <data type>)

Eg
create table stud(sno number, sname char(10));

Maximum no of characters for a table name is 30

CMC Limited

25
CONFIDENTIAL

Alter
Modify the data type of a column

Alter table <table name> modify (<col> <data type>); alter table stud modify(sno varchar2(10));

You can increase the size of the column if the table is empty and containing data and you can decrease the size of the column if the table is empty and the data which was previously inserted is in compliance with the decreased size of the column

Add a column
alter table stud add(city varchar2(10))

Delete a column
alter table stud drop column sname alter table stud drop (sno,age)

Drop multiple columns

Rename a column
alter table stud rename column city to state

Combinations of add and modify


alter table stud modify(state number) add (sno number)

CMC Limited

26
CONFIDENTIAL

Data types
Number([<size>]) Number(precision ,scale) Date Timestamp Char(<size>) Varchar2(<size>) Blob Bfile Clob

CMC Limited

27
CONFIDENTIAL

Inserting data into all the columns in a table


Inserting data into specific columns
Insert into stud values(10,1); insert into stud(sno) values(3) insert into emp1(ename,eno) values('kumar', 1)

Insert

Define insertion order

Insert values into a table at run time


insert into emp1 values(&eno,'&ename');

Insert values into a table at run time for specific columns


insert into stud(sno) values(&sno)

CMC Limited

28
CONFIDENTIAL

Contd
Create table at run time
create table &table_name(&col &data_type, &col1 &data_type1)

Truncate
Used for deleting data from the table Truncate table <table name> Eg

truncate table emp1;

Drop
Drop table <table name>;

CMC Limited

29
CONFIDENTIAL

Update
Syntax
Update <table name> set <colname> = <new value> [where <condition>]; Eg

update emp1 set ename = 'krishna' where ename = 'ravi

Deleting a value from a cell

update emp1 set ename = null where eno = 7

CMC Limited

30
CONFIDENTIAL

Delete Delete from <table name> [where <condition>]; Eg


delete from emp1 where eno = 1

Comparison between truncate and delete


Truncate can never be rolled back Truncate is a table level command Delete can be rolled back Delete is a row level operation

CMC Limited

31
CONFIDENTIAL

Performance issue
Prior to deleting the table structure, the data within the table needs to be truncated for drop only deletes the structure but the data within that structure will still reside in the memory which will go un referenced

CMC Limited

32
CONFIDENTIAL

CMC Limited

33
CONFIDENTIAL

DESCRIPTION
SYNTAX
Select <col names> from <table name> [where <condition>] Eg

Select * from emp; Select sal from emp; Select 1 from emp;

CMC Limited

34
CONFIDENTIAL

Contd..
select empno, job from emp where sal <= 1000; select sal from emp where sal >= 1000 and sal <= 2000

CMC Limited

35
CONFIDENTIAL

Sql operators
BETWEEN <min> and <max>
select sal from emp where sal between 1000 and 2000

Not between <min> and <max> IN


SELECT * FROM EMP WHERE JOB IN('CLERK', 'SALESMAN', 'MANAGER')

NOT IN LIKE
SELECT * FROM EMP WHERE ENAME LIKE 'S% select * from emp where ename like '_M%

DISTINCT
select distinct(job) from emp

Is null
select comm from emp where comm is null /

CMC Limited

36
CONFIDENTIAL

Concatenation operator
select ename || ' is a ' || job || ' whose salary is ' || sal || ' from ' ||deptno from emp Eg
SMITH is a CLERK whose salary is 800 from 20

CMC Limited

37
CONFIDENTIAL

CMC Limited

38
CONFIDENTIAL

DESCRIPTION
A function is a sub program which accepts some arguments and returns a value Categories of functions
System defined functions User defined functions

Calling a function
Select function_name(<arguments>) from dual/<table name>;

CMC Limited

39
CONFIDENTIAL

System defined functions


Numeric functions

String functions
Date and time functions Conversion functions

Aggregate functions

CMC Limited

40
CONFIDENTIAL

NUMERIC FUNCTIONS
Function Ceil(arg1) Floor(arg1) Description Returns succeeding integer value Returns the preceding integer value Rounds the decimal to the nearest integer value(ie 0.5 scale is taken as a standard) This will truncate the decimal places and returns the integral part Returns the power of a number Syntax select ceil(0.1) from dept select floor(-0.1) from emp

Round(arg1)

select round(-1.5) from emp

Trunc(arg1)

select trunc(1.34) from emp

Power(arg1,arg2)

select power(2,10) from emp

Sqrt(arg1) Sin.,cos,tan(arg1)

Returns the square root of a number

CMC Limited

41
CONFIDENTIAL

String Functions
Function Lower(arg1) Description Display data in lower case Syntax select lower(ename) from emp

Upper(arg1)

Display data in upper case

select upper('kumar') from emp

Initcap(arg1)

Display data in sentence case

select initcap(ename) from emp

Substr(a1,a2,a3)

A1 string, a2 starting position of the string, a3 no of characters to be extracted including start position Combines 2 string objects

select substr(ename, 1, 3) from emp

Concat(arg1,arg2) lpad

select concat(45, 10) from emp

CMC Limited

42
CONFIDENTIAL

Lpad(arg1, arg2, arg3)

Arg1 string object/col name Arg2 no of characters to be added from the left hand side + the existing no of characters Arg3 characters to be added Arg1 string object/col name Arg2 no of characters to be added from the right hand side + the existing no of characters Arg3 characters to be added

SELECT LPAD(ENAME, LENGTH(ENAME)+3, 'Mr.') from emp

Rpad(arg1, arg2, arg3)

SELECT rPAD(ENAME, LENGTH(ENAME)+3, 'Mr.') from emp

Ltrim(arg1, arg2)

Trims characters from the left hand side

select ltrim('hyderabad', hyd') from emp /

Rtrim(arg1, arg2)

Trims characters from the right hand side

select rtrim('hyderabad', bad') from emp /

Translate(arg1, arg2, arg3)

Arg1 string, arg2 characters to be replaced, arg3 new characters

Replace (arg1, arg2, arg3)

CMC Limited

43
CONFIDENTIAL

Concat function and operator


Concat function can be implemented with respect to A MAX OF 2 columnS only but an operator does not require any constraint for its imposition of functionality on the columns

CMC Limited

44
CONFIDENTIAL

Replace and translate


Replace
No of characters to be replaced can be greater than or equal to the new characters

Translate
No of characters to be replaced = no of new characters

CMC Limited

45
CONFIDENTIAL

Date and time functions


Function Sysdate Decription Returns the system date(ddmon-yy) Arg1 date, arg2 no of months Syntax select sysdate+365 from emp

Add_months(arg1,arg2)

select add_months(sysdate, -17) from emp

Next_day(arg1, arg2)

Arg1 date, arg2 day of the week

select next_day(sysdate, 'saturday') from emp

Last_day(arg1)

Arg1 date

select last_day('01-feb-44') from emp

Months_between(arg1, arg2) Current_timestamp Display the current date and time in milli seconds

CMC Limited

46
CONFIDENTIAL

Aggregate functions
Sum Avg Count Min Max Any aggregate function accepts only 1 argument All the aggregate functions are independent of the type of the data to be used as an argument in those functions except for sum and average. Sum and average operate only on numeric type

CMC Limited

47
CONFIDENTIAL

Conversion functions
To_char(arg1,arg2) select to_char(sysdate, 'dd$mon$yy') from emp

Extract To_date(arg1)

select extract(year from sysdate) from emp;

CMC Limited

48
CONFIDENTIAL

Group by clause
select deptno, max(sal) from emp group by deptno Note
A column which has been defined in the group by clause need not appear in the select clause. But a column on which a aggregate function has not been invoked must and should appear in the group by clause A group by clause must and should be used in conjunction with an aggregate function in the select clause Where clause cannot be used in conjunction with a group by clause and the replacement would be the having clause Eg

select max(sal) from emp group by deptno having max(sal) > 3000

CMC Limited

49
CONFIDENTIAL

Order by
Display data in a sorted order
Ascending Descending

Syntax
Select <colname> from <table name> order by <col name> asc/desc select * from emp order by comm

If a column has null values then


For ascending sort order, null values will be displayed at the bottom and for descending sort order null values will be displayed at the top

CMC Limited

50
CONFIDENTIAL

Constraints
Not null

Unique
Primary key Check

Default
Foreign key

CMC Limited

51
CONFIDENTIAL

Syntax for constraints imposing


Create table <table name>(<col> <data type> [constraint <constraint name>] constraint type); Can impose constraints at 2 levels
Column level

Constraint definition and column definition apper at the same place Constraint definition and column definition appear at different places

Table level

CMC Limited

52
CONFIDENTIAL

Not null
Discards entry of null values and permits duplicated entries
create table B(eno number not null)

CMC Limited

53
CONFIDENTIAL

Unique
Discards duplicated entries and permits null values
create table B(eno number unique)

CMC Limited

54
CONFIDENTIAL

Primary key
Unique and not null

Eg
create table d(eno number primary key)

Primary key and unique keys by default impose a unique index on a column in a table Primary key is a unique row identifier

CMC Limited

55
CONFIDENTIAL

Check
create table e(sno number age number check(age >= 18))

CMC Limited

56
CONFIDENTIAL

Default
Create table e(sno number, doj date default sysdate) insert into c values(default);

CMC Limited

57
CONFIDENTIAL

Imposing constraints at the table level


create table c(eno number, ename varchar2(10), unique(eno)) create table d(eno number, ename varchar2(10), primary key(eno)) Composite primary key
create table c(eno number, dno number, primary key(eno,dno))

Composite unique key


create table d(eno number, dno number, unique(eno,dno))

create table e(eno number, ename varchar2(10), check(eno > 1))


CMC Limited
58
CONFIDENTIAL

Combination of constraints on a single column of a table

Not null

Unique

Primary key

Default

Check

Not null

No

Yes

Yes

No

Yes

Unique

Yes

No

No

No

Yes

Primary key

Yes

No

No

No

Yes

Default

Yes

Yes

Yes

No

Yes

CMC Limited

59
CONFIDENTIAL

Foreign key
It is a restriction which when imposed is used to validate data with respect to the table relationships Steps for implementing a foreign key
Create master table

create table d1(dno number primary key, dname varchar2(10))

Create a transaction table

create table e1(eno number primary key, ename varchar2(10),


dno number references dept(dno))

Syntax for transaction table creation


Create table <transaction table name>(<col> <data type> references <master table name>(<primary key col>) [<on delete cascade>/<on delete set null>])

CMC Limited

60
CONFIDENTIAL

Adding a constraint
alter table e1 add primary key(eno) Disabling a constraint
ALTER TABLE <TABLE NAME> ENABLE/DISABLE CONSTRAINT TYPE

Rename a constraint
alter table e1 rename constraint e1_nn to e2_nn;

Delete a constraint
alter table e1 drop constraint e2_nn;

CMC Limited

61
CONFIDENTIAL

Data base objects


Tables

Views
Synonyms Sequences

Indexes

CMC Limited

62
CONFIDENTIAL

Activities
Create

Retreive
Update Delete

CMC Limited

63
CONFIDENTIAL

Alias name
It is a temporary name through which the column of a table can be accessed Syntax
Select <col name> [as <alias name>] from <table name> select sal "#$%^&*()" from emp

CMC Limited

64
CONFIDENTIAL

Views
View is a virtual table View defintion is storable and not the data from the view Advts
User can access only specific columns of a table Up dations made on a view or on a table have to be reflected on the other data base object

Syntax
Create[or replace] view <view name> as <select statement>;

CMC Limited

65
CONFIDENTIAL

Create a view without the base table


create force view v3 as select * from abc Deleting a view
drop view v2

Create a view with a condition


Create view <view name> as <select statement [where <condition>]> [with check option]

View with aggregate functions


create view v1 as select max(sal) max_sal from emp3 group by deptno

Alias name

CMC Limited

66
CONFIDENTIAL

Contd
View with string functions
create view v2 as select lower(ename) ename_ll from emp

View with numeric functions


create view v3 as select sqrt(sal) sqr_sal from emp

Read only view


create view v4 as select empno from emp3 with read only

Possibilities
Create a view on a view Create a table on a view

CMC Limited

67
CONFIDENTIAL

Synonyms
What is the difference between alias name and a synonym
Alias name is temporary and used only for display purpose with respect to a specific column in a table Synonym is a permanent name given to a table which is storable in the data dictionary

When to use a synonym?


Synonym can be used if the name of a table is very long

Syntax
Create synonym <synonym name> for [<user name>] . <table name> create synonym d for emp3

Up dations made on a synonym are reflected on the base table and vice versa

CMC Limited

68
CONFIDENTIAL

POSSIBILITIES
Create a synonym on a view

Create a view on a synonym


Create a synonym on a synonym Create a table on a synonym

Alias name and a synonym


select eno as "Employee Number" from s6

CMC Limited

69
CONFIDENTIAL

Sequences
It is a data base object which encourages automatic generation of numbers in a table

Syntax
Create sequence <sequence name> [start with <value>] [minvalue <value>] [maxvalue <value>] [increment by <value>][cycle cache <value>];

Attributes of a sequence
Nextval Currval

Generate numbers from a sequence


Select <sequence name>.nextval/currval from <table name>/<dual>

By default, a sequence object creates a cache memory which stores the values printed/generated by it

CMC Limited

70
CONFIDENTIAL

Contd

Defining the start and end values of a sequence


create sequence d2 start with 100 maxvalue 200

Defining the increment value for a sequence Defining cycle cache for a sequence
create sequence d6 start with 100 maxvalue 110 cycle cache 100

Use a sequence in a table


insert into test1 values(d7.nextval, '&ename')

Setting increment value after sequence creation


alter sequence d10 increment by 2

Setting max value after sequence creation


alter sequence d10 maxvalue 100

Setting cycle cache value


alter sequence d10 cycle cache 50

Drop a sequence
Drop sequence d10;

CMC Limited

71
CONFIDENTIAL

Sub queries
Display the salary of all the employees who are getting a salary greater than smith Eg
select sal from emp where sal > (select sal from emp where ename = 'SMITH')

Update the salary of allen same as that of smith

Display the details of all the employees who are getting a salary greater than average salary
select * from emp where sal > (select avg(sal) from emp)

CMC Limited

72
CONFIDENTIAL

Joins
It is a concept through which data from multiple tables can be retrieved Joins eliminate a cross product relationship between the tables Joins
Equi join

Retreives data from multiple tables based on the equality condition provided both the tables are related Eg * * * select empno, ename, dname from emp,dept where emp.deptno = dept.deptno select empno, ename, dname,sal from emp,dept where emp.deptno = dept.deptno and sal > 1000

Non equi join Right outer join

select empno, ename, dname from emp,dept where emp.deptno(+) = dept.deptno

Left outer join

select empno, ename, dname from emp,dept where emp.deptno = dept.deptno(+)

CMC Limited

73
CONFIDENTIAL

Users
Syntax
Create user user name identified by password

Granting privilages
grant resource,connect to tanla;

Removing permissions
revoke resource,connect from tanla;

CMC Limited

74
CONFIDENTIAL

CMC Limited

75
CONFIDENTIAL

CMC Limited

76
CONFIDENTIAL

DESCRIPTION
It is a procedural language used in conjunction with SQL to perform some activities in a data base which are not possible using the normal SQL queries The implementation of PL/SQL specification is very much benificial when compared to SQL with respect to improving the systems performance It reduces the network traffic in a distributed environment The data types of SQL and PL/SQL remain the same PL/SQL specification ensures a logical and physical data independence

CMC Limited

77
CONFIDENTIAL

Contents
Anonymous blocks

Cursors
Functions Procedures

Exception handling mechanisms


Triggers Packages

CMC Limited

78
CONFIDENTIAL

ANONYMOUS BLOCK
This block can form a single unit for combining different sets of SQL statements so that call to be made to a data base from an external buffer or location can be only for 1 time accomplishing different types of results This block cannot be permanently stored in the data dictionary and is used only at run time

CMC Limited

79
CONFIDENTIAL

Structure of anonymous block

Declare <local variable declarations> Begin <output statements>; <conditional statements>; <loops>; <assignments>; <dml statements>; Exception when <error type> then raise_application_error(<error no> <message>); End;

Output statement Dbms_output.put_line(<message>); The above statement can be operational if the server output is set to an on mode Set server output on
80
CONFIDENTIAL

CMC Limited

Display a message
begin dbms_output.put_line('Exam to be conducted in the last session'); end;

Use the ampersand (&) operator to give any input at run time

CMC Limited

81
CONFIDENTIAL

Print the system date

begin

dbms_output.put_line(sysdate);
end; /

CMC Limited

82
CONFIDENTIAL

Provide a date at run time and display the same

declare date1 date; begin date1 := &d1; dbms_output.put_line('The date is ' ||date1); end;

CMC Limited

83
CONFIDENTIAL

COMMENTS
declare date1 date; /* THIS IS A LOCAL VARIABLE */ begin date1 := &d1; dbms_output.put_line('The date is ' ||date1); end; /

CMC Limited

84
CONFIDENTIAL

ADD 2 NUMBERS
DECLARE N1 NUMBER; N2 NUMBER; N3 NUMBER; BEGIN N1 := &NUM1; N2 := &NUM2; N3 := N1+N2; DBMS_OUTPUT.PUT_LINE('THE SUM IS ' ||N3); END; /

CMC Limited

85
CONFIDENTIAL

DETERMINE THE BIGGEST AMONG 2 NUMBERS


Declare n1 number; n2 number; begin

n1 := &num1; n2 := &num2; if(n1 > n2) then dbms_output.put_line('The biggest number is '|| n1); else dbms_output.put_line('The biggest number is '|| n2); end if;
end;

CMC Limited

86
CONFIDENTIAL

Program
Write an anonymous block which will perform the operations on numbers dependending on the users choice If the choice is 1 then perform addition If choice is 2 then perform subtraction If choice is 3 then perform multiplication Else perform division

CMC Limited

87
CONFIDENTIAL

declare n1 number; n2 number; n3 number; begin n1 := &num1; n2 := &num2; n3 := &num3; if(n1 > n2 and n1 > n3) then dbms_output.put_line('The biggest number is ' ||n1); elsif(n2 > n1 and n2 > n3) then

dbms_output.put_line('The biggest number is ' ||n2); else


dbms_output.put_line('The biggest number is ' ||n3); end if; end;

CMC Limited

88
CONFIDENTIAL

Accept empno at run time and display the name of that employee

declare no number; ge number; begin no := &num1; select age into ge from test where eno = no; dbms_output.put_line(ge); end;

CMC Limited

89
CONFIDENTIAL

Accept the empno at run time and update the salary of that employee by 10%
declare eno emp1.empno%type; sa emp1.sal%type; begin eno := &eno; select sal into sa from emp where empno = eno; sa := sa+(10*sa/100); update emp1 set sal = sa where empno = eno; dbms_output.put_line('The updated salary is '||sa); end; /

CMC Limited

90
CONFIDENTIAL

Description Variable declaration with respect to a column in the table Syntax


<Variable name> <table name>.<column name> % type; %type

It is an attribute which when used in conjunction with a variable name signifies that the data type of the column in a table is in compliance with the declared type of the variable in the anonymous block. The advantage of using this attribute is that if any changes are made to the table structure, the same changes are not reflected in the application logic encouraging physical data independence

Into

This operator is used to copy the data from a specific column in a table into the local variable; Syntax * Select <column name> into <output variable name> from <table name> where <column name> = <input variable name>

CMC Limited

91
CONFIDENTIAL

Accept empno at run time and display the name and salary of that employee

declare eno emp.empno%type; name emp.ename%type; sa emp.sal%type; begin eno := &employee_no; select ename,sal into name, sa from emp where empno = eno; dbms_output.put_line(name ||' '|| sa); end;

CMC Limited

92
CONFIDENTIAL

Loop
declare

x number; y number;
begin x := 1; loop y := x*2; insert into test10 values(x,y); x := x+1; exit when x >= 10; end loop; dbms_output.put_line('Insertion sucessful....');

end;

CMC Limited

93
CONFIDENTIAL

For loop
declare x number; y number; begin x := 1; for x in 1..10 loop y := x*2; insert into test10 values(x,y); end loop; dbms_output.put_line('Insertion sucessful....'); end;

CMC Limited

94
CONFIDENTIAL

Requirement
Accept empno at run time and update the salary of an employee :
If he belongs to deptno 10 then update his salary by Rs 100 If he belongs to deptno 20 then update his salary by Rs 200 If he belongs to deptno 30 then update his salary by Rs 300

CMC Limited

95
CONFIDENTIAL

declare eno emp90.empno%type; dno emp90.deptno%type; nsal emp90.sal%type; begin eno := &employee_no; select deptno,sal into dno,nsal where empno = eno; if(dno = 10) then nsal := nsal+100; elsif(dno = 20) then nsal := nsal+200; else nsal := nsal+300; end if; update emp90 set sal = nsal where empno = eno; dbms_output.put_line('Records Updated...'); end;

CMC Limited

96
CONFIDENTIAL

Variables belonging to the same type cannot be declared on a single line

declare n1, n2 number; begin n1 := 10; n2 := 20; dbms_output.put_line(n1+n2); end; /

CMC Limited

97
CONFIDENTIAL

If a value is not assigned to any local variable then by default, a null value will be supplied by the system

declare
n number; begin dbms_output.put_line('The value is ' ||n); end; /

CMC Limited

98
CONFIDENTIAL

CMC Limited

99
CONFIDENTIAL

CMC Limited

100
CONFIDENTIAL

REQUIREMENT
Display the names of all the employees from emp table declare name emp.ename%type ;

begin
select ename into name from emp; end;

CMC Limited

101
CONFIDENTIAL

Description
The above code returns an error because into operator can fetch on a maximum basis only 1 row at a time for a particular input given at run time To fetch multiple rows from a table, we need to implement a specification referred to as cursors

CMC Limited

102
CONFIDENTIAL

Contd
Cursor is a private SQL area used for fetching the data from a table row wise ie for every SQL statement issued by the user, by default a cursor will be created for that statement

CMC Limited

103
CONFIDENTIAL

How the system creates a cursor for every SQL statement?


Declare the cursor
Cursor <cursor name> is <select statement>

Open the cursor


Open <cursor name>;

Fetch data from the cursor into a local variable


Fetch <cursor name> into <local variable>;

Close the cursor


Close <cursor name>;

CMC Limited

104
CONFIDENTIAL

Display the names from the emp table using cursors


declare cursor c1 is select ename from emp; name emp.ename%type;

begin
open c1; loop fetch c1 into name; exit when c1%notfound; dbms_output.put_line(name); end loop; close c1; end; /

CMC Limited

105
CONFIDENTIAL

Display the first 3 rows from emp table


declare cursor c1 is select ename from emp; name emp.ename%type; begin open c1; loop fetch c1 into name; exit when c1%rowcount >3; dbms_output.put_line(name); end loop; close c1; end;

CMC Limited

106
CONFIDENTIAL

Display the table itself using cursors


declare
cursor c2 is select * from dept; rec dept%rowtype; begin open c2; loop fetch c2 into rec; exit when c2%notfound; dbms_output.put_line(rec.deptno || ' ' ||rec.dname || ' ' ||rec.loc); end loop; close c2; end; /

CMC Limited

107
CONFIDENTIAL

Attributes of cursors
%rowtype
This attribute can be used with cursors if you want to declare a variable which holds data from multiple columns in the same table Syntax

<variable name> <table name>%rowtype;

%rowcount
This attribute can be used with cursors to limit the display of data from tables with respect to specific number of rows

%notfound
This attribute when used with cursors determines the availability of data within a cursor

CMC Limited

108
CONFIDENTIAL

CMC Limited

109
CONFIDENTIAL

CMC Limited

110
CONFIDENTIAL

USER DEFINED FUNCTIONS


SYNTAX
Create or replace <function name> (<arguments>) return <data type> is <variable> <data type>; Begin <statements>; return (<variable>); End [<function name>]

CMC Limited

111
CONFIDENTIAL

Function to add 2 numbers

function add3(n1 number, n2 number) return number is s number; begin s := n1+n2; return s; end;

CMC Limited

112
CONFIDENTIAL

FUNCTION WITH DEFAULT PARAMETERS


Create or replace function add4(n1 number default 10, n2 number default 20) return number is s number; begin s := n1+n2; return s; end;

CMC Limited

113
CONFIDENTIAL

Function that accepts empno as an input and return the name of the employee

create or replace function name_disp(eno emp.empno%type) return emp.ename%type is name emp.ename%type; begin select ename into name from emp where empno = eno; return name; end;

CMC Limited

114
CONFIDENTIAL

CMC Limited

115
CONFIDENTIAL

Function Returns a value It accepts only IN parameters

Procedure Does not return a value Accept IN and Out parameters

CMC Limited

116
CONFIDENTIAL

Syntax

Create or replace procedure <procedure name>(<arguments>) is Begin statements; End;

CMC Limited

117
CONFIDENTIAL

Procedure to add 2 numbers

create or replace procedure add5(n1 number, n2 number , n3 out number) is begin n3 := n1+n2; dbms_output.put_line('The sum is ' ||n3); end;

CMC Limited

118
CONFIDENTIAL

Description
In case a parameter has been defined as an out parameter in a procedure then that parameter has to be declared as a session variable in the SQL prompt
SQL > VAR <VARIABLE> <DATA TYPE> SQL > exec <procedure name>(<val1>, <val2>, <val n>, :<out parameter>) In a procedure call, the out parameter has to be defined as a bind variable

Calling a procedure

Bind variable

CMC Limited

119
CONFIDENTIAL

CMC Limited

120
CONFIDENTIAL

Exception types
Zero divide

No_data_found
Too_many_rows

CMC Limited

121
CONFIDENTIAL

Zero_divide
declare n1 number; n2 number := 0; begin n1 := &num1; dbms_output.put_line(n1/n2); exception when zero_divide then raise_application_error(-20001, 'sorry cannot perform division'); end;

CMC Limited

122
CONFIDENTIAL

No data found
declare eno emp.empno%type; name emp.ename%type; begin eno := &employee_no; select ename into name from emp where empno = eno; dbms_output.put_line(name); exception when no_data_found then raise_application_error(-20001, 'data not available in the emp table'); end;

CMC Limited

123
CONFIDENTIAL

Too_many_rows
declare

name emp.ename%type;
begin select ename into name from emp; dbms_output.put_line(name); exception when too_many_rows then raise_application_error(-20001, 'see 1 row at a time'); end; /

CMC Limited

124
CONFIDENTIAL

CMC Limited

125
CONFIDENTIAL

DESCRIPTION
Package is a named group of functions, procedures and cursors Advantages of using a package
Resolve ambiguity in the names of functions and procedures Reusability

CMC Limited

126
CONFIDENTIAL

How to create a package ?


Package specification

Package body
Note
Package specification name and package body name must be the same

CMC Limited

127
CONFIDENTIAL

Syntax for creating a package specification


Create package <package name> is <procedures>; <functions>; <cursors>; End;

CMC Limited

128
CONFIDENTIAL

Syntax for creating a package body


Create package body <package name> is Procedure <procedure name> is Begin <statements>; End; Function <function name> return <data type> is <var> <data type>; Begin <statements>; return var; End; End;

CMC Limited

129
CONFIDENTIAL

Requirement
Create a package which consists of a function and a procedure The function has to add 2 numbers and return the sum The procedure has to subtract 2 numbers

CMC Limited

130
CONFIDENTIAL

Package specification

create package m1 is function sum1(n1 number, n2 number) return number; procedure sub1(n1 number, n2 number, n3 out number); end;

CMC Limited

131
CONFIDENTIAL

Package body
create package body m1 is function sum1(n1 number, n2 number) return number is s number; begin s := n1+n2; return s; end; procedure sub1(n1 number, n2 number, n3 out number) is begin n3 := n1-n2; dbms_output.put_line('The result is ' ||n3); end; end;

CMC Limited

132
CONFIDENTIAL

Call a procedure within a package


Exec <package name> . <procedure name> (<arguments>)
Call a function within a package Select <package name> . <function name> (<args>) from <table name>

CMC Limited

133
CONFIDENTIAL

CMC Limited

134
CONFIDENTIAL

Description
It is an event which is fired implicitly when a DDL or DML transaction gets executed It is a type of restriction that can be placed on user operations

CMC Limited

135
CONFIDENTIAL

Syntax for creating a DML trigger


Create or replace trigger <trigger name> of <col> on <table name> before /after insert/update/delete for each row; Begin raise_application_error(<errno> <message>); End;

CMC Limited

136
CONFIDENTIAL

Restrict the users from deleting a row from emp table

create or replace trigger t1 before delete on emp for each row begin raise_application_error(-20001, 'sorry cannot delete a row'); end;

CMC Limited

137
CONFIDENTIAL

Restrict the users from inserting data into a table

create or replace trigger t2 before insert on result3 for each row begin raise_application_error(-20001, 'do not try to insert a row'); end;

CMC Limited

138
CONFIDENTIAL

Restrict the users from creating the table

CMC Limited

139
CONFIDENTIAL

CMC Limited

140
CONFIDENTIAL

NAME : S.CHANDRASEKHAR MOBILE : 9247 353820 MAIL ID : chandusivalenka@gmail.com Available time : after 9.00 P.M in the night

CMC Limited

141
CONFIDENTIAL

You might also like