Oracle Sql & PLSQL Complete guide

225
What is a data base? Data base is a structure or a component used for storing the data Data base can be implemented using file systems either in C or C++ or Java

description

Complete Description about the SQL and PLSQL,, the best ppt i have ever seen,,, Easy and Brief guide and description about the Oracle

Transcript of Oracle Sql & PLSQL Complete guide

Page 1: Oracle Sql & PLSQL Complete guide

What is a data base?•Data base is a structure or a component used for storing

the data•Data base can be implemented using file systems either in

C or C++ or Java

Page 2: Oracle Sql & PLSQL Complete guide

Web siteFor a bank

User Open account

Account Data base

Java

C program

Page 3: Oracle Sql & PLSQL Complete guide

Create table

• Data in a data base is stored in the form of tables • How to create a table?

– Create table <table name>(<col> <data type>);• List of all the available data types to be used in Oracle for defining

columns can be obtained by using the following command– SQL > VAR X DATE (SQL > is not a part of the command)

• CREATE TABLE ACC1(ANO NUMBER, ANAME CHAR(10));

Page 4: Oracle Sql & PLSQL Complete guide

ALTER• Modify size of a column

– Alter table <table name> modify(<col> <data type[(size)]>);• alter table acc1 modify(aname char(7));• alter table acc1 modify(aname char(10))

• Add a column to a table– Alter table <table name> add(<col> <data type>);

• alter table acc2 add(ano number);• alter table acc2 add(atype varchar2(10), mbno number);

• Delete a column from a table– Alter table <table name> drop column <col name>;

• alter table acc2 drop column atype;• alter table acc2 drop(aname, mbno);

• Rename a column in a table– Alter table <table name> rename column <old name> to <new name>;

• alter table acc2 rename column ano to acc_no;

Page 5: Oracle Sql & PLSQL Complete guide

• Column size can be decreased if and only if the column is empty • Column size can be increased whether or not the column is empty• If you want to reduce the size of a column even though the column

is containing data then that column has to be declared as varchar2(size). Because varchar2(size) type alocates variable no of memory locations at run time. Whereas char(size) will allocate fixed number of memory locations at run time

• Size of value in a column must be <= max size of a column• Col data type can be changed into a compatible type(char to

varchar2) even though the column is not empty. But col type can be changed into a incompatible type(char to number) if the col is empty

• When you are changing the data type from char to vachar2 you cannot decrease the size of a column

• In a table, you should have atleast 1 column ie you cannot delete all the columns from a table

Page 6: Oracle Sql & PLSQL Complete guide

number(p,s)● This is a special number type that can be used for controlling

the no of digits before decimal and mostly we use this type for storing decimal numbers

● S is the scale of a number ie it defines the min no of digits after decimal

● Max No of digits before decimal is defined using p – s which is the precision of a number

● Less then min is allowed but more than max is not allowed ● Number validation will be done only based on precision and

not on scale● Default precision for any number type is 38

Page 7: Oracle Sql & PLSQL Complete guide

INSERT

• This command is used for inserting data into columns of a table

• Syntax for using this command– Insert into <table name> values(<val 1>, <val 2>);

• insert into stud_test values(102);– Insert data into specific columns of a table

• insert into stud_test1(sno) values(102);– Define an insertion order

• insert into stud_test1(sname, sno) values('james', 103)

– Insert data at run time• insert into stud_test1 values(&sno, '&sname');

Page 8: Oracle Sql & PLSQL Complete guide

Contd..

• insert into stud_test1 values(&123, '&456');– Any character succeeding & in insert command will be

treated as a value and not as a name of the column. Hence you can provide any text succeeding &

• Insert command inserts values into columns of a table depending on No, type and order of those values

• Insert command always inserts values as new row

Page 9: Oracle Sql & PLSQL Complete guide

NULL VALUE

• When you do not insert data into a column of a table for a specific row then by default a NULL value will be inserted into that column by the data base

• NULL value does not occupy space in memory• Null value is independent of a data type of any column in a

table

Page 10: Oracle Sql & PLSQL Complete guide

UPDATE

• This command inserts values for the existing rows • This command can also be used for deleting values from a cell

of a table without the need for deleting a row and a column• Syntax

– Update <table name> set <col name> = <new value> [where <condition>];

• update stud_test1 set mbno = 301 where sno = 101;• update stud_test1 set mbno = null where mbno = 301;

Page 11: Oracle Sql & PLSQL Complete guide

DELETE

• This command is used for deleting specific or all the rows from a table

• Syntax– Delete from <table name> [where <condition>];\

Page 12: Oracle Sql & PLSQL Complete guide

Truncate

• This command can also be used for deleting all the rows from a table

• Syntax– Truncate table <table name>;

• Truncate command cannot be rolled back because it is a AUTO COMMIT operation ie changes committed cannot be rolled back. But DELETE is not a AUTO COMMIT operation. Hence it can be ROLLED BACK/

Page 13: Oracle Sql & PLSQL Complete guide

DROP

• This command can be used for permanently deleting the table from a data base

• Syntax– Drop table <table name>;

• drop table stud_test;

Page 14: Oracle Sql & PLSQL Complete guide

Select

• This command is used to retrieve data from a table• Syntax

– Select <col name> from <table name> [where <condition>];• select ename, job, sal from emp;

• select * from emp ( * denotes all the columns in a table)

Page 15: Oracle Sql & PLSQL Complete guide

OPERATORS

Page 16: Oracle Sql & PLSQL Complete guide

Relational operators

• display the details of those emps who are getting a sal > 20000– SELECT * FROM EMP1 WHERE SAL > 20000

• Display the details of those emps who are getting a sal between 10000 and 20000– select * from emp1 where sal >= 10000 and sal < 20000

• Display the details of those emps who are either clerks or getting a sal < 20000– select * from emp1 where job = 'clerk' or sal < 20000

Page 17: Oracle Sql & PLSQL Complete guide

SQL OPERATORS

Page 18: Oracle Sql & PLSQL Complete guide

Between<lower> and <upper>

• This operator is used as a replacement for relational(>, <) and logical operators(AND, OR)

• In this operator lower and upper values are inclusive if they are of number or date types

• In this operator upper limit is not inclusive when it is of a char type

• The lower limit must be <= upper limit– select * from emp1 where sal between 10000 and 20000

Page 19: Oracle Sql & PLSQL Complete guide

IS NULL

• This operator can be used for testing for the existence of NULL values in any column of a table

• Display the details of those employees who are not having any job

• select * from emp1 where job is null• Nul l value cannot be compared. Hence you cannot use

relational operators for comparing NULL value with a column• Therefore IS NULL operator has to be used for that purpose

Page 20: Oracle Sql & PLSQL Complete guide

Concatenation operator (||)

• This operator should be used for appending a string to a variable or a column

• Display the data from emp table in the following format for all the rows – Ravi is getting a sal of Rs. 20000

• select ename || ' is getting a sal of Rs. ' || sal from emp1– “Ravi is an employee”

• select ' " '||ename || ' is an employee " ' from emp1

Page 21: Oracle Sql & PLSQL Complete guide

IN OPERATOR

• This operator is used to compare multiple values with a single column

• In this operator, the values must be of the same type and they should belong to only 1 column

• This operator is a replacement for OR operator– select * from emp1 where job in('clerk', 'manager')

Page 22: Oracle Sql & PLSQL Complete guide

Like operator • This operator is used for comparing characters in a string from a specific

position• % ignores variable number of characters • _ ignores only 1 char• Display the details of thos e emps whose name is starting with “r”

– select * from emp1 where ename like 'r%‘

• Display the details of those emps who have ‘naidu’ as their name– select * from emp1 where ename like '%naidu%‘

• Display the details of those emps whose name is starting with “a” as the second char– select * from emp1 where ename like '_a%‘

• Display the details of those emps whose first char is N and third char is I– select * from emp1 where ename like 'n_i%';

Page 23: Oracle Sql & PLSQL Complete guide

• Display the details of those emps whose name is starting with a char which is between A and L– select * from emp1 where ename between 'a%’ and 'l%'

Page 24: Oracle Sql & PLSQL Complete guide

FUNCTIONS

Page 25: Oracle Sql & PLSQL Complete guide

Description

• Function is a sub program which performs a specific task

• Every function utmost returns only 1 value• Functions in Oracle data base will be used or defined

for– Performing arithmetic calculations which are not possible

using arithmetic operators – Formatting text – Type casting ie converting one type of data into another

Page 26: Oracle Sql & PLSQL Complete guide

Using functions

• Functions can be either built in or user defined Ie there are 2 types of functions– System defined functions– User defined functions

• Usage of a function is subject to calling a function– Select <function name(args)> from <table name>;

Page 27: Oracle Sql & PLSQL Complete guide

System defined functions

• Number functions• String functions• Date and time functions• Conversion functions• Aggregate functions

Page 28: Oracle Sql & PLSQL Complete guide

NUMBER FUNCTIONS

Page 29: Oracle Sql & PLSQL Complete guide

Ceil(arg1)

• This function will return the succeeding integer value for the decimal value passed as an argument

• This function will accept only 1 parameter which is of a number type– select ceil(10.35) from emp1

• When you pass a negative argument to this function, it will return the current integer value– select ceil(10.35) from emp1

Page 30: Oracle Sql & PLSQL Complete guide

Floor(arg1)

• This function will return the preceding integer value by accepting a decimal value as an argument– select floor(-10.9999) from emp1

• When you pass a negative argument, this function will return the preceding negative value

Page 31: Oracle Sql & PLSQL Complete guide

Round(arg1, [arg2])

• This function will return either the preceding or succeeding integer value depending on the decimal value ie if the decimal value is >= 0.5 then succeeding integer value will be returned else if the decimal value is < 0.5, preceding integer value will be returned

• The second argument to be passed to this function is an optional argument. But it signifies the no of decimal places up to which the number has to be rounded– select round(10.567899991345, 4) from dual

Page 32: Oracle Sql & PLSQL Complete guide

Power(arg1, arg2)

• This function returns the power of 2 numbers• It accepts 2 arguments

– Arg1 is the base which can be –ve or +ve– Arg2 is the exponent which can be –ve or +ve

• Using this function anything raised to the power of 0 will always return 1 including 0

Page 33: Oracle Sql & PLSQL Complete guide

Sqrt(arg1)

• This function returns the square root of a number• Arg1 must be always +ve• If it is negative then the function should return a

imaginary number which is represented as a complex number.

• A complex number can be stored as a class type• Therefore the function should return an object which

is not possible in ORACLE

Page 34: Oracle Sql & PLSQL Complete guide

MOD(ARG1, ARG2)

• This function will return the remainder of a division of 2 numbers

• Arg1 is the numerator and arg2 is the denominator

• Sign of the remainder must be same as sign of the numerator

• Arg1 and arg2 can be of decimal types also

Page 35: Oracle Sql & PLSQL Complete guide

Abs(arg1)

• This function will convert a –ve number into a +ve number

• Arg1 can be +ve or -ve

Page 36: Oracle Sql & PLSQL Complete guide

STRING FUNCTIONS

Page 37: Oracle Sql & PLSQL Complete guide

CASE CONVERSION FUNCTIONS• Lower(arg1)

– Arg1 is of a char type– This function will return the text in lower case

• Upper(arg1)– Arg1 is of a char type– This function will return the text in upper case

• Initcap(arg1)– Arg1 is of a char type– This function will return the text in Title case

• Argument to be passed to a string function can be a – Constant– Column name– Variable– Function

Page 38: Oracle Sql & PLSQL Complete guide

Substr(a1,a2,a3)

• This function is used for extracting a part of a text from a given text

• Arg1 is the main string• Arg2 is the starting position of the text to be extracted• Arg3 is the no of chars to be extracted from the start position

of the sub string • Arg1 can also be passed as a number type

Page 39: Oracle Sql & PLSQL Complete guide

instr(string, char)

● This function returns the position of the first occurrence of a char in a string

● Arg1 is the string● Arg2 is the char for which you need to know the position● Eg : select instr('welcome', 'e') from dept

Page 40: Oracle Sql & PLSQL Complete guide

Length(arg1)

• This function returns the no of chars in a text• Arg1 is of a char type

– select length('welcome to cmc and thank you') from dept;

• Arg1 can also be of a number type– select length('welcome to cmc and thank you')

from dept;

Page 41: Oracle Sql & PLSQL Complete guide

Concat(arg1, arg2)

• This function will concatenate 2 different strings • Arg1 and arg2 can be of char or number types

– select concat(ename, concat(' ', sal)) from emp– select concat(ename, concat(' is a ', job)) from emp

• Disadvantages with this function– You cannot pass more than 2 args to this function– Position and number of the characters to be added must

be explicitly provided as an argument

Page 42: Oracle Sql & PLSQL Complete guide

Padding functions

• These function are used to resolve the limitations with concat function

• These functions are used to add chars from left or right side of a string

• Lpad(arg1, arg2, arg3)– Arg1 is a string or number – Arg2 is the no of chars existing in the main string + the number of

characters to be added from the left side of the string– Arg3 is the chars to be added from the left side

• Rpad(arg1, arg2, arg3)– Arg1 is a string or number – Arg2 is the no of chars existing in the main string + the number of characters

to be added from the right side of the string– Arg3 is the chars to be added from the right side

Page 43: Oracle Sql & PLSQL Complete guide

Contd..

• select lpad('kumar', 8, 'Mr.’) from dept• select rpad('kumar', 15, '*') from dept;• select lpad(job, length(job) + 10, '$') from emp

Page 44: Oracle Sql & PLSQL Complete guide

Trimming functions

• These functions are used to trim the chars from left or right side of a string

• Ltrim(arg1, arg2)– Arg1 is the string– Arg2 is the characters you want to trim from the LHS – select ltrim('welcome', 'wel') from dept;

• rtrim(arg1, arg2)– Arg1 is the string– Arg2 is the characters you want to trim from the RHS – select rtrim('welcome', 'come') from dept;

Page 45: Oracle Sql & PLSQL Complete guide

Contd..

• Chars to be trimmed either from left or right side must be the first most chars starting from left or right

• In ltrim or rtrim, if the char to be trimmed is having a multiple occurrence continuously then every occurrence will be trimmed(“cccbc”). Else if the occurrence is alternating then only the first occurrence will be trimmed(“cfcfcf” ) based on the chars in the trim set

• Trim(arg1)– This trims spaces from left and right side of a string– select trim('c' from 'cbcbcbc') from dept

Page 46: Oracle Sql & PLSQL Complete guide

Replace and translate

• These functions are used for replacing old chars with new chars in a string

• These functions will accept 3 arguments– Arg1 is a main string– Arg2 is the old chars you want to replace in the main string– Arg3 is the new chars to you want to substitute in place of

old chars– select translate('abcdef', 'def', 'pqr') from dept– select replace('abcdef', 'def', 'pqr') from dept

Page 47: Oracle Sql & PLSQL Complete guide

Translate Replace

The no of new charas must be <= the old chars to be replaced

The no of new chars can be > old chars to be replaced

Multiple occurrences of old chars will be replaced with only the first new char

Multiple occurrences of old chars will be replaced with every new char

Page 48: Oracle Sql & PLSQL Complete guide

Reverse(arg1)

• This function will reverse a string or a number

Page 49: Oracle Sql & PLSQL Complete guide

DATE TYPE

● STANDARD date formats supported in ORACLE are

● DD-MON-YY● DD-MON-YYYY

● Only those formats can be used for storing date values in any column declared as a date type

● Any other format other than the above depicted ones will be treated as a char type and not as a date type

Page 50: Oracle Sql & PLSQL Complete guide

Date and time functions

• Sysdate– This function returns the system date and this function will

not accept any arguments – select sysdate from dept;

• Add_months(arg1, arg2)– This function will return a date succeeding or preceding the no of

months from the date specified in arg1– Arg1 is the date type– Arg2 is the number type(no of months)– select add_months(sysdate, 120) from dept

Page 51: Oracle Sql & PLSQL Complete guide

Contd..• Months_between(arg1, ag2)

– This function will return the no of months between 2 dates– Arg1 and arg2 are of date types– select round(months_between(sysdate, '13-jan-83')/12) || ' years' from dept– select ename, round(months_between(sysdate, hiredate)/12) || ' years' from

emp

• Last_day(arg1)– This function will return the last day of a date specified in arg1– select last_day('02-feb-13') from dept

• Next_day(arg1, arg2)– This function will return the date on the coming day of the week– Arg1 is the start date– Arg2 is the day of the week(mon – sun)– select next_day(sysdate, 'sat') from dept– select next_day(sysdate, 1) from dept

Page 52: Oracle Sql & PLSQL Complete guide

Contd..

• Arg2 in next_day function can also be of a number type ie from 1 to 7 which is from sun to sat

• Current_timestamp– This function will return the system date and system time which does

not accept any arguments – select current_timestamp from dept;

Page 53: Oracle Sql & PLSQL Complete guide

CONVERSION FUNCTIONS

Page 54: Oracle Sql & PLSQL Complete guide

DESCRIPTION

• These functions are used for converting one type of data into another

• To_char(arg1, arg2)– This function converts a date or a number type into a char type– Arg1 is the date or number value and arg2 is the format in which you

want to represent that date or number value– Arg1 must and should be a

• Function• Column name• Variable

– And must not be a date constant but can be a number constant– User defined formats in arg2 must be enclosed in “ “

Page 55: Oracle Sql & PLSQL Complete guide

select to_char(sysdate, 'dd-mm-yyyy') from dual/

22-01-2013

select to_char(sysdate, 'year') from dual/

Year is printed in words

select to_char(sysdate, 'dy') from dual/

Day : tue

select ename, to_char(sal, '$99999.99') from emp1/

select to_char(1000, '9999.999') from dual/select to_char(hiredate, ' "you have joined on" dd-mm-yyyy') from emp1/

Page 56: Oracle Sql & PLSQL Complete guide

To_date(arg1,arg2)

• This function will convert a char type into a date type

• Ag1 is the date value• Arg2 is the format of the date value in arg1• Advantage with this function

– User can supply any customized date format which can be converted into standard date format using this function

Page 57: Oracle Sql & PLSQL Complete guide

Extract()

• This function will extract a part of the date from a given date

• The return type of this function is a number• “Year”, “month” and “day” formats only must be

used in this function and no other format is allowed – select extract(year from sysdate) from emp1– select extract(month from sysdate) from emp1– select extract(year from sysdate) - extract(year from

hiredate) from emp1

Page 58: Oracle Sql & PLSQL Complete guide

Aggregate functions

• Sum(a1)• Avg(a1)• Min(a1)• Max(a1)• Count(a1)

Page 59: Oracle Sql & PLSQL Complete guide
Page 60: Oracle Sql & PLSQL Complete guide
Page 61: Oracle Sql & PLSQL Complete guide

Description

• Aggregate functions are multiple row functions because every aggregate function will return utmost 1 value for all the rows of a table

• Number, string, date and time, conversion functions are single row functions because these functions return utmost 1 value for every row of a table

• You can pass any type of data as an argument to max, min, count functions

• Aggregate functions completely ignore NULL values

Page 62: Oracle Sql & PLSQL Complete guide

Real time applications with functions

• select dname from dept where dname = initcap('accounts')• update emp1 set sal = sal + (sal*10/100) where extract(year

from hiredate) = 1987

Page 63: Oracle Sql & PLSQL Complete guide

Clauses in select statement

Page 64: Oracle Sql & PLSQL Complete guide

Group by and having clauses

• This clause is used to group the data according to a criteria using a column

• Syntax – Select <col name>, <aggregate function> from <table name> group by

<col name>;– Eg : select deptno, max(sal) from emp group by deptno

• Any column identified in the group by clause need not appear in the select clause(select max(Sal) from emp group by deptno). But any column identified in the select clause must and should appear in the group by clause(select ename, max(sal) from emp group by deptno → error)

• Group by clause used on a column will by default display the data in ascending order

• Group by clause by default will eliminate duplicates

Page 65: Oracle Sql & PLSQL Complete guide

Contd..

• Aggregate function cannot be used in WHERE clause. Hence we should use having clause for that purpose – select deptno, max(sal) from emp group by deptno cl

having max(Sal) >= 3000

• Group by and having clauses can be used without aggregate functions

Page 66: Oracle Sql & PLSQL Complete guide

Order by clause

• This clause is used for sorting data in a column in ascending or descending order

• Syntax– Select <col name> from <table name> order by <col

name> [asc]/desc– select * from emp order by ename desc– select ename, job, hiredate from emp order by 2 desc– select ename emp_name from emp order by emp_name

desc

Page 67: Oracle Sql & PLSQL Complete guide

• Alias name can be used in the order by clause• Number in the order by clause signifies the

position of the column in the select clause• Order of clauses

– select deptno, max(sal) from emp where sal >= 3000 group by deptno having max(Sal) >= 3000 order by deptno desc

– /

Page 68: Oracle Sql & PLSQL Complete guide

CONSTRAINTS

Page 69: Oracle Sql & PLSQL Complete guide

DESCRIPTION

• CONSTRAINT is a limitation or restriction to be imposed on any column of a table to validate data

• When to impose constraints?– Constraints can be imposed either during the process of table

creation or after creating a table

• Constraint types– NOT NULL– UNIQUE– PRIMARY KEY– CHECK– DEFAULT(Default cannot be treated as a constraint by DBA)

– key

Page 70: Oracle Sql & PLSQL Complete guide

HOW TO IMPOSE A CONSTRAINT DURING THE PROCESS OF TABLE CREATION?

• Create table <table name>(<col name> <data type> [constraint <constraint name>] constraint type);

• Providing a name to the constraint is optional. Ie if you do not provide a name to the constraint then by default, the system will provide it’s own name in the format SYS_<number>

• Constraint name is provided for disabling or deleting a constraint

• SYS is the user name for SYSDBA

Page 71: Oracle Sql & PLSQL Complete guide

Not null • This constraint is imposed to obscure the entry of

null values into a column of a table– create table testnull(sno number constraint tab1_nn not

null)– create table testnull2(sno number not null, sname

varchar2(20) not null)

• Command for tracking names of constraints– select constraint_name, table_name from

user_constraints where table_name = upper('testnull1')

• At run time, null value should be explicitly passed for number type and do not enter any value to enter NULL value for char type

Page 72: Oracle Sql & PLSQL Complete guide

Unique

• This constraint when imposed on any column of a table will not allow data in that column to be duplicated – create table testun(sno number unique)– create table testun1(sno number unique, age number unique)

• One NULL value is never equal to another NULL value.

Page 73: Oracle Sql & PLSQL Complete guide

Primary key

• This constraint is a combination of unique and not null

• In a table on a max basis, you can impose only one physical primary key. But on a need basis, if you require to define 2 primary keys in 1 table, then explicitly impose a combination of UNIQUE and NOT NULL– Create table testun2(sno number unique not null)– create table pk(sno number primary key)– create table pk1(sno number unique not null, age number

unique not null);

Page 74: Oracle Sql & PLSQL Complete guide

Check

• This constraint is used to impose user defined or customized restrictions on any column of a table

• Impose a restriction on a column in such a way that age must be > 18 years

• Impose restriction on a column mbno in a table in such a way that mbno must exactly contain 10 digits

• Impose restriction on a column mbno in a table in such a way that mbno must exactly contain 10 digits and mbno should start with 9

• Impose a restriction on a column dob in such a way that date must fall on either mon or wed or fri

Page 75: Oracle Sql & PLSQL Complete guide

Queries

• create table che1(age number check(age > 18))• create table ch2(mbno number check(length(mbno)

= 10))• create table ch3(mbno number, check((length(mbno)

= 10) and (substr(mbno, 1, 1) = 9)))• create table ch4(dob date check(to_char(dob, 'dy')

in('mon', 'wed', 'fri')))

Page 76: Oracle Sql & PLSQL Complete guide

Default

• This is a restriction which is used to over ride NULL value with a DEFAULT value

• Default value will be inserted whenever you are not entering data into any column of a table. But default value will not be inserted whenever you are explictly passing a NULL value

• Default keyword should be used in INSERT command if the table has only 1 column which had been defined under default restriction – create table def1(sno number, sname varchar2(20) default 'Ravi

Shankar')– create table def2(sno number, dob date default sysdate)– insert into def4 values(default);

Page 77: Oracle Sql & PLSQL Complete guide

Add constraints after creating a table

• alter table addcons add primary key(sno);• alter table cons3 add unique(sno);• alter table cons3 add check(sno > 101);• alter table cons4 modify(sno number not null);• alter table cons5 modify(age number default 18);

Page 78: Oracle Sql & PLSQL Complete guide

Table and col level constraints

• Table level constraints only can be added using ADD attribute of ALTER command and not Column level constraints

• Primary key, check and unique are called as table level constraints because they can be added using ADD attribute of ALTER command

• Not null and default are column level constraints and cannot be added using ADD attribute of ALTER command

• Not null and default constraints can be logically added using MODIFY attribute of ALTER command

Page 79: Oracle Sql & PLSQL Complete guide

Description of table and column level constraints

• Table level constraint– If the constraint type and column definition can appear at

different places in the same table then that constraint is referred to as a table level constraint

– create table cons6(cno number, cname varchar2(20), primary key(cno))

– create table cons7(sno number, sname varchar2(20), unique(sno));

– create table cons8(sno number, age number, check(sno > 101));

Page 80: Oracle Sql & PLSQL Complete guide

Contd..

• Column level constraint– Constraint definition and column definition must appear at the same

place in the same table

• The advantage with a table level constraint is that you can define a COMPOSITE PRIMARY KEY only by using table level constraints

• Composite primary key– When a primary key can be imposed on multiple columns in the same

table then that primary key is called as a composite primary key– create table cons8_edge(cid number, ano number, primary key(cid,

ano))

Page 81: Oracle Sql & PLSQL Complete guide

Constraint operations

• Delete a constraint without deleting a column from a table– alter table cons9 drop constraint SYS_C005256;– alter table cons9 drop primary key;– You cannot delete any other constraint without a name except for

primary key constraint

• Rename a constraint– alter table cons13 rename constraint SYS_C005261 to pk_cons13;

• Enable or disable primary key– alter table cons14 disable primary key– alter table cons14 enable primary key– alter table cons15 disable constraint SYS_C005263

Page 82: Oracle Sql & PLSQL Complete guide
Page 83: Oracle Sql & PLSQL Complete guide
Page 84: Oracle Sql & PLSQL Complete guide

Foreign key

• This is a constraint used for establishing table relationships • 2 tables can be related if a common column is defined in both

the tables • The common column should not be duplicated and should not

contain NULL values in that table from which it is borrowed as a common column

• Therefore a primary key column must be taken as a common column. Because primary key is a combination of UNIQUE and NOT NULL

• The table from which a primary key column is taken as a common column is called as a Master Table. The other table is called as a transaction table.

• Any table in which a foreign key column got reflected is called as a transaction table

Page 85: Oracle Sql & PLSQL Complete guide

Steps to implement a foreign key

• Create a master table– create table master1(cno number primary key, cname varchar2(20))

• Create a transaction table– create table trans1(sno number primary key, sname varchar2(20),

cno number references master1(cno))

• Deletion anamolies– You cannot delete data from the master table directly without

deleting the data from the transaction table because the foreign key column is referring to the primary key column

– In case you need to delete data from the master table directly then you should use a clause in the transaction table ON DELETE CASCADE

Page 86: Oracle Sql & PLSQL Complete guide

CONTD..

• On delete cascade– On deleting a row from the master table, the cascading

or automatic effect of deletion is reflected on transaction table

– create table master2(cno number primary key, cname varchar2(20))

– create table trans2(sno number primary key, sname varchar2(20), cno number references master2(cno) on delete cascade)

Page 87: Oracle Sql & PLSQL Complete guide

Contd..

• On delete set null– This clause should be used in the transaction table so that

if you delete a row from the master table, the corresponding column value in the transaction table will be updated to NULL without deleting a row and a column from that table

Page 88: Oracle Sql & PLSQL Complete guide
Page 89: Oracle Sql & PLSQL Complete guide

Contd..

• Add foreign key after creating a table– alter table trans4 add foreign key(cno) references master4(cno) on

delete cascade;

• In one transaction table, you can define more than 1 foreign key

• Foreign key column must and should be defined as a primary key (logical or physical)or as a unique key in the master table

• The names of the foreign key and primary key columns can be different but data type must be the same

Page 90: Oracle Sql & PLSQL Complete guide
Page 91: Oracle Sql & PLSQL Complete guide
Page 92: Oracle Sql & PLSQL Complete guide

JOINS• Joins is a technique of retrieving data from multiple tables by eliminating the cross

product of rows among tables • Equi join

– This type of join condition has to be defined whenever tables are related – = operator will be used to define a equi join

• Display the ename and dname from emp and dept tables – select ename, dname from emp, dept where emp.deptno = dept.deptno

• Display the ename and exp , dname of every emp– select ename, dname, extract(year from sysdate) - extract(year from

hiredate)exp from emp, dept where emp.deptno = dept.deptno• Display the ename and dname of those emps whose sal is > 2000

– select ename, dname, sal from emp, dept where emp.deptno = dept.deptno and sal > 2000

Page 93: Oracle Sql & PLSQL Complete guide

Non equi join

• This type of join condition will be defined whenever tables are not related

• Between and operator can be used to define a NON EQUI JOIN

• Display ename, sal and grade of every emp– select ename, sal, grade from emp, salgrade where sal between losal

and hisal order by grade asc– select emp_name.ename as emp_name, sal, grad.grade as grad from

emp emp_name, salgrade grad where sal between losal and hisal order by grad asc

Page 94: Oracle Sql & PLSQL Complete guide

Combination of equi and non equi joins

• Display the ename, dname and grade of every emp– select ename, dname, grade from emp, dept,

salgrade where emp.deptno = dept.deptno and sal between losal and hisal

• To join N tables, we need to define N – 1 join conditions

Page 95: Oracle Sql & PLSQL Complete guide

Alias names

• This is a temporary name that is used for a column for display purpose

• Syntax– Select <col name> <alias name> from <table name>;

• select ename emp_name from emp• select ename "emp_name" from emp

• Alias name and col name by default will be displayed in upper case. If you want the same case to be displayed then alias name should be provided in “ “

Page 96: Oracle Sql & PLSQL Complete guide

Contd..

• Define joins using alias names – select emp_name.ename as emp_name,

dept_name.dname as dept_name from emp emp_name, dept dept_name where emp_name.deptno = dept_name.deptno

• As keyword should be used to differentiate between the alias used for join and display purpose. As keyword is optional and is used only for readability

• Display the ename, dname and deptno from emp and dept tables – select ename, dname, emp.deptno from emp, dept where

emp.deptno = dept.deptno

Page 97: Oracle Sql & PLSQL Complete guide

Outer join

• This type of join condition has to be defined whenever you want to select all rows from 1 table and matching row from the other table

• + symbol has to be used adjacent to that table from where yu are selecting matching rows

• When you use + symbol on left side it is called as LEFT OUTER JOIN

• When you use + symbol on RIGHT side it is called as RIGHT OUTER JOIN– select ename ,dept.deptno, dname from emp, dept where

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

dept.deptno(+)

Page 98: Oracle Sql & PLSQL Complete guide

Self join

• Joining a table to itself – Manager_name is not a pre defined column of emp table– Manager_name can be logically obtained from emp name – Manager id of an emp must match with the empid of the manager– select emp_name.ename as emp_name, manager_name.ename as

manager_name from emp emp_name, emp manager_name where emp_name.mgr = manager_name.empno

– /

Page 99: Oracle Sql & PLSQL Complete guide

SUB QUERIES

Page 100: Oracle Sql & PLSQL Complete guide

Description

• It is a query within some other query• Display the details of those emps who are getting a sal > smith

– select * from emp where sal > (select sal from emp where ename = upper('smith'))

• Display the details of those emps whose experience is > than experience of ford – select ename, extract(year from sysdate) - extract(year from hiredate)

exp from emp where (extract(year from sysdate) - extract(year from hiredate)) > (select extract(year from sysdate) - extract(year from hiredate) from emp where ename = upper('ford'))

• Update the sal of allen to the same sal as that of smith– update emp set sal = (select sal from emp where ename =

upper('smith')) where ename = upper('allen')

Page 101: Oracle Sql & PLSQL Complete guide

Advantages with sub queries

• You can write a sub query to eliminate the problem encountered using GROUP BY CLAUSE

• You can create table copies and views using sub queries

Page 102: Oracle Sql & PLSQL Complete guide

Advantage 1

• Display the max(sal) from every department and also the name of that emp who is getting the max(sal)– select ename, sal, deptno from emp where sal

in(select max(sal) from emp group by deptno)

Page 103: Oracle Sql & PLSQL Complete guide

Table copies

• Create a table copy of emp table– create table empcopy as select * from emp

• Create a table copy without copying data from the base table– create table empcopy1 as select * from emp

where 1 = 2• Copy data from base table into table copy

– insert into empcopy1(select * from emp);

Page 104: Oracle Sql & PLSQL Complete guide

Table copies

• In table copies, constraints are not copied from the base table • Updations made on a table copy are not reflected on the base

table

Page 105: Oracle Sql & PLSQL Complete guide

View

• View is a virtual table which will be logically identified as an image of the base table

Emp table

oracleUser

View1

Update sal

Page 106: Oracle Sql & PLSQL Complete guide

Views contd..

• View is called as a virtual table because you cannot store data in a view

• Syntax for creating a view– Create view <view name> as <select statement>;

• Updations made on a table or on a view are reflected on the other data base object

• Create a view without a base table– create force view v2_abc as select * from abc

• When you delete a table on which a view is dependent then that view will become invalidated

Page 107: Oracle Sql & PLSQL Complete guide

Views contd…

• Create a view which will contain max sal from every dept– create view v4_emp as select deptno, max(sal) max_sal from emp

group by deptno– Alias name should be used because view is created only for pre

defined columns in a table and you cannot create a view with a column which is not existing in the table

– YView created with aggregate function is a read only view – View created with any other type of function is not a read only view

but you cannot make any updations on virtual columns(col existing in view but not in table) in that view

Page 108: Oracle Sql & PLSQL Complete guide

Views contd..

• With check option– This clause is used to define a condition in the where

clause of the select statement in a view definition as a constraint

• create view v9_emp as select empno, ename, sal from emp where sal > 2000 with check option

• Read only view• create view v11_emp as select empno, sal from emp with read only

• Create a view on a view– Create view <view name 2> as select <col> from <view name 1>

• Delete a view– drop view v13_emp;

Page 109: Oracle Sql & PLSQL Complete guide

Table copy View

updations made on a table copy are not reflected on the base table

Updations made on a view are reflected on the base table

Constraints are not copied into table copy

Constraints are copied into table copy

Physical Virtual

Page 110: Oracle Sql & PLSQL Complete guide

Oracle Data base

Tables

Views

Synonyms

Indexes

Sequences

Constraints

Procedures

Functions

Packag

Triggers

Varrays

Clusters

Page 111: Oracle Sql & PLSQL Complete guide

• Views can be used to track details about different types of data base objects which are stored in the data dictionary of the data base

Page 112: Oracle Sql & PLSQL Complete guide

Synonyms

• This is a permanent alias name through which you can access any data base object

• SYNTAX for creating a synonym● Create synonym <syn name> for [<user name>] . <table

name>;

– create synonym d1 for empcopy;

• Why to create synonyms?– Synonyms can be used to access a table if the table had been created

with a very long name

Page 113: Oracle Sql & PLSQL Complete guide
Page 114: Oracle Sql & PLSQL Complete guide
Page 115: Oracle Sql & PLSQL Complete guide

Sequences

• Sequence is a data base object which automatically generates numbers in a progression

• Syntax for creating a sequence– Create sequence <sequence name> [<start with> value] [minvalue

<value>] [ increment by <value>] [<maxvalue> value>] [cycle cache <value>];

• Attributes of sequence object– Nextval : this is an attribute which will be generating the next value

from the current value– Currval : Generates the current value of a sequence

• Select <sequence name>.<nextval> from <table name>;• Select <sequence name>.<currval> from <table name>;

• Current value of a sequence object will be stored in the cache memory

Page 116: Oracle Sql & PLSQL Complete guide

Contd…• Modify max value

– alter sequence s3 maxvalue 30– Maxvalue must be >= current value

• Start with value cannot be generated for more than once and suceeding the generation of the max value if you want to get back to the start with value, you should use a clause minvalue

• Cycle cache value = ((maxvalue) – (minvalue))/2• Remove cycle cache

– alter sequence s8 nocycle

• Add cycle cache– alter sequence s8 cycle cache 25

• Command for tracking sequence details– select sequence_name, min_value, max_value from user_sequences

where sequence_name = 'S8';

Page 117: Oracle Sql & PLSQL Complete guide

Contd..

• Min value must always be <= start with value• Add minvalue

– alter sequence s11 minvalue 2;– Minvalue must always be <= current value ie once a sequence object

is created, the default min value will be the start with value PROVIDED you did not define any start with value

• Add increment by value– alter sequence s13 increment by 20;

Page 118: Oracle Sql & PLSQL Complete guide

Use sequence in table

Page 119: Oracle Sql & PLSQL Complete guide

PL/SQL(PROCEDURALLANGUAGE

ORSQL )

Page 120: Oracle Sql & PLSQL Complete guide

Description

• Any language in which you can write programs is called as a procedural language

• Integrating SQL in a procedural language is called as PL/SQL

• Why to integrate SQL in a procedural language?– SQL is a non procedural query language which at times is a

disadvantage to a data base programmer due to which he cannot implement the data base flexibly because of the following cited reasons

Page 121: Oracle Sql & PLSQL Complete guide

Disadvantages with SQL

• SQL queries are not reusable because they cannot be stored in a data base

• SQL queries cannot abstract the data base object from outside world

• SQL queries degrade the performance of a data base

Emp User

Insert 20 rows

HDD

Page 122: Oracle Sql & PLSQL Complete guide

Contd..

• Hence because of the the above cited flaws in SQL, SQL has to be integrated in a procedural language

• We can integrate SQL in a procedural language by writing a program

• Programs can be written by using ANONYMOUS BLOCKS

• BLOCK is a unit which combines a procedural construct (variables, conditions, loops etc)with SQL statement

Page 123: Oracle Sql & PLSQL Complete guide

Structure of a BLOCKDeclare

<local variables >; Begin

<variable intializations>;<conditional statements>;<loop statements>;<SQL statements>;<output statements>;

Exception when <exception type> thenraise_application_error(errno, message);

End;

Page 124: Oracle Sql & PLSQL Complete guide

Output statement

• Dbms_output.put_line(message/variable/function);

• Dbms_output is a package and put_line is a procedure

Page 125: Oracle Sql & PLSQL Complete guide

Variables

• Declare variables– <variable name> <data type>;– SQL data types can be used to declare variables in PL/SQL – := is an assignment operator and = is a comparison operator

• Default value for a local variable in a block is NULL• Declare variable as not null

– <variable> <data type> not null := <value>;– A variable declared as not null must be intialized to a value only at the

place of declaration– When you declare a variable as not null, explicitly you cannot pass a

null value to be stored in that variable

Page 126: Oracle Sql & PLSQL Complete guide

Contd..

• Constant variable– Any variable for which a value cannot be modified is called as a

constant variable– <variable> constant <data type> := <value>;

• n constant number := 20;

• Commonality in not null and constant variables– Not null and constant variables have to be initialized to some value

only at the place of declaration

• Difference between constant and not null variables– Not null variables can be modified– Constant variables cannot be modified

• Default variable– <variable> <data type> default <value>;

Page 127: Oracle Sql & PLSQL Complete guide

Vars contd..

• Variables declared in the declaration section are always having a scope of LOCAL ie they are identified as LOCAL variables

Page 128: Oracle Sql & PLSQL Complete guide

If else

-- print max of 2 nosdeclare

n1 number := &num1;n2 number := &num2;

beginif(n1 > n2) then

dbms_output.put_line('max n1 = ' || n1);else

dbms_output.put_line('max n2 = ' || n2);end if;

end;/

Page 129: Oracle Sql & PLSQL Complete guide

Nested if else-- print max of 3 nos

declare

n1 number := &num1;

n2 number := &num2;

n3 number := &num3;

begin

if(n1 > n2 and n1 > n3)then

dbms_output.put_line('max n1 = ' || n1);

elsif(n2 > n1 and n2 > n3) then

dbms_output.put_line('max n2 = ' || n2);

else

dbms_output.put_line('max n3 = ' || n3);

end if;

end;

Page 130: Oracle Sql & PLSQL Complete guide

Syntax for case statement

Case when expression 1 then

Statement 1

when expression 2 then

Statement 2

When expression 3 then

Statement 3

End case;

Page 131: Oracle Sql & PLSQL Complete guide

loops (spec to oracle)

Loops are used for executing a piece of code for more than 1 time eg : reading 10 rows from a file, Insert multiplication tables in a file etc

3 types of loops

1. while loop

2. do while loop

3. for loop

syntax for defining a while loop

while(expression) loop

statement

end loop;

Page 132: Oracle Sql & PLSQL Complete guide

● Until the boolean value of the expression is true, the code within the body of while loop would execute

● WHILE loop will terminate when the boolean value in the expression is false

Page 133: Oracle Sql & PLSQL Complete guide

Case statementdeclare• text varchar2(20) := 'welcome to cmc';• choice number := &choice;• begin• case when choice = 1 then• text := upper(text);• when choice = 2 then• text := initcap(text);• when choice = 3 then• text := lpad(text, length(text) + 10, '@');• end case;• dbms_output.put_line('choice = ' || choice || ' and formatted text = '

|| text);• end;

Page 134: Oracle Sql & PLSQL Complete guide

Contd..

• When you compare a null value with a variable in a condition of a IF statement then the condition will always evaluate to FALSE and the ELSE part will get executed

• Cases can be duplicated and at any point of program execution, max only 1 case will be executed and in case of duplicate cases, first occurrence of the duplicated case would be executed

• Case constant can be a decimal value • Operators can also be used in case statements

Page 135: Oracle Sql & PLSQL Complete guide

LOOPS

Page 136: Oracle Sql & PLSQL Complete guide

While loop

-- print nos from 1 to 20 using while loopdeclare

n1 number := 1;begin

while(n1 <= 20) loopdbms_output.put_line('n1 = ' || n1);n1 := n1 + 1;

end loop;end;

Page 137: Oracle Sql & PLSQL Complete guide

Do while loop

● Syntax for defining a do while loop

loop● statements

Page 138: Oracle Sql & PLSQL Complete guide

Do while loop-- print nos from 1 to 20 using do while loopdeclare

n1 number := 1;begin

loopdbms_output.put_line('n1 = ' || n1);n1 := n1 + 1;exit when n1 > 20;

end loop;end;/

Page 139: Oracle Sql & PLSQL Complete guide

For loop

-- print nos from 1 to 20 using for loopbegin

for n1 in 1..20 loopdbms_output.put_line('n1 = ' || n1);

end loop;end;/

Page 140: Oracle Sql & PLSQL Complete guide

For loop

• Loop variable need not be declared, initialized and incremented in a FOR loop

• Using a for loop, we can print numbers in a reverse order without the need for decrementing a variable value

• User defined increment value cannot be identified in a for loop

Page 141: Oracle Sql & PLSQL Complete guide

While loop Do while loop

Loop will terminate when condition is false

Loop will terminate when the condition is true

Condition Negation of condition

Differences among while and do while loops

Page 142: Oracle Sql & PLSQL Complete guide

%type

• This is an attribute used for declaring variables in a block ie this attribute must be used whenever you are declaring variables to belong to the same type as that of a column in a table

• Syntax for using %type– <variable name> <table name> . <colname> % type

• The advantage of using this attribute is that changes made to the col size and type are automatically reflected in a variable of a block

Data type

Page 143: Oracle Sql & PLSQL Complete guide

Example

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

Page 144: Oracle Sql & PLSQL Complete guide

INTO operator

• This operator has to be used for copying data from a column into a variable

• Syntax for using this opeartor– Select <col name 1> into <variable 1> from <table name> where <col

name 2> = <variable 2>;

• Variable 1 is a variable that had been declared either for displaying a value or calculating a value for which already some value is available in a column of the table

• Variable 2 is a variable that is being used as an input variable• Select command in a block is only used for copying data from

a column into a variable and cannot be used for displaying data from a block

Page 145: Oracle Sql & PLSQL Complete guide

CURSORS

Page 146: Oracle Sql & PLSQL Complete guide

CODE

declarename emp.ename%type;

beginloop

select ename into name from emp;dbms_output.put_line(name);exit when name is null;

end loop;end;/

Page 147: Oracle Sql & PLSQL Complete guide

PROBLEM WITH THE CODE

• In the above code snippet, INTO operator cannot be used for copying multiple values from a column into a variable

• Hence we cannot use a block alone for displaying multiple rows

• Therefore we have to define CURSORS in a block for displaying multiple rows

Page 148: Oracle Sql & PLSQL Complete guide

Introduction to cursors

• Cursor is a private SQL area used for fetching the data from a table row wise. For every SQL statement issued by the user, a cursor will be created for that statement by the data base

• Cursor is private because user cannot create a cursor • Cursor is a SQL area because cursor will be created

by the data base only for SQL QUERIES issued by the user at run time

Page 149: Oracle Sql & PLSQL Complete guide

EMP TABLE

USER Select ename from

emp

ImplicitCursor

Pointer to 1st Row of a table

Fetch row into cursor

HOSTVARIABLES

Block

ExplicitCursor

Page 150: Oracle Sql & PLSQL Complete guide

Define explicit cursor

• Declare the cursor– Cursor <cursor name> is <select statement>;

• Open the cursor– Open <cursor name>;

• Fetch the data from a cursor into a local variable– Fetch <cursor name> into <local variable>;

• Close the cursor– Close <cursor name>;

Page 151: Oracle Sql & PLSQL Complete guide

Steps usage

• Open a cursor– Cursor has to be opened to execute the query identified in

the cursor declaration . Since opening a cursor enables a query to be executed, cursor has to be opened in the BEGIN section of a block

• Copy data from a cursor into a variable– Cursor is not a variable and user cannot directly access a

cursor. Hence data from a cursor has to be copied into a variable

Page 152: Oracle Sql & PLSQL Complete guide

Attributes of a cursor

• Syntax for using cursor attributes– <cursor name> %attribute

• %notfound– This attribute is used to verify whether data is available in a cursor or

not– This attribute will always return a BOOLEAN value. Default boolean

value for this attribute is always FALSE

• %rowcount– This attribute will validate a cursor with respect to the no of rows

available in a cursor ie using this attribute you can determine the no of rows available in a cursor

• %rowtype– This attribute is used to declare 1 variable for all the columns of a

table– Syntax of using this attribute

• <variable> <table name> %rowtype;

Page 153: Oracle Sql & PLSQL Complete guide

Contd..

• You cannot use a WHILE loop for using the attributes %notfound and %found because the default boolean values for these attributes are always false

• %rowcount can be used to display the no of rows fetched from a cursor into a variable

• Variable declared as %rowtype is only used to access all the columns of a table and that variable cannot store the data from all the columns of a table. That variable is called as a record set

• Local variables in a cursor have to be declared for– Display purpose– Calculation purpose

Page 154: Oracle Sql & PLSQL Complete guide

Advantages with cursor

• Cursor can be defined in a procedure or a function

• Select query can be declared in a cursor• Procedure or function can be stored in a data

base• Hence you can re use SELECT statement using

a procedure or a function through a cursor

Page 155: Oracle Sql & PLSQL Complete guide

EXCEPTION HANDLINGMECHANISMS

Page 156: Oracle Sql & PLSQL Complete guide

Description

• Exception is a mechanism for handling run time errors generated in a code

• Run time errors are generated because of– Invalid inputs given by the user– Incorrect logic of the program

• Exceptions can be raised using exception type. Exception type is a variable which is of type exception

• 2 types of exceptions can be used in Oracle Data base– System defined exception types– User defined exception types

Page 157: Oracle Sql & PLSQL Complete guide

Contd…

• System defined exception types are always used to only handle run time errors and you cannot use these exception types to throw run time errors

• If you want to create and throw a run time error then we need to make use of user defined exceptions

• System defined exceptions– zero_divide : This exception type has to be used whenever you want

to handle a run time error which will be generated because of dividing a number by 0

– No_data_found : This exception type has to be used whenever the code is throwing a run time error due to non availability of the data in a table

– Too_many_rows : This exception type has to be used whenever INTO operator is attempting to copy more than 1 value from a column into a variable

Page 158: Oracle Sql & PLSQL Complete guide

Raise_application_error(errno, message)• This is a procedure which can be called or used to display a

message like a error message• This procedure will accept 2 parameters. First parameter is

the error number and second parameter is a variable or function or text

• Error number must be provided as a first argument because. In oracle, every RUN TIME and COMPILE TIME errors is associated with a number

• Since the message to be rendered by this procedure is user defined, accordingly the error number must also be user defined

• Even though the error number is user defined, it must be within the range -20001 to -20990

Page 159: Oracle Sql & PLSQL Complete guide

Contd…

• This procedure can also be used in the BEGIN section of a block. In that case, exception section is not required for using this procedure

• But exception section would be mandatory to be used in case of user defined exceptions and exception section is mandatory to be used whenever you want to handle a specific run time error generated by a system

Page 160: Oracle Sql & PLSQL Complete guide

Zero_divide

declaren1 number := &n1;n2 number := &n2;

begindbms_output.put_line(n1||'/'||n2||'='||

(n1/n2));exception when zero_divide then

dbms_output.put_line('Denominator must not be 0...');end;/

Exception type

Page 161: Oracle Sql & PLSQL Complete guide

NO DATA FOUND

--write a block for reading eno and display the name of an empdeclare

eno emp.empno%type := &empno;name emp.ename%type;

beginselect ename into name from empwhere empno = eno;dbms_output.put_line(name||' is the name

of the emp whose empno = '||eno);exception when no_data_found then

raise_application_error(-20001, 'Empno = '||eno||' not existing in emp table...');end;/

Page 162: Oracle Sql & PLSQL Complete guide

Too many rows

declarename emp.ename%type;

beginselect ename into name from emp;dbms_output.put_line(name);

exception when too_many_rows thenraise_application_error(-20001, 'INTO OPERATOR CAN COPY

MAX ONLY 1 ROW FROM A COL INTO A VAR...');End;

Page 163: Oracle Sql & PLSQL Complete guide

User defined exceptions

• These exception types are used and defined for throwing user defined run time errors

• Steps to define a user defined exception– Declare the exception type in the declaration section of a block

• <exception variable> exception;– Raise the exception using a if condition

If(condition) then

statements;

Else

raise <exception variable>;

– Handle the exception using the exception section• Exception <exception var> then

Page 164: Oracle Sql & PLSQL Complete guide

Contd…

• Exception type has to be declared so that the exception type can be used in the exception section of a block

• Exception has to be raised for branching the control to the exception section of a block to throw the run time error

• You cannot handle multiple exceptions from a block. In case if you want to handle multiple exceptions then define them in a procedure and call those procedures from a block

Page 165: Oracle Sql & PLSQL Complete guide

Example 1-- write a block for adding 2 numbers. add those numbers if they are negative else do not add them

declare

n1 number := &num1;

n2 number := &num2;

res number;

inv_no exception; --exception var

begin

if(n1 < 0 and n2 < 0) then

res := n1 + n2;

dbms_output.put_line(n1||' + '||n2||' = '||res);

else

raise inv_no;

exception when inv_no then

raise_application_error(-20003, n1||' or ' || n2 || ' is positive...');

end;

Page 166: Oracle Sql & PLSQL Complete guide

Example 2--create table testexc1(dob date, age number)

declare

dob testexc1.dob%type := '&dob';

age testexc1.age%type;

inv_age exception;

begin

age := extract(year from sysdate) - extract(year from dob);

if(age > 18) then

insert into testexc1 values(dob, age);

dbms_output.put_line(dob||' and ' ||age||' got inserted into testexc1 table...');

else

raise inv_age;

end if;

exception when inv_age then

raise_application_error(-20001, 'age = '||age||' < 18 years because you were born on '||dob);

end;

Page 167: Oracle Sql & PLSQL Complete guide

Can you handle a system defined run time error using a user defined exception?

• If you want to handle a system defined run time error using a user defined exception type then you need to call the following procedure– Pragma exception_init(exception type, error no);

• Exception type is a user defined exception type and error no is a system generated error number

• This procedure has to be called in the DECLARE section of a block

Page 168: Oracle Sql & PLSQL Complete guide

Example 1• -- write a block for inserting empno into emp

table• declare• eno emp.empno%type := $empno;• dup_eno exception;• pragma exception_init(dup_eno, -00001);• begin• insert into emp(empno) values(eno);• dbms_output.put_line(eno||' got inserted into emp table...');• exception when dup_eno then• raise_application_error(-20001, eno||' already existing in emp table...');• end;

Page 169: Oracle Sql & PLSQL Complete guide

Functions

• Functions are used to store a cursor or an exception in a data base because functions themselves once compiled are stored permanently in a data base

• If you want to store a cursor or an exception in a function, we cannot make use of system defined functions. Hence we need to define a user defined function for that purpose

• Therefore we can make use of a function for code reusability because a block cannot be re usable for it cannot be stored in a data base

Page 170: Oracle Sql & PLSQL Complete guide

Syntax for defining or creating a function

Create [or replace] function <function name(args)> return <data type> is <return var> <data type>;Begin

Statements;

return <return variable>;

End [<function name>];

FunctionPrototype Or headerOr decalartion

Function defn

If you do not use replace keyword then theFunction can be compiled for max only 1 time ieRe compilation of the function is not possible

Page 171: Oracle Sql & PLSQL Complete guide

Call a function

• Select <function name(args)> from <table name>;– select fun1(10,20) from dept;

Page 172: Oracle Sql & PLSQL Complete guide

Functions return value• Function can be defined with 0 parameters and a return

variable of a function can be initialized to some value in case you are defining a function with 0 parameters. Do not use () if you are defining a function and calling it with 0 parameters

• You can define a function with no return variable ie you cannot define a function in such a way that it is not returning any value. But you can define a function in such a way that no return variable had been declared. Do not use ; at the end of the function declaration if you are defining a function with no return variable

• When you do not specify any size for varchar2 which is an argument type, you cannot specify any size for the return type. But a size has to be specified for varchar2 if it is a type of a return variable

Page 173: Oracle Sql & PLSQL Complete guide

Contd..

• You cannot define a size for varchar2 if it is a return type. If size for varchar2 as a return type cannot be specified then you cannot and should not specify a size for varchar2 as argument type

• You can define a loop in a function. But that function will max return only 1 value which is the initial value assigned to a variable

Page 174: Oracle Sql & PLSQL Complete guide

Varchar2 type as par, return types

● When a return var is declared of type varchar2 then size has to be specified for that return var

● Size should not be provided for varchar2 if it is a return type

● Size should not be provided for varchar2 if it is a par type

Page 175: Oracle Sql & PLSQL Complete guide
Page 176: Oracle Sql & PLSQL Complete guide
Page 177: Oracle Sql & PLSQL Complete guide
Page 178: Oracle Sql & PLSQL Complete guide

Advantages with functions

• Functions abstract the implementation from the outside world

• Functions reduce the complexity of implementing the application

• Functions can be re usable in a block• Whenever you are defining a function with INSERT or UPDATE

or DELETE commands then the function cannot be called from a SELECT statement. Instead the function has to be called from a block which is an advantage with a block to call a function

Page 179: Oracle Sql & PLSQL Complete guide

Disadvantages with functions

• You can define a cursor in a function. But that function will return max only 1 value from the first row of that table. Because functions max return only 1 value and cursor default position if the first row ie functions max return only 1 value which is the primary disadvantage

Page 180: Oracle Sql & PLSQL Complete guide

Command for tracking functions in a data base

• select text from user_source where name like 'FUN%‘– The above command will display the code written for

every function– User_source is a view of the data dictionary which is used

to track the details of functions, procedures and packages

Page 181: Oracle Sql & PLSQL Complete guide

Procedures Function Procedure

Function returns 1 value programmatically and logically

Procedure cannot return a value programmatically. But it can return more than 1 value logically

Function can be called from a procedure, function and a block

Procedure cannot be called from a function but can be called from a block or a procedure

Cursor defined in a function can fetch utmost only 1 row

Cursor defined in a procedure can fetch multiple rows

Functions accept only IN parameters Procedures accept IN, OUT and IN OUT parameters

Page 182: Oracle Sql & PLSQL Complete guide

• You cannot call a procedure from a function because procedure cannot programmatically return a value. You can call a function from a procedure because function can return a value programmatically and that return value can be used anywhere within the procedure

• You cannot assign a procedure to a variable because a procedure cannot return a value

Page 183: Oracle Sql & PLSQL Complete guide

Parameter types

• IN– This parameter type is passed as an argument to a function or a

procedure

• OUT– This a parameter type for which a value will be returned by the

procedure – Local variables are used to display values from a procedure logically .

But they cannot be qualified as OUT parameters

Page 184: Oracle Sql & PLSQL Complete guide

Contd…

• OUT parameters are not identified by a data base. Hence we have to register an OUT parameter with the data base.

• Step 1 : Declare a host variable which is of the same type as that of the OUT parameter. The variable is called as HOST variable because, it should be declared in a data base and not in a BLOCK or PROCEDURE or FUNCTION

– SQL> VAR <Variable name> <data type>

• HOST variable is declared so that the return value of the procedure can be stored in that variable

• Step 2 : Use that variable as a bind variable in the procedure call– Exec <procedure name>(<in1>, <in2>,……, :<host variable>);– If a variable is binded with the procedure call then that variable is

called as a bind variable– Variable has to be binded in order to store the return value of the

procedure in that variable

Page 185: Oracle Sql & PLSQL Complete guide

Contd..

• The advantage with OUT parameters is that you can re use OUT parameters in multiple procedures because you are registering an OUT parameter as a HOST variable and HOST variable is a variable declared in a data base.

• Hence that variable can be passed as a BIND variable in multiple procedures which is not possible with LOCAL variables

• Name of the HOST variable can be different from that of the name of an OUT parameter. Data types can also differ but they should be compatible

Page 186: Oracle Sql & PLSQL Complete guide
Page 187: Oracle Sql & PLSQL Complete guide

IN OUT parameters

• If a parameter value that is passed as a IN parameter needs t be modified within the procedure then that parameter can be declared as IN OUT parameter

• See the next slide to USE IN OUT parameters

Page 188: Oracle Sql & PLSQL Complete guide
Page 189: Oracle Sql & PLSQL Complete guide

PACKAGES

Page 190: Oracle Sql & PLSQL Complete guide

Description

• Package is a collection of procedures and functions, variables

• Why to define or create packages?– Packages are created for resolving the name conflicts

among functions and procedures – Packages can be used to aggregate the functionalities of

functions and procedures into a single unit so that you can just remember the name of the package instead of remembering the names of all functions and procedures

– Procedure created for 1 user cannot be publicly accessible from the other user privileges. But a package can be publicly accessible from every user privilege

Page 191: Oracle Sql & PLSQL Complete guide

Eno numberEname varchar2(20)Hiredate dateBasic numberDa numberHra numberCca numberGross numberNetsal number

Procedure forInserting data into the table

FunctionDA

FunctionGross

FunctionNetsal

FunctionHRA

Package

Page 192: Oracle Sql & PLSQL Complete guide

Java programTo open an

account in a bank

Customer

Account Data base

Procedure toInsert

account details

Call procedure

SCOTT

CREATE

No of programmers

are 20Write program

Page 193: Oracle Sql & PLSQL Complete guide

How to implement packages in ORACLE?

• STEP 1 : We have to create a package specification – Package specification can be thought of as a prototype for defining a

package ie functions and procedures will be declared in the package specification and will not be defined

– Return variable for a function will not be declared in a package specification because you are only declaring the function and not defining it

• STEP 2 : create a package body– Package body is used for defining the procedures and functions

declared in the package specification

Page 194: Oracle Sql & PLSQL Complete guide

Syntax for defining a package specification

Create [or replace ] package <package name> isFunction <function name(args)> return <data type>;Procedure <procedure name(args)>;<variable_spec> <data type>;End;

Page 195: Oracle Sql & PLSQL Complete guide

Package body

Create [or replace> package body <package name> is<variable_body> <data type>; function <function name(args)> return <data type> is <variable> <data type>;Begin

statements;return <variable>;

End;Procedure <procedure name(args)> isBegin

statements;End;End;

Page 196: Oracle Sql & PLSQL Complete guide

Members visibility in a package

• Variable or function or procedure declared in a package specification by default is having a public visibility ie that member can be accessed from outside the package specification

• Member visibility in a package body is private ie that member cannot be accessible from outside the package

• When you delete a package specification, by default even the package body will be deleted. If you delete a package body then the package specification by default will not be deleted

Page 197: Oracle Sql & PLSQL Complete guide

TRIGGERS

Page 198: Oracle Sql & PLSQL Complete guide

Description

• TRIGGER is an event which is fired implicitly whenever a DDL or a DML transaction takes place in a data base

• How to create a trigger?Create [or replace] trigger <trigger name> before / after

insert/update/delete on <table name> [of <col name>] for each row

Begin

Statements

End

Page 199: Oracle Sql & PLSQL Complete guide

EMP

DBA

InsertRows only onSAT or SUN

PROCEDURE

InsertData intoEmp table onSat or sun

User

Call

proc

edur

e

Error Mon to fri BlockInsert

Exception

INSERTCOMMAND ANY DAY

Page 200: Oracle Sql & PLSQL Complete guide

NORMALIZATION

Trigger syntax

● before/after : This is called as trigger timing and is used to tell the trigger when to fire

● Insert/update/delete : They are called as triggering events ie the events will tell the trigger to fire for a spcific DB transaction

● For each row : It is called as a trigger type. Trigger type will tell the trigger so as to how many times it has to fire

● There are 2 types of triggers that can fire :● Statement level trigger : this trigger will fire for 1 time for

all the rows ● Row level trigger(for each row) : this trigger will fire for 1

time for 1 row

Page 201: Oracle Sql & PLSQL Complete guide

Normalization

• The main goal of normalization is to reduce data redundancy in tables in a data base and it is recommended not to completely eliminate redundancy

• What is data redundancy?– Data redundancy = data duplication + data inconsistency– Data in a data base will become redundant if data is

becoming inconsistent because of duplication

Page 202: Oracle Sql & PLSQL Complete guide

Examine the tableSno Sname Phone no

10 Ravi shankar 100,200,300

20 James 101,201

30 Javed 202

40 Akhtar

50 Suresh 203

60 Styanedfra 204, 205

Page 203: Oracle Sql & PLSQL Complete guide

Contd..

• In the preceding table, At least 1 student is possessing more than 1 phone number. Hence for 1 row, we have to store multiple phone numbers in phone number column

• But any proprietary data base will be deployed in such a way that in any cell of a table, you can store max only 1 value in order to eliminate the anomalies caused due to INSERT or UPDATE or DELETE

• Deletion is a row wise operation. Hence one entire row will be deleted if you issue a delete command for deleting phone numbers of a student.

• Hence the problem encountered using delete command can be solved using Update command. Ie if you update phone number 100 to null then only 1 phone number will be deleted . But update command will be functional if and only if there is only 1 value in any cell of a table

Page 204: Oracle Sql & PLSQL Complete guide

Contd..

• Insert command would also throw a problem in the future whenever you are inserting data into that table

• Suppose you want to insert a row with sno = 60 for whom there are 2 mobile numbers and 3 columns in a table(sno, sname and phone number), we need to pass 4 values to the insert command which are identified as invalid no of arguments. Hence that row will not be inserted

• Hence whenever you are storing data in that table in such a way that one column is accommodating multiple values for a particular row, then that column would be responsible for causing anomalies in INSERT, UPDATE and DELETE

• Therefore the presence of multi valued attributes in a table are causing problems to INSERT, UPDATE and DELETE commands

Page 205: Oracle Sql & PLSQL Complete guide

Multi valued attributes

• Multi valued attribute : When a column is storing multiple values for a particular row then that column is called as a multi valued attribute

• In our example, phone no column can be qualified as multi valued attribute because this column is storing multiple phone numbers for a particular row

• Multi valued attributes will be responsible for causing anomalies in INSERT, UPDATE and DELETE commands

Page 206: Oracle Sql & PLSQL Complete guide

Solutions to the problems faced due to multi valued attributes

• Solution 1 : Ensure that phone number column is storing max only one phone number for every row

Sno Sname Phone no

10 Ravi shankar 100

10 Ravi shankar 200

10 Ravi shankar 300

20 Javed 101

20 Javed 102

30 Akhtar NULL

Page 207: Oracle Sql & PLSQL Complete guide

Problem with solution1

• Sno column will be duplicated because of phone number column.

• Hence sno column cannot be defined as a primary key. Sno column must be defined as a primary key because you need to uniquely identify a row using primary key

• Phone no column cannot be defined as a primary key because it is not mandatory for every student to have a phone number. Hence a NULL value will be entered into that column for which a student is not possesing a phone number. Primary key cannot accept NULL values

• Hence this solution is not effective to solve the problem of multi valued attributes

Page 208: Oracle Sql & PLSQL Complete guide

Solution 2

• Define one independent column for every phone number of a particular student

Sno Sname Ph1 Ph2 Ph3

10 Ravi 100 200 300

20 James 101 102

30 Javed 103

40 Akhtar

Page 209: Oracle Sql & PLSQL Complete guide

Problem with solution 2

• This solution is not effective due to the following reasons– If you want to insert a row for which that student is

possessing 7 phone numbers then you need to add 4 columns to the existing table. Hence for every data updation, I need to modify the table structure

– In this connection, the user needs to directly access the table in a data base which may be a threat to the security and performance of the data base application

Page 210: Oracle Sql & PLSQL Complete guide

Solution 3

• Do not create phone number column or tell the student to maintain max only 1 phone number– This is a best solution from the programmar’s angle and a

worst solution from the customers angle– Main goal of sotware development is to satisfy customer– Hence this solution is not acceptable ]

• Hence the solution to solve the problem is that– one row should accommodate only 1 phone number– Sno should not be duplicated– Additional columns should not be added

Page 211: Oracle Sql & PLSQL Complete guide

Conclusion

• Data redundancy in a table is caused due to the presence of multi valued attributes

• Hence to reduce data redundancy, we need to normalize the table

• You should not eliminate data redundancy because if data redundancy is totally eliminated then tables cannot be related

Page 212: Oracle Sql & PLSQL Complete guide

NORMALIZATION

• This is a process of decomposing 1 table into multiple tables to reduce data redundancy

• This process has to be implemented before creating tables in ORACLE data base

• Hence this process is an activity of DATA BASE DESIGN• NORMALIZATION process can be identified to be

implemented through the presence of MULTI VALUED ATTRIBUTES

• MULTI VALUED ATTRIBUTES can be identified using ER DIAGRAMS

Page 213: Oracle Sql & PLSQL Complete guide

Sno Sname Major Cno Cname FN Fl Grade

101 RAVI JAVA 101102103

CppOracleMs.net

AmirAmir venkat

Hyd Hydsecbad

ABA

102 Shankar MAIN FRAMES

104105

SEMATHS

AmirSatish

Secbad Secbad

AA

Assumption : One faculty can max handle only 1 course Faculty name must be unique

Page 214: Oracle Sql & PLSQL Complete guide

First normal form• When you encounter multi valued attributes in a table then

those attributes have to be identified in a second table ie 1 table has to be decomposed into 2 tables. 1 table comprising of single valued attributes and second table comprising of multi valued attributes – Table 1 = {sno, sname, major} single valued attributes – Table 2 = {sno, cno, cname, FN, FL, grade} multi valued attributes

• Table 1 and Table 2 must be related because both these table initially belonged to only 1 table. 2 tables can be related by taking a primary key column as a common column

• Sno and cno are primary key columns in the respective tables. But cno cannot be defined as a common column because it is a multi valued attribute. Hence sno must be defined as a common column

Page 215: Oracle Sql & PLSQL Complete guide

SNO

CNO

Table 2 = {sno, cno, cname, FN, FL, grade} multi valued attributes

CNAME

FN FL

Grade

Table 3

Table 4`

Full functionalDependency

Partial functionalDependency

Page 216: Oracle Sql & PLSQL Complete guide

Second normal form

• In 1 table if you encounter full functional and partial functional dependencies then that table has to be decomposed into 2 tables. 1 table comprising of full functional dependency and second table comprising of partial functional dependency

• Table 3 = {sno, cno, grade} full functional dependency• Table 4 = {cno, cname, FN, FL} Partial functional dependency

Page 217: Oracle Sql & PLSQL Complete guide

THIRD NORMAL FORM

• In table 4 cname and FN are directly dependent on CNO. But FL is indirectly dependent on CNO through FN ie FL is dependent on FN and CNO which is a transitive dependency

• Hence decompose table 4 into 2 tables – Functional dependency– Transitive dependency

• Table 5 ={ cno, cname, IN }• Table 6 = {IN, IL}

Page 218: Oracle Sql & PLSQL Complete guide

Updated tables

• Table A = {sno, sname, major}• Table B = {sno, cno, grade}• Table C ={ cno, cname, IN }• Table D = {IN, IL}

Page 219: Oracle Sql & PLSQL Complete guide

Normal form Table 1 Table 2

First Single values attributes Multi Valued Attributes

Second Full functional dependency

Partial Functional Dependency

Third Full functional dependency

Transitive Dependency

In any normal form 1 table will be deocmposed into 2 tables

Page 220: Oracle Sql & PLSQL Complete guide

● Full functional dependency● Non key column is totally dependent on a composite

primary key. If the table has only 1 primary key then also it is called as a full functional dependency

● Partial functional dependency● Non key column is partly depedent on a composite primary

key● Transitive dependency

● It is a dependency between non key columns

Page 221: Oracle Sql & PLSQL Complete guide

Basic terms

● Data ● Is A COLLECTION of RAW FACTS and FIGURES

● DATA BASE● Data has to be stored in a data base for extracting useful

infromation from it● Data base can either be designed or data base can be

borrowed from any body for storing data

Page 222: Oracle Sql & PLSQL Complete guide

● Data base design must comply to the user's requirement ie any type of application that is to be developed requires a data base also to be designed

● Data base can be designed using FILES system .

● Data base can be designed using a FILE system but FILES have some disadvanatages

● Files cannot be distributed ● Data stored in a file is always redundant ie data can be duplicated in a

file which will lead to data inconsistency and there is no provision in a C compiler to reduce or eliminate data redundancy which is the main problem with a file system

● In c compiler, you can store data only in text files and text files cannot be distributed or updated

Page 223: Oracle Sql & PLSQL Complete guide

● Due to the disadvantages in file systems, programmars felt the need of using a data base that can offer security, re usability of data. With that thought in mind they felt that if data is stored in tables when compared to that of files the above requirements can be achieved

● Advantages with tables

● Data can be stored in any manner in a table● Table can be implemented as a object but file cannot be

implemented as an object● Hence companies like IBM in the year 1992 developed it's own data

base called as DB2 and this was possible for IBM because of the standard of tables in a data base

Page 224: Oracle Sql & PLSQL Complete guide

● A language was required for maintaining DB2 data base. That language also was standardized by IBM in the same year referred to as SQL

● SQL is a non procedural 3rd generation query language . SQL was implemented by using some commands and was not implemented using programs ie SQL commands can be used for DB maintenance and operations and for that you need not write any programs

● Oracle company also started intergrating SQL into their DB products and happened to standardize a product namely ORACLE

Page 225: Oracle Sql & PLSQL Complete guide

Oracle

● Why the name oracle was standardized?● Oracle is not only a data base but also a relational data

base (Any data base that can be designed using tables is called as a relational data base)

● Oracle is a Relational Data Base Management System(till oracle 8) ie from oracle 9i onwards It was qualified as OBJECT RELATIONAL DATA BASE MANAGEMENT SYSTEM

● ORACLE is a data base server