SlideShare a Scribd company logo
1 of 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
Web site
For a bank
User
Open account
Account
Data base
Java
C program
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));
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;
• 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
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
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');
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
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
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;
DELETE
• This command is used for deleting specific or all the rows
from a table
• Syntax
– Delete from <table name> [where <condition>];
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/
DROP
• This command can be used for permanently
deleting the table from a data base
• Syntax
– Drop table <table name>;
• drop table stud_test;
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)
OPERATORS
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
SQL OPERATORS
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
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
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
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')
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%';
• 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%'
FUNCTIONS
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
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>;
System defined functions
• Number functions
• String functions
• Date and time functions
• Conversion functions
• Aggregate functions
NUMBER FUNCTIONS
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
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
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
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
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
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
Abs(arg1)
• This function will convert a –ve number into a
+ve number
• Arg1 can be +ve or -ve
STRING FUNCTIONS
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
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
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
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;
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
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
Contd..
• select lpad('kumar', 8, 'Mr.’) from dept
• select rpad('kumar', 15, '*') from dept;
• select lpad(job, length(job) + 10, '$') from emp
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;
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
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
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
Reverse(arg1)
• This function will reverse a string or a number
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
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
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
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;
CONVERSION FUNCTIONS
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 “ “
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
/
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
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
Aggregate functions
• Sum(a1)
• Avg(a1)
• Min(a1)
• Max(a1)
• Count(a1)
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
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
Clauses in select statement
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
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
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
• 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
– /
CONSTRAINTS
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
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
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
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.
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);
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
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')))
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);
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);
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
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));
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))
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
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
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
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)
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
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
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
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
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
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 “ “
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
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(+)
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
– /
SUB QUERIES
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')
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
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)
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);
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
View
• View is a virtual table which will be logically
identified as an image of the base table
Emp table
oracleUser
View1
Update sal
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
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
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;
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
Oracle
Data base
Tables
Views
Synonyms
Indexes
Sequences
Constraints
Procedures
Functions
Packag
Triggers
Varrays
Clusters
• 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
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
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
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';
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;
Use sequence in table
PL/SQL(PROCEDURAL
LANGUAGE
OR
SQL )
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
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
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
Structure of a BLOCK
Declare
<local variables >;
Begin
<variable intializations>;
<conditional statements>;
<loop statements>;
<SQL statements>;
<output statements>;
Exception when <exception type> then
raise_application_error(errno, message);
End;
Output statement
• Dbms_output.put_line(message/variable/func
tion);
• Dbms_output is a package and put_line is a
procedure
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
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>;
Vars contd..
• Variables declared in the declaration section are always
having a scope of LOCAL ie they are identified as LOCAL
variables
If else
-- print max of 2 nos
declare
n1 number := &num1;
n2 number := &num2;
begin
if(n1 > n2) then
dbms_output.put_line('max n1 = ' || n1);
else
dbms_output.put_line('max n2 = ' || n2);
end if;
end;
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;
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;
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;
●
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
Case statement
declare
• 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;
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
LOOPS
While loop
-- print nos from 1 to 20 using while loop
declare
n1 number := 1;
begin
while(n1 <= 20) loop
dbms_output.put_line('n1 = ' || n1);
n1 := n1 + 1;
end loop;
end;
Do while loop
●
Syntax for defining a do while loop
loop
●
statements
Do while loop
-- print nos from 1 to 20 using do while loop
declare
n1 number := 1;
begin
loop
dbms_output.put_line('n1 = ' || n1);
n1 := n1 + 1;
exit when n1 > 20;
end loop;
end;
For loop
-- print nos from 1 to 20 using for loop
begin
for n1 in 1..20 loop
dbms_output.put_line('n1 = ' || n1);
end loop;
end;
/
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
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
%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
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;
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
CURSORS
CODE
declare
name emp.ename%type;
begin
loop
select ename into name from emp;
dbms_output.put_line(name);
exit when name is null;
end loop;
end;
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
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
EMP
TABLE
USER Select
ename from
emp
Implicit
Cursor
Pointer to 1st
Row of a table
Fetch row into cursor
HOST
VARIABLES
Block
Explicit
Cursor
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>;
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
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
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
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
EXCEPTION HANDLING
MECHANISMS
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
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
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
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
Zero_divide
declare
n1 number := &n1;
n2 number := &n2;
begin
dbms_output.put_line(n1||'/'||n2||'='||
(n1/n2));
exception when zero_divide then
dbms_output.put_line('Denominator must
not be 0...');
Exception type
NO DATA FOUND
--write a block for reading eno and display the
name of an emp
declare
eno emp.empno%type := &empno;
name emp.ename%type;
begin
select ename into name from emp
where empno = eno;
dbms_output.put_line(name||' is the name
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, 'INTO OPERATOR CAN COPY
MAX ONLY 1 ROW FROM A COL INTO A VAR...');
End;
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
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
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...');
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);
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
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;
•
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
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>];
Function
Prototype
Or header
Or decalartion
Function defn
If you do not use replace keyword then the
Function can be compiled for max only 1 time ie
Re compilation of the function is not possible
Call a function
• Select <function name(args)> from <table name>;
– select fun1(10,20) from dept;
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
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
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
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
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
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
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
• 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
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
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
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
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
PACKAGES
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
Eno number
Ename varchar2(20)
Hiredate date
Basic number
Da number
Hra number
Cca number
Gross number
Netsal number
Procedure for
Inserting data
into the table
Function
DA
Function
Gross
Function
Netsal
Function
HRA
Package
Java program
To open an
account in a bank
Customer
Account
Data base
Procedure to
Insert
account
details
Call procedure
SCOTT
CREATE
No of
programmers
are 20
Write program
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
Syntax for defining a package specification
Create [or replace ] package <package name> is
Function <function name(args)> return <data type>;
Procedure <procedure name(args)>;
<variable_spec> <data type>;
End;
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)> is
Begin
statements;
End;
End;
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
TRIGGERS
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
EMP
DBA
Insert
Rows only on
SAT or SUN
PROCEDURE
Insert
Data into
Emp table on
Sat or sun
User
Callprocedure
ErrorMon to fri Block
Insert
Exception
INSERT
COMMANDANY DAY
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
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
Examine the table
Sno 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
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
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
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
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
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
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
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
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
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
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
Sno Sname Major Cno Cname FN Fl Grade
101 RAVI JAVA 101
102
103
Cpp
Oracle
Ms.net
Amir
Amir
venkat
Hyd
Hyd
secbad
A
B
A
102 Shankar MAIN
FRAMES
104
105
SE
MATHS
Amir
Satish
Secbad
Secbad
A
A
Assumption : One faculty can max handle only 1 course
Faculty name must be unique
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
SNO
CNO
ble 2 = {sno, cno, cname, FN, FL, grade}  multi valued attributes
CNAME
FNFL
Grade
Table
3
Table
4`
Full functional
Dependency
Partial functional
Dependency
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
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}
Updated tables
• Table A = {sno, sname, major}
• Table B = {sno, cno, grade}
• Table C ={ cno, cname, IN }
• Table D = {IN, IL}
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
●
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
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
●
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
●
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
●
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
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

More Related Content

What's hot (20)

Normalization in DBMS
Normalization in DBMSNormalization in DBMS
Normalization in DBMS
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Plsql
PlsqlPlsql
Plsql
 
Packages - PL/SQL
Packages - PL/SQLPackages - PL/SQL
Packages - PL/SQL
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Oracle Index
Oracle IndexOracle Index
Oracle Index
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
SQL - DML and DDL Commands
SQL - DML and DDL CommandsSQL - DML and DDL Commands
SQL - DML and DDL Commands
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
Sql Functions And Procedures
Sql Functions And ProceduresSql Functions And Procedures
Sql Functions And Procedures
 
SQL BASIC QUERIES
SQL  BASIC QUERIES SQL  BASIC QUERIES
SQL BASIC QUERIES
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
 

Viewers also liked

Oracle database Career paths - Introduction
Oracle database Career paths - IntroductionOracle database Career paths - Introduction
Oracle database Career paths - IntroductionMyOnlineITCourses
 
White Paper, How to improve your Oracle career
White Paper, How to improve your Oracle careerWhite Paper, How to improve your Oracle career
White Paper, How to improve your Oracle careerFrancisco Alvarez
 
Oracle apps-interview-questions
Oracle apps-interview-questionsOracle apps-interview-questions
Oracle apps-interview-questionsPakeera Mekala
 
Becoming a Better Developer #WCA2
Becoming a Better Developer #WCA2Becoming a Better Developer #WCA2
Becoming a Better Developer #WCA2Brian Richards
 
A Beginners Guide to noSQL
A Beginners Guide to noSQLA Beginners Guide to noSQL
A Beginners Guide to noSQLMike Crabb
 

Viewers also liked (11)

Oracle SQL Self Study
Oracle SQL Self StudyOracle SQL Self Study
Oracle SQL Self Study
 
Oracle database Career paths - Introduction
Oracle database Career paths - IntroductionOracle database Career paths - Introduction
Oracle database Career paths - Introduction
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
White Paper, How to improve your Oracle career
White Paper, How to improve your Oracle careerWhite Paper, How to improve your Oracle career
White Paper, How to improve your Oracle career
 
Oracle apps-technical-tutorial
Oracle apps-technical-tutorialOracle apps-technical-tutorial
Oracle apps-technical-tutorial
 
Oracle apps-interview-questions
Oracle apps-interview-questionsOracle apps-interview-questions
Oracle apps-interview-questions
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
Becoming a Better Developer #WCA2
Becoming a Better Developer #WCA2Becoming a Better Developer #WCA2
Becoming a Better Developer #WCA2
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
The Programmer
The ProgrammerThe Programmer
The Programmer
 
A Beginners Guide to noSQL
A Beginners Guide to noSQLA Beginners Guide to noSQL
A Beginners Guide to noSQL
 

Similar to Oracle Sql & PLSQL Complete guide

Similar to Oracle Sql & PLSQL Complete guide (20)

Array
ArrayArray
Array
 
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek SharmaIntroduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 
Practical 03 (1).pptx
Practical 03 (1).pptxPractical 03 (1).pptx
Practical 03 (1).pptx
 
Arrays_and_Strings_in_C_Programming.pptx
Arrays_and_Strings_in_C_Programming.pptxArrays_and_Strings_in_C_Programming.pptx
Arrays_and_Strings_in_C_Programming.pptx
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
DBMS.pptx
DBMS.pptxDBMS.pptx
DBMS.pptx
 
Sql Tutorials
Sql TutorialsSql Tutorials
Sql Tutorials
 
OracleSQLraining.pptx
OracleSQLraining.pptxOracleSQLraining.pptx
OracleSQLraining.pptx
 
SQL LECTURE.pptx
SQL LECTURE.pptxSQL LECTURE.pptx
SQL LECTURE.pptx
 
Java class 8
Java class 8Java class 8
Java class 8
 
Sql server
Sql serverSql server
Sql server
 
Structured Query Language (SQL) - An Introduction
Structured Query Language (SQL) - An IntroductionStructured Query Language (SQL) - An Introduction
Structured Query Language (SQL) - An Introduction
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.ppt
 
MS SQL Server.ppt
MS SQL Server.pptMS SQL Server.ppt
MS SQL Server.ppt
 
Table functions - Planboard Symposium 2013
Table functions - Planboard Symposium 2013Table functions - Planboard Symposium 2013
Table functions - Planboard Symposium 2013
 

More from Raviteja Chowdary Adusumalli (14)

Testing fundamentals
Testing fundamentalsTesting fundamentals
Testing fundamentals
 
Softskill brief description,the way to change our attitude
Softskill brief description,the way to change our attitudeSoftskill brief description,the way to change our attitude
Softskill brief description,the way to change our attitude
 
Introduction to phishing
Introduction to phishingIntroduction to phishing
Introduction to phishing
 
Computer viruses
Computer virusesComputer viruses
Computer viruses
 
Brain fingerprinting tech
Brain fingerprinting techBrain fingerprinting tech
Brain fingerprinting tech
 
Geographic inf system
Geographic inf systemGeographic inf system
Geographic inf system
 
Peer to peer
Peer to peerPeer to peer
Peer to peer
 
Ethical hacking (2)
Ethical hacking (2)Ethical hacking (2)
Ethical hacking (2)
 
Brain gate
Brain gateBrain gate
Brain gate
 
Free space optics
Free space opticsFree space optics
Free space optics
 
Wearable computer
Wearable computerWearable computer
Wearable computer
 
Image processing ppt
Image processing pptImage processing ppt
Image processing ppt
 
Wimax
WimaxWimax
Wimax
 
Surface computing by raviteja
Surface computing by ravitejaSurface computing by raviteja
Surface computing by raviteja
 

Recently uploaded

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Recently uploaded (20)

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Oracle Sql & PLSQL Complete guide

  • 1. 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
  • 2. Web site For a bank User Open account Account Data base Java C program
  • 3. 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));
  • 4. 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;
  • 5. • 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
  • 6. 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
  • 7. 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');
  • 8. 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
  • 9. 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
  • 10. 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;
  • 11. DELETE • This command is used for deleting specific or all the rows from a table • Syntax – Delete from <table name> [where <condition>];
  • 12. 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/
  • 13. DROP • This command can be used for permanently deleting the table from a data base • Syntax – Drop table <table name>; • drop table stud_test;
  • 14. 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)
  • 16. 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
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. 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')
  • 22. 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%';
  • 23. • 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%'
  • 25. 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
  • 26. 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>;
  • 27. System defined functions • Number functions • String functions • Date and time functions • Conversion functions • Aggregate functions
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. Abs(arg1) • This function will convert a –ve number into a +ve number • Arg1 can be +ve or -ve
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. 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;
  • 41. 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
  • 42. 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
  • 43. Contd.. • select lpad('kumar', 8, 'Mr.’) from dept • select rpad('kumar', 15, '*') from dept; • select lpad(job, length(job) + 10, '$') from emp
  • 44. 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;
  • 45. 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
  • 46. 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
  • 47. 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
  • 48. Reverse(arg1) • This function will reverse a string or a number
  • 49. 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
  • 50. 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
  • 51. 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
  • 52. 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;
  • 54. 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 “ “
  • 55. 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 /
  • 56. 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
  • 57. 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
  • 58. Aggregate functions • Sum(a1) • Avg(a1) • Min(a1) • Max(a1) • Count(a1)
  • 59.
  • 60.
  • 61. 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
  • 62. 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
  • 63. Clauses in select statement
  • 64. 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
  • 65. 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
  • 66. 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
  • 67. • 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 – /
  • 69. 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
  • 70. 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
  • 71. 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
  • 72. 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.
  • 73. 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);
  • 74. 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
  • 75. 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')))
  • 76. 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);
  • 77. 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);
  • 78. 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
  • 79. 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));
  • 80. 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))
  • 81. 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
  • 82.
  • 83.
  • 84. 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
  • 85. 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
  • 86. 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)
  • 87. 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
  • 88.
  • 89. 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
  • 90.
  • 91.
  • 92. 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
  • 93. 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
  • 94. 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
  • 95. 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 “ “
  • 96. 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
  • 97. 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(+)
  • 98. 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 – /
  • 100. 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')
  • 101. 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
  • 102. 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)
  • 103. 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);
  • 104. 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
  • 105. View • View is a virtual table which will be logically identified as an image of the base table Emp table oracleUser View1 Update sal
  • 106. 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
  • 107. 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
  • 108. 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;
  • 109. 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
  • 111. • 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
  • 112. 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
  • 113.
  • 114.
  • 115. 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
  • 116. 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';
  • 117. 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;
  • 118. Use sequence in table
  • 120. 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
  • 121. 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
  • 122. 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
  • 123. Structure of a BLOCK Declare <local variables >; Begin <variable intializations>; <conditional statements>; <loop statements>; <SQL statements>; <output statements>; Exception when <exception type> then raise_application_error(errno, message); End;
  • 124. Output statement • Dbms_output.put_line(message/variable/func tion); • Dbms_output is a package and put_line is a procedure
  • 125. 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
  • 126. 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>;
  • 127. Vars contd.. • Variables declared in the declaration section are always having a scope of LOCAL ie they are identified as LOCAL variables
  • 128. If else -- print max of 2 nos declare n1 number := &num1; n2 number := &num2; begin if(n1 > n2) then dbms_output.put_line('max n1 = ' || n1); else dbms_output.put_line('max n2 = ' || n2); end if; end;
  • 129. 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;
  • 130. 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;
  • 131. 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;
  • 132. ● 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
  • 133. Case statement declare • 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;
  • 134. 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
  • 135. LOOPS
  • 136. While loop -- print nos from 1 to 20 using while loop declare n1 number := 1; begin while(n1 <= 20) loop dbms_output.put_line('n1 = ' || n1); n1 := n1 + 1; end loop; end;
  • 137. Do while loop ● Syntax for defining a do while loop loop ● statements
  • 138. Do while loop -- print nos from 1 to 20 using do while loop declare n1 number := 1; begin loop dbms_output.put_line('n1 = ' || n1); n1 := n1 + 1; exit when n1 > 20; end loop; end;
  • 139. For loop -- print nos from 1 to 20 using for loop begin for n1 in 1..20 loop dbms_output.put_line('n1 = ' || n1); end loop; end; /
  • 140. 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
  • 141. 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
  • 142. %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
  • 143. 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;
  • 144. 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
  • 146. CODE declare name emp.ename%type; begin loop select ename into name from emp; dbms_output.put_line(name); exit when name is null; end loop; end;
  • 147. 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
  • 148. 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
  • 149. EMP TABLE USER Select ename from emp Implicit Cursor Pointer to 1st Row of a table Fetch row into cursor HOST VARIABLES Block Explicit Cursor
  • 150. 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>;
  • 151. 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
  • 152. 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
  • 153. 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
  • 154. 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
  • 156. 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
  • 157. 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
  • 158. 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
  • 159. 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
  • 160. Zero_divide declare n1 number := &n1; n2 number := &n2; begin dbms_output.put_line(n1||'/'||n2||'='|| (n1/n2)); exception when zero_divide then dbms_output.put_line('Denominator must not be 0...'); Exception type
  • 161. NO DATA FOUND --write a block for reading eno and display the name of an emp declare eno emp.empno%type := &empno; name emp.ename%type; begin select ename into name from emp where empno = eno; dbms_output.put_line(name||' is the name
  • 162. 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, 'INTO OPERATOR CAN COPY MAX ONLY 1 ROW FROM A COL INTO A VAR...'); End;
  • 163. 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
  • 164. 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
  • 165. 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...');
  • 166. 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);
  • 167. 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
  • 168. 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; •
  • 169. 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
  • 170. 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>]; Function Prototype Or header Or decalartion Function defn If you do not use replace keyword then the Function can be compiled for max only 1 time ie Re compilation of the function is not possible
  • 171. Call a function • Select <function name(args)> from <table name>; – select fun1(10,20) from dept;
  • 172. 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
  • 173. 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
  • 174. 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
  • 175.
  • 176.
  • 177.
  • 178. 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
  • 179. 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
  • 180. 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
  • 181. 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
  • 182. • 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
  • 183. 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
  • 184. 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
  • 185. 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
  • 186.
  • 187. 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
  • 188.
  • 190. 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
  • 191. Eno number Ename varchar2(20) Hiredate date Basic number Da number Hra number Cca number Gross number Netsal number Procedure for Inserting data into the table Function DA Function Gross Function Netsal Function HRA Package
  • 192. Java program To open an account in a bank Customer Account Data base Procedure to Insert account details Call procedure SCOTT CREATE No of programmers are 20 Write program
  • 193. 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
  • 194. Syntax for defining a package specification Create [or replace ] package <package name> is Function <function name(args)> return <data type>; Procedure <procedure name(args)>; <variable_spec> <data type>; End;
  • 195. 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)> is Begin statements; End; End;
  • 196. 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
  • 198. 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
  • 199. EMP DBA Insert Rows only on SAT or SUN PROCEDURE Insert Data into Emp table on Sat or sun User Callprocedure ErrorMon to fri Block Insert Exception INSERT COMMANDANY DAY
  • 200. 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
  • 201. 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
  • 202. Examine the table Sno 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
  • 203. 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
  • 204. 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
  • 205. 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
  • 206. 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
  • 207. 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
  • 208. 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
  • 209. 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
  • 210. 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
  • 211. 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
  • 212. 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
  • 213. Sno Sname Major Cno Cname FN Fl Grade 101 RAVI JAVA 101 102 103 Cpp Oracle Ms.net Amir Amir venkat Hyd Hyd secbad A B A 102 Shankar MAIN FRAMES 104 105 SE MATHS Amir Satish Secbad Secbad A A Assumption : One faculty can max handle only 1 course Faculty name must be unique
  • 214. 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
  • 215. SNO CNO ble 2 = {sno, cno, cname, FN, FL, grade}  multi valued attributes CNAME FNFL Grade Table 3 Table 4` Full functional Dependency Partial functional Dependency
  • 216. 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
  • 217. 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}
  • 218. Updated tables • Table A = {sno, sname, major} • Table B = {sno, cno, grade} • Table C ={ cno, cname, IN } • Table D = {IN, IL}
  • 219. 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
  • 220. ● 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
  • 221. 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
  • 222. ● 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
  • 223. ● 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
  • 224. ● 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
  • 225. 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