Oracle SQL Concepts
Oracle SQL Concepts
1
Introduction to DBMS
What is Data ?
-- Facts, figures, statistics etc. having no particular meaning
2
Introduction to DBMS
What is Information ?
-- It is the date in the processed form/ Meaningful data
3
Introduction to Table
4
Introduction to DBMS
5
Introduction to DBMS
6
Introduction to DBMS
What is a Transaction ?
7
Introduction to DBMS
What is RDBMS ?
8
ACID Properties
Atomicity
-- All or Nothing
9
ACID Properties
Consistency
-- Valid data will be written in Database
-- When failed rollback to previous consistant state
10
ACID Properties
Isolation
-- Multiple transactions occurring at the same time does not
impact each other transaction
11
ACID Properties
Durability
-- Transactions committed to database will never lost
12
ACID Properties
Normalization
14
1st Normal Form -1NF
15
2nd Normal Form -2NF
16
3rd Normal Form -3NF
18
Introduction to SQL
19
Tables to be used
20
Data Types in Oracle
21
Data Types in Oracle – Character Data Type
22
Data Types in Oracle – Number Data Type
23
Data Types in Oracle – Long Data Type
24
Data Types in Oracle – Date Data Type
25
Data Types in Oracle – LOB Data Type
26
DATA DEFINITION LANGUAGE (DDL)
Create table :
Syntax :
Create table <table_name> (col1 datatype1, col2 datatype2 …coln datatypen);
Example:
create table student (no number (2), name varchar 2(10), marks number (3));
27
Rules of creating a table
28
DATA DEFINITION LANGUAGE (DDL)
Renaming a column.
S: alter table <table_name> rename column <old_col_name> to
<new_col_name>;
E: ALTER TABLE emp RENAME COLUMN ename TO empname;
29
DATA DEFINITION LANGUAGE (DDL)
Renaming tables:
S: rename <old_table_name> to <new_table_name>;
E: RENAME emp TO myemp:
Drop a table:
S: Drop table <table_name>;
E: DROP TABLE emp;
Truncate a table:
S: truncate table <table_name>;
E: TRUNCATE TABLE emp:
30
DATA MANIPULATION LANGUAGE (DML) - INSERT
INSERT
This will be used to insert the records into table.
We have two methods to insert.
• By value method
Syntax:
insert into <table_name> values (value1, value2, value3 …. Valuen);
Example:
insert into student values (1, ’sudha’, 100);
• By address method
Syntax:
insert into <table_name) values (&col1, &col2, &col3 …. &coln);
Example:
insert into student values (&no, '&name', &marks);
31
DATA MANIPULATION LANGUAGE (DML) - INSERT
32
DATA MANIPULATION LANGUAGE (DML) - UPDATE
33
DATA MANIPULATION LANGUAGE (DML) - DELETE
34
DATA RETRIVAL LANGUAGE (DRL)
35
DATA CONTROL LANGUAGE (DCL)
36
TRANSACTION CONTROL LANGUAGE (TCL) - COMMIT
37
TRANSACTION CONTROL LANGUAGE (TCL) – ROLLBACK &
SAVEPOINT
ROLLBACK :
ROLLBACK rolls back the current transaction and causes all the
updates/inserts made by the transaction to be discarded.
ROLLBACK;
Save point:
38
CONDITIONAL SELECTIONS AND OPERATORS
USING WHERE
select * from <table_name> where <condition>;
39
CONDITIONAL SELECTIONS AND OPERATORS
USING ORDER BY
This will be used to ordering the columns data (ascending or descending).
40
DUAL Table
41
Functions
42
Single Row Functions – Numeric Functions
• Abs • Log
• Sign • Ceil
• Sqrt • Floor
• Mod • Round
• Nvl • Trunk
• Power • Greatest
• Exp • Least
• Ln • Coalesce
43
Single Row Functions – Numeric Functions
ABS :
• ABS returns the absolute value of the given value
• Absolute value is always a positive number.
Sy : abs (value)
Ex : select abs(5), abs(-5), abs(0), abs(null) from dual;
SIGN :
• Sign gives the sign of a value.
Sy : sign (value)
Ex : select sign(5), sign(-5), sign(0), sign(null) from dual;
SQRT :
• This will give the square root of the given value.
Sy : sqrt (value)
Ex : select sqrt(4), sqrt(0), sqrt(null), sqrt(1) from dual;
44
Single Row Functions – Numeric Functions
MOD :
• This will give the remainder.
Sy : mod (value, divisor)
Ex : select mod(7,4), mod(1,5), mod(null,null), mod(0,0), mod(-7,4)
from dual;
NVL :
• This will substitutes the specified value in the place of null
values.
Sy : nvl (null_col, replacement_value)
Ex : select nvl(1,2), nvl(2,3), nvl(4,3), nvl(5,4) from dual;
POWER:
• Power is the ability to raise a value to a given exponent.
Sy : power (value, exponent)
Ex: select power(2,5), power(0,0), power(1,1), power(null,null),
power(2,-5) from dual; 45
Single Row Functions – Numeric Functions
EXP :
• This will raise e value to the give power.
Sy : exp (value)
Ex : select exp(1), exp(2), exp(0), exp(null), exp(-2) from dual;
LN :
• This is based on natural or base e logarithm.
Sy : ln (value)
Ex : select ln(1), ln(2), ln(null) from dual;
LOG :
• This is based on 10 based logarithm.
Sy : log (10, value)
Ex: select log(10,100), log(10,2), log(10,1), log(10,null) from dual;
46
Single Row Functions – Numeric Functions
CEIL :
• This will produce a whole number that is greater than or equal to
the specified value.
Sy : ceil (value)
Ex : select ceil(5), ceil(5.1), ceil(-5), ceil( -5.1), ceil(0), ceil(null) from
dual;
FLOOR :
• This will produce a whole number that is less than or equal to
the specified value.
Sy : floor (value)
Ex : select floor(5), floor(5.1), floor(-5), floor( -5.1), floor(0),
floor(null) from dual;
47
Single Row Functions – Numeric Functions
ROUND :
• This will rounds numbers to a given number of digits of
precision.
Sy : round (value, precision)
Ex: select round(123.2345), round(123.2345,2), round(123.2354,2)
from dual;
TRUNC :
• This will truncates or chops off digits of precision from a
number.
Sy : trunc (value, precision)
Ex : select trunc(123.2345), trunc(123.2345,2), trunc(123.2354,2) from
dual;
GREATEST :
• This will give the greatest number.
Sy : greatest (value1, value2, value3 … valuen)
Ex : select greatest(1, 2, 3), greatest(-1, -2, -3) from dual;
48
Single Row Functions – Numeric Functions
LEAST :
• This will give the least number.
Sy : least (value1, value2, value3 … value n)
Ex: select least(1, 2, 3), least(-1, -2, -3) from dual;
If all the values are zeros then it will display zero.
If all the parameters are nulls then it will display nothing.
If any of the parameters is null it will display nothing.
COALESCE :
• This will return first non-null value.
Sy : coalesce (value1, value2, value3 … value n)
EX: select coalesce(1,2,3), coalesce(null,2,null,5) from
dual;
49
Single Row Functions – String Functions
• Initcap • Replace
• Upper • Soundex
• Lower • Concat ( ‘ || ‘
• Length Concatenation
• Rpad operator)
• Lpad • Ascii
• Ltrim • Chr
• Rtrim • Substr
• Trim • Instr
• Translate • Decode
• Greatest
• Least
• Coalesce
50
Single Row Functions – String Functions
INITCAP :
• This will capitalize the initial letter of the string.
Sy : initcap (string)
EX: select initcap('computer') from dual;
UPPER :
• This will convert the string into uppercase.
Sy : upper (string)
EX: select upper('computer') from dual;
LOWER :
• This will convert the string into lowercase.
Sy : lower (string)
EX: select lower('COMPUTER') from dual;
51
Single Row Functions – String Functions
LENGTH :
• This will give length of the string.
Sy : length (string)
EX: select length('computer') from dual;
RPAD :
• This will allows you to pad the right side of a column with any
set of characters.
Sy : rpad (string, length [, padding_char])
EX: select rpad('computer',15,'*'), rpad('computer',15,'*#') from
dual;
LPAD:
• This will allows you to pad the left side of a column with any set
of characters.
Sy : lpad (string, length [, padding_char])
EX: select lpad('computer',15,'*'), lpad('computer',15,'*#') from
dual; 52
Single Row Functions – String Functions
LTRIM:
• This will trim off unwanted characters from the left end of string.
Sy : ltrim (string [,unwanted_chars])
EX: select ltrim('computer','co'), ltrim('computer','com') from dual;
RTRIM:
• This will trim off unwanted characters from the right end of
string.
Sy : rtrim (string [, unwanted_chars])
EX: select rtrim('computer','er'), rtrim('computer','ter') from dual;
TRIM:
• This will trim off unwanted characters from the both sides of
string.
Sy : trim (unwanted_chars from string)
EX: select trim( 'i' from 'indiani') from dual;
53
Single Row Functions – String Functions
TRANSLATE:
• This will replace the set of characters, character by character.
Sy : translate (string, old_chars, new_chars)
EX: select translate('india','in','xy') from dual;
REPLACE:
• This will replace the set of characters, string by string.
Sy : replace (string, old_chars [, new_chars])
EX:
SOUNDEX:
• This will be used to find words that sound like other words,
exclusively used in where clause.
Sy : soundex (string)
EX: select * from emp where soundex(ename) = soundex('SMIT');
54
Single Row Functions – String Functions
CONCAT :
• This will be used to combine two strings only.
Sy : concat (string1, string2)
EX: select concat('computer',' operator') from dual;
ASCII :
• This will return the decimal representation in the database
character set of the first character of the string.
Sy : ascii (string)
EX: select ascii('a'), ascii('apple') from dual;
CHR :
• This will return the character having the binary equivalent to the
string in either thedatabase character set or the national character
set.
Sy : chr (number)
EX: select chr(97) from dual;
55
Single Row Functions – String Functions
SUBSTR:
56
Single Row Functions – String Functions
INSTR:
• This will allows you for searching through a string for set of
characters.
Sy : instr (string, search_str [, start_chr_count [, occurrence] ])
EX: select instr('information','o',4,1), instr('information','o',4,2)
from dual;
• If you are not specifying start_chr_count and occurrence then it will start
search from the beginning and finds first occurrence only.
• If both parameters start_chr_count and occurrence are null, it will display
nothing.
57
Single Row Functions – String Functions
DECODE:
58
Single Row Functions – String Functions
GREATEST:
• This will give the greatest string.
Sy : greatest (strng1, string2, string3 … stringn)
EX: select greatest('a', 'b', 'c'), greatest('satish','srinu','saketh') from
dual;
LEAST:
• This will give the least string.
Sy : greatest (strng1, string2, string3 … stringn)
EX: select least('a', 'b', 'c'), least('satish','srinu','saketh') from dual;
COALESCE:
• This will gives the first non-null string.
Sy : coalesce (strng1, string2, string3 … stringn)
EX: select coalesce('a','b','c'), coalesce(null,'a',null,'b') from dual;
59
Single Row Functions – Date Functions
• Sysdate
• Extract
• TO_CHAR
• TO_DATE
• Add_months
• Months_between
• Next_day
• Last_day
• Greatest
• Least
• Round
• Trunc
• New_time
• Coalesce
60
Single Row Functions – Date Functions
SYSDATE :
• Returns the current date and time in the Oracle Server.
Ex : select sysdate from dual;
EXTRACT:
• This is used to extract a portion of the date value.
Sy : extract ((year | month | day | hour | minute | second), date)
Ex : select extract(year from sysdate) from dual;
61
Single Row Functions – Date Functions
TO_CHAR :
• This will be used to extract various date formats.
• The available date formats as follows.
D No of days in week YEAR Fully spelled out year
DD No of days in month CC Century
Q No of quarters
DDD No of days in year
W No of weeks in month
MM No of month WW No of weeks in year
MON Three letter abbreviation of month IW No of weeks in year from ISO standard
MONTH Fully spelled out month HH Hours
RM Roman numeral month MI Minutes
DY Three letter abbreviated day SS Seconds
FF Fractional seconds
DAY Fully spelled out day
AM or PM -- Displays AM or PM depending upon time
Y Last one digit of the year of day
YY Last two digits of the year A.M or P.M -- Displays A.M or P.M depending upon time
YYY Last three digits of the year of day
YYYY Full four digit year AD or BC -- Displays AD or BC depending upon the date
SYYYY Signed year A.D or B.C -- Displays AD or BC depending upon the
date
I One digit year from ISO standard
FM -- Prefix to month or day, suppresses padding of
IY Two digit year from ISO standard month or day
IYY Three digit year from ISO standard TH Suffix to a number
IYYY Four digit year from ISO standard SP suffix to a number to be spelled out
Y, YYY Year with comma SPTH Suffix combination of TH and SP to be both
spelled out
THSP same as SPTH
62
Single Row Functions – Date Functions
63
Single Row Functions – Date Functions
TO_DATE :
• This will be used to convert the string into data format.
Sy : to_date (date)
Ex : select to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd * month *
day') from dual;
ADD_MONTHS :
• This will add the specified months to the given date.
Sy : add_months (date, no_of_months)
Ex : select add_months(to_date('11-jan-1990','dd-mon-yyyy'), 5) from
dual;
MONTHS_BETWEEN :
• This will give difference of months between two dates.
Sy : months_between (date1, date2)
Ex : select months_between(to_date('11-aug-1990','dd-mon-yyyy'),
to_date('11-jan-1990','dd-mon-yyyy')) from dual;
64
Single Row Functions – Date Functions
NEXT_DAY:
• This will produce next day of the given day from the specified date.
Sy : next_day (date, day)
Ex : select next_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from
dual;
LAST_DAY :
• This will produce last day of the given date.
Sy : last_day (date)
Ex : select last_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from
dual;
GREATEST:
• This will give the greatest date.
Sy : greatest (date1, date2, date3 … daten)
Ex : select greatest(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-
90','ddmon-yy'),to_date('11-apr-90','dd-mon-yy')) from dual;
65
Single Row Functions – Date Functions
LEAST:
• This will give the least date.
Sy : least (date1, date2, date3 … daten)
Ex : select least(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-
90','dd-monyy'),to_date('11-apr-90','dd-mon-yy')) from dual;
66
Single Row Functions – Date Functions
ROUND:
• Round will rounds the date to which it was equal to or greater than
the given date.
Sy : round (date, (day | month | year))
Ex : select round(to_date('24-dec-04','dd-mon-yy'),'year'),
round(to_date('11-mar-06','dd-mon-yy'),'year') from dual;
• If the month falls between JAN and JUN then it returns the first day of the current year.
• If the month falls between JUL and DEC then it returns the first day of the next year.
• If the day falls between 1 and 15 then it returns the first day of the current month.
• If the day falls between 16 and 31 then it returns the first day of the next month.
• If the week day falls between SUN and WED then it returns the previous sunday.
• If the weekday falls between THU and SUN then it returns the next sunday.
• If the second parameter was null then it returns nothing.
• If you are not specifying the second parameter then round will resets the time
to the begining of the current day in case of user specified date.
• If the you are not specifying the second parameter then round will resets the time
to the begining of the next day in case of sysdate
67
Single Row Functions – Date Functions
TRUNC:
• Trunc will chops off the date to which it was equal to or less than the
given date.
Sy : trunc (date, (day | month | year))
Ex : select trunc(to_date('24-dec-04','dd-mon-yy'),'year'),
trunc(to_date('11-mar-06','dd-mon-yy'),'year') from dual;
• If the second parameter was year then it always returns the first day of the current
year.
• If the second parameter was month then it always returns the first day of the current
month.
• If the second parameter was day then it always returns the previous sunday.
• If the second parameter was null then it returns nothing.
• If the you are not specifying the second parameter then trunk will resets the time to the
begining of the current day.
68
Single Row Functions – Date Functions
NEW_TIME :
• This will give the desired timezone’s date and time.
Sy : new_time (date, current_timezone, desired_timezone)
Ex : select to_char(new_time(sysdate,'gmt','yst'),'dd mon yyyy hh:mi:ss
am') from dual;
69
Single Row Functions – Date Functions
COALESCE:
• This will give the first non-null date.
Sy : coalesce (date1, date2, date3 … daten)
Ex : select coalesce('12-jan-90','13-jan-99'), coalesce(null,'12-jan-90','23-
mar-
98',null) from dual;
70
Single Row Functions – Miscellaneous Functions
• Uid
• User
• Vsize
• ROWID
• ROWNUM
• SYSDATE
71
Single Row Functions – Miscellaneous Functions
Uid :
• This will returns the integer value corresponding to the user currently logged
in.
EX : select uid from dual;
USER :
• This will returns the login’s user name.
EX : select user from dual;
VSIZE :
• This will returns the number of bytes in the expression.
EX : select vsize(123), vsize('computer'), vsize('12-jan-90') from dual;
ROWID :
• It gives location in the database where row is physically stored.
EX : SELECT ROWID, name FROM emp;
72
Single Row Functions – Miscellaneous Functions
ROWNUM:
• It gives a sequence in which rows are retrieved from the database
EX : SELECT ROWNUM, name FROM emp;
SYSDATE:
• It gives current date and time of the system
EX : SELECT SYSDATE FROM DUAL;
RANK:
• This will give the non-sequential ranking.
SELECT RANK(2975) WITHIN GROUP(ORDER BY SAL DESC) FROM
EMP;
DENSE_RANK:
• This will give the sequential ranking.
SELECT DENSE_RANK(2975) WITHIN GROUP(ORDER BY SAL DESC)
FROM EMP;
73
Single Row Functions – Conversion Functions
• Bin_to_num
• To_char
• To_date
• To_number
74
Single Row Functions – Conversion Functions
Bin_to_num
• This will convert the binary value to its numerical equivalent.
Sy: bin_to_num( binary_bits)
Ex : select bin_to_num(1,1,0) from dual;
To_number
• converts expr to a value of NUMBER datatype
Sy: To_number( string)
Ex : select To_Num(‘100’) from dual;
75
Group Functions
• Sum
• Avg
• Max
• Min
• Count
Group functions will be applied on all the rows but produces single
output.
76
Group Functions
Sum
• This will give the sum of the values of the specified column.
Sy : sum (column)
Ex : select sum(sal) from emp;
AVG
• This will give the average of the values of the specified column.
Sy : avg(column)
Ex : select avg(sal) from emp;
MAX
• This will give the maximum of the values of the specified column.
Sy : max(column)
Ex : select max(sal) from emp;
77
Group Functions
MIN
• This will give the minimum of the values of the specified column.
Sy : min (column)
Ex : select min(sal) from emp;
COUNT
• This will give the count of the values of the specified column
Sy : count(column)
Ex : select count(sal) from emp;
78
ORDER OF EXECUTION
• FROM
• WHERE
• GROUP BY
• HAVING
• SELECT
• DISTINCT
• ORDER BY
79
Group by Clause:
80
HAVING Clause:
EX: select max ( sal ), deptno from emp group by deptno HAVING
deptno=10;
81
Integrity Constraints
• Entity Integrity
• Domain Integrity
• Referential integrity
• User-Defined Integrity
82
Integrity Constraints
83
Integrity Constraints
84
Domain Integrity – Check Constraint
COLUMN LEVEL
• create table student(no number(2) , name varchar(10), marks
number(3) check (marks > 300));
• create table student(no number(2) , name varchar(10), marks
number(3) constraint ch check(marks > 300));
TABLE LEVEL
• create table student(no number(2) , name varchar(10), marks
number(3),check (marks > 300));
• create table student(no number(2) , name varchar(10), marks
number(3), constraint ch check(marks > 300));
ALTER LEVEL
• alter table student add check(marks>300);
• alter table student add constraint ch check(marks>300);
85
Domain Integrity – Not Null Constraint
COLUMN LEVEL
• create table student(no number(2) not null, name varchar(10), marks
number(3));
• create table student(no number(2) constraint nn not null, name
varchar (10), marks number(3));
86
Entity Integrity – Unique Key Constraint
COLUMN LEVEL
• create table student(no number(2) constraint un unique, name
varchar(10), marks number(3));
TABLE LEVEL
• create table student(no number(2) , name varchar(10), marks
number(3),unique(no));
• create table student(no number(2) , name varchar(10), marks
number(3),constraint un unique(no));
ALTER LEVEL
• alter table student add unique(no);
87
• alter table student add constraint un unique(no);
Entity Integrity – Primary Key Constraint
88
Entity Integrity – Primary Key Constraint
COLUMN LEVEL
• create table student(no number(2) primary key, name varchar(10),
marks number(3));
• create table student(no number(2) constraint pk primary key, name
varchar(10),marks number(3));
TABLE LEVEL
• create table student(no number(2) , name varchar(10), marks
number(3), primary key(no));
• create table student(no number(2) , name varchar(10), marks
number(3), constraint pk primary key(no));
ALTER LEVEL
• alter table student add primary key(no);
• alter table student add constraint pk primary key(no);
89
Referential Integrity – Primary Key Constraint
• This is used to reference the parent table primary key column which
allows duplicates.
• Foreign key always attached to the child table.
• Parent that is being referenced has to be unique or primary key.
• Foreign key constraint can be specified on child but not on parent.
• Parent record can be deleting provided no child record exists
• Master table can not be updated if child record exists.
• We can add this constraint in table and alter levels only.
90
Referential Integrity – Primary Key Constraint
TABLE LEVEL
• create table emp(empno number(2), ename varchar(10), deptno
number(2), primary key(empno), foreign key(deptno) references
dept(deptno));
• create table emp(empno number(2), ename varchar(10), deptno
number(2), constraint pk primary key(empno), constraint fk foreign
key(deptno) references dept(deptno));
ALTER LEVEL
• alter table emp add foreign key(deptno) references dept(deptno);
• alter table emp add constraint fk foreign key(deptno) references
dept(deptno);
91
On Delete Cascade
• By using this clause you can remove the parent record even it childs
exists.
• Because when ever you remove parent record oracle automatically
removes all its dependent records from child table, if this clause is
present while creating foreign key constraint.
TABLE LEVEL
• create table emp(empno number(2), ename varchar(10), deptno
number(2), primary key(empno), foreign key(deptno) references
dept(deptno) on delete cascade);
• create table emp(empno number(2), ename varchar(10), deptno
number(2), constraint pk primary key(empno), constraint fk foreign
key(deptno) references dept(deptno) on delete cascade);
ALTER LEVEL
• alter table emp add foreign key(deptno) references dept(deptno) on
delete cascade;
• alter table emp add constraint fk foreign key(deptno) references
dept(deptno) on delete cascade;
92
DEFERRABLE CONSTRAINTS
Enable
This will enable the constraint. Before enable, the constraint will check
the existing data.
Ex: alter table student enable constraint un;
Disable
This will disable the constraint.
Ex: alter table student enable constraint un;
94
Operations with constraints
Enforce
• This will enforce the constraint rather than enable for future inserts or
updates.
• This will not check for existing data while enforcing data.
Ex: alter table student enforce constraint un;
Drop
• This will remove the constraint.
Ex : alter table student drop constraint un;
95
Case & Default
Case
Ex:
Select sal,
Case sal
When 500 then ‘low’
When 5000 then ‘high’
Else ‘medium’
End case
From emp;
96
Case & Default
DEFAULT
97
Set Operators
Union
This will combine the records of multiple tables having the same
structure
select * from student1 union select * from student2;
Union all
This will combine the records of multiple tables having the same
structure but including duplicates.
select * from student1 union all select * from student2;
98
Set Operators
Intersect
This will give the common records of multiple tables having the same
structure.
select * from student1 intersect select * from student2;
Minus
This will give the records of a table whose records are not in other tables
having the same structure.
select * from student1 minus select * from student2;
99
Joins
• Equi join
• Non-equi join
• Self join
• Natural join
• Cross join
• Outer join
Left outer join
Right outer join
Full outer join
• Inner join
• Using clause
• On clause
100
Joins
EMP
EMPNO ENAME JOB MGR DEPTNO
111 Saketh Analyst 444 10
222 Sudha Clerk 333 20
333 Jagan Manager 111 10
444 Madhu Engineer 222 30
101
Joins
Equi Join
• An inner join is called Equi Join when the where statement compares two
columns with the equivalence (‘=’) operator.
• These joins returns all rows from both tables where there is a match.
102
Joins
USING CLAUSE
ON CLAUSE
NON-EQUI JOIN
A join which contains an operator other than ‘=’ in the joins condition.
103
Joins
SELF JOIN
NATURAL JOIN
104
Joins
CROSS JOIN
OUTER JOIN
105
Joins
This returns all the rows from the table on the left side of the join,
along with the values from the right-hand side, or nulls if a matching
row doesn't exist.
106
Joins
This will display the all matching records and the records which are in
right hand side table those that are not in left hand side table.
107
Joins
This will display the all matching records and the non-matching
records from both tables.
INNER JOIN
108
Sub Queries
USING
TYPES
• Single row sub queries
• Multi row sub queries
• Multiple sub queries
• Correlated sub queries
109
Sub Queries
select * from emp where sal > (select sal from emp where empno =
7566);
In multi row subquery, it will return more than one value. In such
cases we should include operators like any, all, in or not in between
the comparision operator and the subquery.
select * from emp where sal > any (select sal from emp where sal
between 2500 and 4000);
select * from emp where sal > all (select sal from emp where sal
between 2500 and 4000);
select * from emp where sal In (select sal from emp where sal
110
between 2500 and 4000);
Sub Queries
MULTIPLE SUBQUERIES
select * from emp where sal = (select max(sal) from emp where sal <
(select max(sal) from emp));
CORRELATED SUBQUERIES
111
Inline Views
Select ename, sal, rownum rank from (select *from emp order by sal);
112
VIEWS
A view takes the output of the query and treats it as a table, therefore
a view can be thought of as a stored query or a virtual table.
113
VIEWS
TYPES
• Simple view
• Complex view
Simple view can be created from one table where as complex view
can be created from multiple tables.
UPDATABLE VIEW
if a view is used to look at the table data as well as INSERT, UPDATE
and DELETE table data is called updatable views
FORCE VIEW
Forces The Creation Of A View Even When The View Will Be Invalid.
No Force Is The Default
114
VIEWS
115
VIEWS
Creating a view:
Create view v_emp as select * from emp;
Create view v_emp as select ename,deptno from emp;
Force View:
Create FORCE view v_emp as select * from emp;
Destroying a view:
Drop view v_emp;
116
VIEWS
• View was created but the underlying table was dropped then we
will get the message like “ view has errors ”.
• View was created but the base table has been altered but still the
view was with the initial definition, we have to replace the view to
affect the changes.
• Complex view (view with more than one table) -- insert not possible
-- update, delete possible (not always)
117
Materialized Views
Stores data
118
Synonyms
TYPES
• Private
• Public
Private synonym is available to the particular user who creates.
Public synonym is created by DBA which is available to all the users.
ADVANTAGES
Hide the name and owner of the object.
Provides location transparency for remote objects of a distributed
database.
119
Synonyms
CREATE SYNONYM
create synonym s1 for emp;
create public synonym s2 for emp;
DROP SYNONY
drop synonym s1;
120
Sequence
121
Sequence
Ex:
create sequence s;
create sequence s increment by 10 start with 100 minvalue 5
maxvalue 200 cycle cache 20;
USING SEQUENCE
122
Sequence
ALTERING SEQUENCE
Ex:
alter sequence s minvalue 5;
alter sequence s increment by 2;
alter sequence s cache 10;
DROPPING SEQUENCE
drop sequence s;
123
Analytical Functions
124
Analytical Functions
DEPTNO AVG(SAL)
---------- ----------
10 2916.66667
20 2175
30 1566.66667
125
Analytical Functions
126
SELECT empno, deptno, sal,
AVG(sal) OVER (PARTITION BY deptno) AS avg_dept_sal
FROM emp;
129
USING
130
USING
131
132
133
PL/SQL
134
PL/SQL Records
• Objects of type RECORD are called PL/SQL records
• PL/SQL records have uniquely named fields, which can belong to
different datatypes
135
Cursors
• To process a SQL statement, PL/SQL opens a work area called a context
area.
• PL/SQL uses this area to execute SQL statements and store processing
information
• A PL/SQL construct called ‘Cursor’ allows you to name a context area,
access its information and in some cases, control its processing
Types of Cursors:
1. Implicit Cursors
2. Explicit Cursors
136
Cursors
Implicit Cursors :
These cursors are opened by SQL automatically when ever a select is issued
on any table
Explicit Cursors :
Defined by the user to keep track of which row is being processed, when a
query returns multiple rows
137
Cursors - Explicit Cursors
Defining a Cursor
A cursor is defined in the declarative part of the PL/SQL block by naming it and
associating it with a query
CURSOR <cursorname> IS
<SELECT statement>;
Example
CURSOR emp_cur IS
SELECT empno, ename, job, sal
FROM emp;
138
Cursors - Explicit Cursors
The OPEN Statement
• Initializes or opens a cursor
• Cursor must be opened before any rows are returned by the query
OPEN <cursorname>
Example --
OPEN emp_cur;
139
Cursors - Explicit Cursors
The CLOSE Statement
Closes the cursor and makes the active set undefined
CLOSE <cursorname>;
Example
CLOSE emp_cur;
140
Cursors - Explicit Cursors
Attributes of Explicit Cursors
Every cursor has four attributes that can be used to access the cursor’s context
area
%NOTFOUND
%FOUND
%ROWCOUNT
%ISOPEN
To use these attributes, simple append them to the name of the cursor
%NOTFOUND
• evaluates to TRUE if last FETCH failed because no more rows were
available
• evaluates to FALSE if last FETCH returned a row
%FOUND
• evaluates to TRUE if last FETCH returned a row
• evaluates to FALSE if last FETCH failed because no more rows were
available
141
Cursors - Explicit Cursors
%ROWCOUNT
• Returns the number of rows FETCHed from the active set so far
%ISOPEN
• Evaluates to TRUE if an explicit cursor is open
• Evaluates to FALSE if an explicit cursor is closed
142
Cursors – Cursor For loop & Parameterized cursors
Parameterized Cursor
The same cursor can be reopened and closed with different active sets.
143
Cursors - Implicit Cursors
Implicit Cursors
• Automatically defined and opened, by Oracle, to process each SQL
statement
• Most recently opened context area is referred to as a ‘SQL%’ cursor
144
Cursors - Implicit Cursors
SQL%NOTFOUND
evaluates to TRUE if an INSERT, UPDATE or DELETE statement affected
no rows, else it evaluates to FALSE
SQL%FOUND
logical opposite of SQL%NOTFOUND
evaluates to TRUE if an INSERT, UPDATE or DELETE affected one or
more rows, else it evaluates to FALSE
SQL%ROWCOUNT
returns the number of rows affected by an INSERT, UPDATE or DELETE
statement
SQL%ISOPEN
Oracle automatically closes an implicit cursor after executing its associated
SQL statement
For an implicit cursor SQL%ISOPEN always evaluates to FALSE
145
Collections
146
Collections - varray
Declaration of varray
A variety of methods exist for collections, but not all are relevant for every
collection type.
EXISTS(n) - Returns TRUE if the specified element exists.
COUNT - Returns the number of elements in the collection.
LIMIT - Returns the maximum number of elements for a VARRAY, or NULL for
nested tables.
FIRST - Returns the index of the first element in the collection.
LAST - Returns the index of the last element in the collection.
PRIOR(n) - Returns the index of the element prior to the specified element.
NEXT(n) - Returns the index of the next element after the specified element.
EXTEND - Appends a single null element to the collection.
EXTEND(n) - Appends n null elements to the collection.
EXTEND(n1,n2) - Appends n1 copies of the n2th element to the collection.
TRIM - Removes a single element from the end of the collection.
TRIM(n) - Removes n elements from the end of the collection.
DELETE - Removes all elements from the collection.
DELETE(n) - Removes element n from the collection.
DELETE(n1,n2) - Removes all elements from n1 to n2 from the collection.
148
Collections - varray
Multiset Operations
The below are the four multi set operations that can be performed
• MULTISET UNION
• MULTISET UNION DISTINCT
• MULTISET EXCEPT
• MULTISET INTERSECT
149
Collections – Nested table
150
Collections – Nested table
151
Collections – Associative array
152
Collections - Assignments and Equality Tests
Assignments can only be made between collections of the same type. Not
types of similar structures, or with the same name in different packages, but
literally the same type.
153
Bulk Binds
Oracle uses two engines to process PL/SQL code. All procedural code is
handled by the PL/SQL engine while all SQL is handled by the SQL statement
executor, or SQL engine.
There is an overhead associated with each context switch between the two
engines. If PL/SQL code loops through a collection performing the same DML
operation for each item in the collection it is possible to reduce context switches
by bulk binding the whole collection to the DML statement in one operation.
154
BULK COLLECT
Bulk binds can improve the performance when loading collections from a
queries. The BULK COLLECT INTO construct binds the output of the query to
the collection.
Note. The select list must match the collections record definition exactly for this
to be successful.
Remember that collections are held in memory, so doing a bulk collect from a
large query could cause a considerable performance problem. In actual fact
you would rarely do a straight bulk collect in this manner. Instead you would
limit the rows returned using the LIMIT clause and move through the data
processing smaller chunks. This gives you the benefits of bulk binds, without
hogging all the server memory
155
Bulk Load - FORALL
SQL%BULK_ROWCOUNT
156
SAVE EXCEPTIONS and SQL%BULK_EXCEPTION
We saw how the FORALL syntax allows us to perform bulk DML operations, but
what happens if one of those individual operations results in an exception? If
there is no exception handler, all the work done by the current bulk operation is
rolled back. If there is an exception handler, the work done prior to the
exception is kept, but no more processing is done. Neither of these situations is
very satisfactory, so instead we should use the SAVE EXCEPTIONS clause to
capture the exceptions and allow us to continue past them. We can
subsequently look at the exceptions by referencing
theSQL%BULK_EXCEPTION cursor attribute.
157
EXCEPTIONS
158
EXCEPTIONS - Predefined Exceptions
EXCEPTION
WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN
statements;
WHEN OTHERS THEN
statements;
END; 159
EXCEPTIONS – User - defined Exceptions
160
RAISE_application_error
This can be used to create user defined error message, which can be more
descriptive than named exceptions.
161
SQLCODE AND SQLERRM
162
Procedure
• Provide Extensibility
• PL/SQL language can be tailored to suit the needs of the application
• Promote reusability and maintainability
• Once validated, they can be used with confidence in any number of
applications
• Simplifies maintenance/enhancement, as subprogram is only affected if
definition changes
• Provide Modularity
• Program can be broken down into manageable, well-defined logical
modules
• Supports top-down design and stepwise refinement approach to
problem solving
• Aid in abstraction
• Allow mental separation from particulars
• Stubs allow programmers to defer definition of procedures/functions
until main program is tested and debugged
163
Procedure
165
Parameter modes for Procedure
IN
• allows values to be passed to the subprogram being called
• inside the subprogram it acts like a constant
• actual corresponding parameter can be a constant, literal, initialized
variable or expression
• can be initialized to default values
OUT parameter
• allows values to be returned to the caller of a subprogram
• inside the subprogram it acts like an uninitialized variable
• actual corresponding parameter must be a variable; it cannot be a
constant or expression
• its value cannot be assigned to another variable or reassigned to itself
166
Parameter modes for Procedure
IN OUT parameter
• allows initial values to be passed and returns updated values to the
caller
• inside the subprogram it acts like an initialized variable
• actual corresponding parameter must be a variable; it cannot be a
constant or expression
• can be assigned a value and its value can be assigned to another
variable
167
Autonomous Transaction
168
Functions
170
Packages
• Database objects that group logically related PL/SQL types, objects and
subprograms
• They cannot be called, passed parameters to or nested
• There are two parts
• Specification
• Body
Advantages of Packages
• Modularity
• Easier Application Design
• Information Hiding
• Better performance
171
Packages
Package Specification
• Is an interface to the applications
• Declares the types, variables, constants, exceptions, cursors and
subprograms available for use
• Holds public declarations, visible to the application
• Can be thought of as an operational interface
• Scope of the declarations are local to the database schema and global to the
package
• Lists the package resources available to applications
• Created using CREATE PACKAGE command
Package Body
• Implements the package specification
• Fully defines cursors and subprograms
• Holds implementation details and private declarations, hidden from the
application
• Can be thought of as a ‘black body’
• Can be replaced, enhanced or replaced without changing the interface
• Can be changed without recompiling calling programs
• Scope of the declarations are local to the package body
• Declared types and objects are inaccessible except from within the package
body
• Initialization part of a package is run only once, the first time the package is
referenced
Syntax for Package Body –
CREATE [OR REPLACE] PACKAGE BODY <packagename> AS
Private members (variables and procedure/functions/cursors/types)
Procedure Code;
Function Code;
Implementation of Types;
Use of Cursors;
173
Using Global variables in the members of the package.
TRIGGERS
174
TRIGGERS
• Name in the ON clause identifies the database table associated with the
trigger
• The trigger event specifies the SQL DML statement (INSERT, DELETE or
UPDATE) that affects the table
• AFTER specifies that the trigger fires after the manipulation is done
• BEFORE specifies that the trigger fires before the manipulation is done
• By default, a trigger fires once per table
• FOR EACH ROW specifies that the trigger fires once per row
• For the trigger to fire, the Boolean expression in the WHEN clause must
evaluate to TRUE
• REPLACE can be added to the CREATE statement to drop and re-create
the trigger automatically
175
TRIGGERS
• Prefix :new is a correlation name that refers to the newly updated column
value
• Within a trigger, the :new and :old values of changing rows can be
referenced
• A single trigger can handle more than one operation
176