Oracle Material
Oracle Material
Table of Contents
INTRODUCTION
1.1 Purpose
ORACLE
2.2.1
CREATE (DDL)
2.2.2
INSERT (DML)
2.2.3
Commit (TCL)
2.2.4
SELECT (DRL)
2.2.5
UPDATE (DML)
21
2.2.6
DELETE (DML)
21
2.2.7
TRUNCATE (DDL)
22
2.2.8
DROP (DDL)
22
2.2.9
USING DDL
23
2.2.10
USING TCL
24
2.2.11
USING DCL
26
2.3 Synonym
27
2.4 Dblink
28
28
2.6 Aliases
29
2.7 Functions
30
2.7.1
SINGLE
ROW
FUNCTIONS
2.7.2
30
55
57
2.8.1
UNION
57
2.8.2
UNION ALL
58
2.8.3
INTERSECT
58
2.8.4
MINUS
58
2.9 Constraints
58
2.9.1
NOT NULL
59
2.9.2
CHECK
60
2.9.3
UNIQUE
60
2.9.4
PRIMARY KEY
61
2.9.5
FOREIGN KEY
62
Page 1 of 90
2.9.6
2.10
COMPOSITE KEYS
64
Joins
65
2.10.1
EQUI JOIN
67
2.10.2
NON-EQUI JOIN
68
2.10.3
SELF JOIN
69
2.10.4
NATURAL JOIN
69
2.10.5
CROSS JOIN
70
2.10.6
OUTER JOIN
71
2.10.7
INNER JOIN
73
2.11
Case OR Decode ()
2.11.1
CASE
2.11.2
74
74
Decode ()
75
2.12
Merge Statement
75
2.13
75
2.13.1
SUB QUERIES
75
2.13.2
CORRELATED SUBQUERIES
77
2.13.3
EXISTS
77
2.14
78
2.14.1
VIEWS
78
2.14.2
INLINE VIEW
79
2.14.3
MATERILIZED VIEW
79
2.15
Indexes
81
2.15.1
UNIQUE INDEX
81
2.15.2
NON-UNIQUE INDEX
81
2.15.3
82
2.15.4
BITMAP INDEX
82
2.15.5
COMPOSITE INDEX
82
2.16
82
2.17
Differences
84
2.17.1
84
2.17.2
85
2.17.3
85
2.17.4
86
2.17.5
86
2.18
PL/SQL Basics
87
2.18.1
Store Procedure
87
2.18.2
Triggers:
88
2.19
IMPORTANT QUERIES
89
Page 2 of 90
1
1.1
INTRODUCTION
Purpose
The purpose of this document is to provide the detailed information
about Oracle-SQL based on Real-Time for beginners.
2
2.1
ORACLE
What is Oracle?
2.2
Page 3 of 90
Description
Max Size:
Oracle 11g
VARCHAR2(size)
4000 bytes
minimum is 1
NUMBER(p,s)
DATE
Page 4 of 90
varchar2 (50));
NAME
DOJ
Page 5 of 90
Page 6 of 90
Syntax:
Insert into <table_name>(col1, col2, col3 Coln) values (value1,
value2, value3 . Valuen);
Ex:
SQL> insert into student (no, name) values (3, Ramesh);
SQL> insert into student (no, name) values (4, Madhu);
d) INSERTING NULL DATA INTO SPECIFIED COLUMNS
SQL> insert into student values (1, sham, NULL);
Here null is not a value you cant use it for comparison.
2.2.3 Commit (TCL)
To save transaction permanently in the database we need to issue
commit.
Every DML should follow TCL.
SQL> commit;
2.2.4 SELECT (DRL)
Syntax:
Select * from <table_name>; -- here * indicates all columns
Or
Select col1, col2 coln from <table_name>;
Ex:
SQL> select * from student;
NO
NAME
address
Page 7 of 90
---
------
--------
sham
hyd
mohan
mpl
NAME
--- ------
address
--------
sham
hyd
mohan
mpl
NAME
--- ------1
Sham
mohan
Syntax:
Page 8 of 90
-- highest precedence
+, -, *, /
Comparison operators
=, !=, >, <, >=, <=, <>
between, not between
in, not in
null, not null
like
Logical operators
And
Or
-- lowest precedence
Not
a) USING =, >, <, >=, <=, !=, <>
Ex:
SQL> select * from student where DOJ = To_date (01-232010,MM-DD-YYYY);
NO NAME
MARKS
--- -------
---------
Saketh
200
Naren
400
Page 9 of 90
MARKS
--- -------
----------
Sudha
100
Jagan
300
MARKS
--- -------
----------
Ramesh
Madhu
Visu
Rattu
MARKS
--- -------
----------
Sudha
100
Saketh
200
Jagan
300
Naren
400
NO NAME
MARKS
--- -------
---------
Saketh
200
Naren
400
Ramesh
Madhu
Visu
Rattu
MARKS
--- -------
----------
Sudha
100
Jagan
300
Ramesh
Madhu
MARKS
--- -------
----------
Sudha
100
Jagan
300
Ramesh
Page 11 of 90
Madhu
Visu
Rattu
b) USING AND
This will gives the output when all the conditions become true.
Syntax:
Select * from <table_name> where <condition1> and
<condition2> and...
<conditionn>;
Ex:
SQL> select * from student where no = 2 and marks >= 200;
NO NAME
MARKS
--- -------
--------
Saketh
200
Naren
400
c) USING OR
This will gives the output when either of the conditions becomes true.
Syntax:
Select * from <table_name> where <condition1> or <condition2>
or...
<conditionn>;
Ex:
SQL> select * from student where no = 2 or marks >= 200;
Page 12 of 90
NO NAME
MARKS
--- -------
---------
Saketh
200
Jagan
300
d) USING BETWEEN
This will gives the output based on the column and its lower bound,
upper bound.
Syntax:
Select * from <table_name> where <col> between <lower bound>
and <upper bound>;
Ex:
SQL> select * from student where marks between 200 and 400;
NO NAME
MARKS
--- -------
---------
Saketh
200
Jagan
300
Naren
400
MARKS
--- -------
---------
Sudha
100
f) USING IN
This will gives the output based on the column and its list of values
specified.
Syntax:
Select * from <table_name> where <col> in (value1, value2,
value3 valuen);
Ex:
SQL> select * from student where no in (1, 2, 3);
NO NAME
MARKS
--- -------
---------
Sudha
100
Saketh
200
Jagan
300
Naren
400
Ramesh
Page 14 of 90
g) USING NOT IN
This will gives the output based on the column which values are not in
the list of values specified.
Syntax:
Select * from <table_name> where <col> not in (value1, value2,
value3 valuen);
Ex:
SQL> select * from student where no not in (1, 2, 3);
NO NAME
MARKS
--- -------
---------
Madhu
Visu
Rattu
h) USING NULL
This will gives the output based on the null values in the specified
column.
Syntax:
Select * from <table_name> where <col> is null;
Ex:
SQL> select * from student where marks is null;
NO NAME
MARKS
Page 15 of 90
--- ------3
Ramesh
Madhu
Visu
Rattu
---------
MARKS
--- -------
---------
Sudha
100
Saketh
200
Jagan
300
Naren
400
j) USING LIKE
This will be used to search through the rows of database column based
on the pattern you specify.
Page 16 of 90
Syntax:
Select * from <table_name> where <col> like <pattern>;
Ex:
i) This will give the rows whose marks are 100.
SQL> select * from student where marks like 100;
NO NAME
MARKS
--- -------
---------
Sudha
100
ii) This will give the rows whose name start with S.
SQL> select * from student where name like 'S%';
NO NAME
MARKS
--- -------
---------
Sudha
100
Saketh
200
iii) This will give the rows whose name ends with h.
SQL> select * from student where name like '%h';
NO NAME
MARKS
--- -------
---------
Saketh
200
Ramesh
Page 17 of 90
iV) This will give the rows whose names second letter start with a.
SQL> select * from student where name like '_a%';
NO NAME
MARKS
--- -------
--------
Saketh
200
Jagan
300
Naren
400
Ramesh
Madhu
Rattu
V) This will give the rows whose names third letter start with d.
SQL> select * from student where name like '__d%';
NO NAME
MARKS
--- -------
---------
Sudha
Madhu
100
Vi) This will give the rows whose names second letter start with t
from ending.
SQL> select * from student where name like '%_t%';
NO NAME
MARKS
--- -------
---------
Page 18 of 90
Saketh
Rattu
200
Viii) This will give the rows whose name cotains 2 as.
SQL> select * from student where name like '%a%a%';
NO NAME
--- ------1
Jagan
MARKS
---------300
MARKS
--- -------
---------
Sudha
100
Jagan
300
Page 19 of 90
Saketh
200
Naren
400
Ramesh
Madhu
MARKS
--- -------
---------
4 Madhu
3 Ramesh
2 Saketh
200
2 Naren
400
1 Sudha
100
1 Jagan
300
Page 20 of 90
Page 21 of 90
Syntax:
Truncate table <table_name>;
Ex:
SQL> Truncate table student;
Page 22 of 90
e) RENAMING COLUMN
Syntax:
Alter table <table_name> rename column <old_col_name> to
<new_col_name>;
Ex:
SQL> Alter table student rename column marks to smarks;
USING RENAME
This will be used to rename the database object;
Page 23 of 90
Syntax:
Rename <old_table_name> to <new_table_name>;
Ex:
SQL> Rename student to stud;
2.2.10 USING TCL
USING COMMIT
This will be used to save the work.
Commit is of two types.
Implicit
Explicit
a) IMPLICIT
This will be issued by oracle internally
When any DDL operation is performed.
b) EXPLICIT
This will be issued by the user.
Syntax:
Commit or commit work;
* Whenever you committed then the transaction was completed.
USING ROLLBACK
This will undo the operation.
This will be applied in two methods.
Page 24 of 90
Up to previous commit
Up to previous rollback
Syntax:
Roll or roll work;
Or
Rollback or rollback work;
* While process is going on, if suddenly power goes then oracle will
rollback the transaction.
USING SAVEPOINT
You can use savepoints to rollback portions of your current set of
transactions.
Syntax:
Savepoint <savepoint_name>;
2.2.11 USING DCL
DCL commands are used to granting and revoking the permissions on
objects. To access tables from one schema to another schema.
USING GRANT
This is used to grant the privileges to other users.
Syntax:
Grant <privileges> on <object_name> to <user_name> [with grant
option];
Ex:
SQL> grant select on student to abc; -- you can give individual
privilege
Page 25 of 90
SQL> grant select, insert on student to abc; -- you can give set of
privileges
SQL> grant all on student to abc; -- you can give all privileges
The abc user has to use dot method to access the object.
SQL> select * from scott.student;
The abc user can not grant permission on student table to other users.
To get this type of option use the following.
SQL> grant all on student to abc with grant option;
Now abc user also grants permissions on student table.
USING REVOKE
This is used to revoke the privileges from the users to which you granted
the privileges.
Syntax:
Revoke <privileges> on <object_name> from <user_name>;
Ex:
SQL> revoke select on student form abc;
individual privilege
SQL> revoke select, insert on student from abc;
set of privileges
SQL> revoke all on student from abc; -- you can revoke all privileges
2.3
Synonym
Page 26 of 90
Dblink
2.5
Page 27 of 90
We can create a table using existing table [along with data] Called it as
Back up tables.
Syntax:
Create table <new_table_name> [col1, col2, col3 ... coln] as select *
from
<old_table_name>;
Ex:
SQL> create table student1 as select * from student;
Creating table with your own column names.
SQL> create table student2 (sno, sname, smarks) as select * from
student;
Creating table with specified columns.
SQL> create table student3 as select no, name from student;
Creating table without table data.
SQL> create table student2 (sno, sname, smarks) as select * from
student where 1 = 2;
In the above where clause give any condition which does not satisfy.
INSERT WITH SELECT
Using this we can insert existing table data to another table in a single
trip. But the table structure should be same.
Syntax:
Insert into <table1> select * from <table2>;
Ex:
Page 28 of 90
2.6
Aliases
COLUMN ALIASES
Syntax:
Select <orginal_col> <alias_name> from <table_name>;
Ex:
SQL> select no sno from student;
Or
SQL> select no as sno from student;
TABLE ALIASES
If you are using table aliases you can use dot method to the columns.
Syntax:
Select <alias_name>.<col1>, <alias_name>.<col2>
<alias_name>.<coln> from <table_name> <alias_name>;
Ex:
SQL> select s.no, s.name from student s;
2.7
Functions
SQL functions are built into Oracle Database and are available for use in
various appropriate SQL statements.
Functions can be categorized as follows.
Page 29 of 90
2.7.1 SINGLE
ROW
FUNCTIONS
Single row functions can be categorized into five. These will be applied for
each row and produces individual output for each row.
Numeric functions
String functions
Date functions
Miscellaneous functions
Conversion functions
2.7.1.1.1
Numeric Functions
MOD(1,5) MOD(NULL,NULL)
MOD(0,0) MOD(-7,4)
---------- --------------------1
----------- ------------0
-3
NVL:
Page 30 of 90
This will substitutes the specified value in the place of null values.
Syntax: nvl (null_col, replacement_value)
Ex:
SQL> select * from student; -- here for 3rd row marks value is null
NO NAME
MARKS
--- -------
---------
100
200
NAME
NVL(MARKS,300)
---
-------
---------------------
100
200
300
ROUND:
This will rounds numbers to a given number of digits of precision.
Syntax: round (value, precision)
Ex:
SQL>
Page 31 of 90
--------------------123
123.23
123.24
GREATEST:
This will give the greatest number.
Syntax: greatest (value1, value2, value3 valuen)
Ex:
SQL> select greatest(1, 2, 3), greatest(-1, -2, -3) from dual;
GREATEST(1,2,3) GREATEST(-1,-2,-3)
-------------------- ----------------------3
-1
TRUNC (number) :
The TRUNC (number) function returns n truncated to m decimal places.
SELECT TRUNC(15.79,1) "Truncate" FROM DUAL;
Truncate
---------15.7
Page 32 of 90
Ltrim
Rtrim
Trim
Translate
Replace
Soundex
Concat ( || Concatenation operator)
Ascii
Chr
Substr
Instr
Decode
Greatest
Least
Coalesce
a) INITCAP
This will capitalize the initial letter of the string.
Syntax: initcap (string)
Ex:
SQL> select initcap('computer') from dual;
INITCAP
----------Computer
b) UPPER
This will convert the string into uppercase.
Page 33 of 90
8
e) RPAD
This will allows you to pad the right side of a column with any set of
characters.
Syntax: rpad (string, length [, padding_char])
Ex:
SQL> select rpad('computer',15,'*'), rpad('computer',15,'*#') from dual;
RPAD('COMPUTER' RPAD('COMPUTER'
---------------------- ---------------------computer*******
computer*#*#*#*
---------------------
*******computer
*#*#*#*computer
Page 35 of 90
This will trim off unwanted characters from the left end of string.
Syntax: ltrim (string [,unwanted_chars])
Ex:
SQL> select ltrim('computer','co'), ltrim('computer','com') from dual;
LTRIM( LTRIM
-------- --------mputer
puter
LTRIM('C LTRIM('C
----------
----------
computer
computer
comput
compu
----------
computer
computer
i) TRIM
This will trim off unwanted characters from the both sides of string.
Syntax: trim (unwanted_chars from string)
Ex:
SQL> select trim( 'i' from 'indiani') from dual;
TRIM(
----ndian
SQL> select trim( leading'i' from 'indiani') from dual; -- this will
work as LTRIM
TRIM(L
-----ndiani
Page 37 of 90
SQL> select trim( trailing'i' from 'indiani') from dual; -- this will
work as RTRIM
TRIM(T
-----Indian
j) TRANSLATE
This will replace the set of characters, character by character.
Syntax: translate (string, old_chars, new_chars)
Ex:
SQL> select translate('india','in','xy') from dual;
TRANS
-------xydxa
k) REPLACE
This will replace the set of characters, string by string.
Syntax: replace (string, old_chars [, new_chars])
Ex:
SQL> select replace('india','in','xy'), replace(india,in) from dual;
REPLACE
REPLACE
----------- ----------Xydia
dia
Page 38 of 90
m) CONCAT
This will be used to combine two strings only.
Syntax: concat (string1, string2)
Ex:
SQL> select concat('computer',' operator') As Name from dual;
Name
------------------------computer operator
If you want to combine more than two strings you have to use
concatenation
Operator(||).
SQL> select 'how' || ' are' || ' you' from dual;
'HOW'||'ARE
--------------how are you
n) ASCII
This will return the decimal representation in the database character
set of the first
character of the string.
Syntax: ascii (string)
Ex:
Page 39 of 90
97
o) CHR
This will return the character having the binary equivalent to the string
in either the database character set or the national character set.
Syntax: chr (number)
Ex:
SQL> select chr(97) from dual;
CHR
----a
p) SUBSTR
This will be used to extract substrings.
Syntax: substr (string, start_chr_count [, no_of_chars])
Ex:
SQL> select substr('computer',2), substr('computer',2,5),
substr('computer',3,7) from dual;
SUBSTR( SUBST SUBSTR
---------- -------
--------
omputer omput
mputer
Page 40 of 90
q) INSTR
This will allows you for searching through a string for set of characters.
Syntax: instr (string, search_str [, start_chr_count [, occurrence] ])
Ex:
SQL> select instr('information','o',4,1), instr('information','o',4,2)
from dual;
INSTR('INFORMATION','O',4,1) INSTR('INFORMATION','O',4,2)
------------------------------------ ------------------------------------4
10
Page 41 of 90
SAL
-----
DECODE
---------
500
Low
2500
Medium
2000
Medium
3500
Medium
DECODE(1,1,3) DECODE(1,2,3,4,4,6)
----------------- -----------------------3
from dual;
GREAT GREAT
------- ------c
srinu
saketh
2.7.1.1.3
DATE FUNCTIONS
Systimestamp
Localtimestamp
Dbtimezone
Sessiontimezone
To_char
To_date
Add_months
Months_between
Next_day
Last_day
Extract
Greatest
Least
Round
Trunc
New_time
Coalesce
a) SYSDATE
This will give the current date and time.
Ex:
SQL> select sysdate from dual;
SYSDATE
----------24-DEC-06
b) CURRENT_DATE
This will returns the current date in the sessions timezone.
Page 44 of 90
Ex:
SQL> select current_date from dual;
CURRENT_DATE
-----------------24-DEC-06
c) CURRENT_TIMESTAMP
This will returns the current timestamp with the active time zone
information.
Ex:
SQL> select current_timestamp from dual;
CURRENT_TIMESTAMP
--------------------------------------------------------------------------24-DEC-06 03.42.41.383369 AM +05:30
d) SYSTIMESTAMP
This will returns the system date, including fractional seconds and time
zone of the
database.
Ex:
SQL> select systimestamp from dual;
SYSTIMESTAMP
--------------------------------------------------------------------------24-DEC-06 03.49.31.830099 AM +05:30
Page 45 of 90
h) TO_CHAR
This will be used to extract various date formats.
The available date formats as follows.
Syntax: to_char (date, format)
DATE FORMATS
D
--
No of days in week
DD
--
No of days in month
DDD
--
No of days in year
MM
--
No of month
MON
--
MONTH
--
RM
--
DY
--
DAY
--
--
YY
--
YYY
--
YYYY
--
SYYYY
--
Signed year
--
IY
--
IYY
--
IYYY
--
Y, YYY
--
YEAR
--
CC
--
Century
--
No of quarters
--
No of weeks in month
WW
--
No of weeks in year
IW
--
HH
--
Hours
MI
--
Minutes
SS
--
Seconds
FF
--
Fractional seconds
AM or PM
--
A.M or P.M --
AD or BC
--
A.D or B.C --
FM
--
--
Suffix to a number
month or day
TH
Page 47 of 90
SP
--
SPTH
--
THSP
--
same as SPTH
out
Page 48 of 90
month * day')
from dual;
TO_CHAR(TO_DATE('24/DEC/20
-------------------------24 * december * Sunday
-- If you are not using to_char oracle will display output in default
date format.
j) ADD_MONTHS
This will add the specified months to the given date.
Syntax: add_months (date, no_of_months)
Ex:
SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), 5)
from dual;
ADD_MONTHS
---------------11-JUN-90
SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), -5)
from dual;
ADD_MONTH
--------------11-AUG-89
If no_of_months is zero then it will display the same date.
If no_of_months is null then it will display nothing.
Page 49 of 90
k) MONTHS_BETWEEN
This will give difference of months between two dates.
Syntax: months_between (date1, date2)
Ex:
SQL> select months_between(to_date('11-aug-1990','dd-monyyyy'), to_date('11-jan-1990','dd-mon-yyyy')) from dual;
MONTHS_BETWEEN(TO_DATE('11-AUG-1990','DD-MON-YYYY'),TO_DATE('11-JAN-1990','DD-MONYYYY'))
----------------------------------------------------------------------------------------------7
MONTHS_BETWEEN(TO_DATE('11-JAN-1990','DD-MON-YYYY'),TO_DATE('11-AUG1990','DD-MON-YYYY'))
-------------------------------------------------------------------------------------------------7
l) NEXT_DAY
This will produce next day of the given day from the specified date.
Syntax: next_day (date, day)
Ex:
SQL> select next_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun')
from dual;
NEXT_DAY(
Page 50 of 90
------------31-DEC-06
-- If the day parameter is null then it will display nothing.
m) LAST_DAY
This will produce last day of the given date.
Syntax: last_day (date)
Ex:
SQL> select last_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun')
from dual;
LAST_DAY(
------------31-DEC-06
o) GREATEST
This will give the greatest date.
Syntax: greatest (date1, date2, date3 daten)
Ex:
SQL> select greatest(to_date('11-jan-90','dd-mon-yy'),to_date('11mar-90','dd-mon-yy'),to_date('11-apr-90','dd-mon-yy')) from dual;
GREATEST(
-------------
Page 51 of 90
11-APR-90
p) LEAST
This will give the least date.
Syntax: least (date1, date2, date3 daten)
Ex:
SQL> select least(to_date('11-jan-90','dd-mon-yy'),to_date('11mar-90','dd-mon-yy'),to_date('11-apr-90','dd-mon-yy')) from dual;
LEAST(
------------11-JAN-90
r) TRUNC
Trunc will chops off the date to which it was equal to or less than the
given date.
Syntax: trunc (date, (day | month | year))
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.
Ex:
Page 52 of 90
TRUNC(TO_ TRUNC(TO_
------------- -------------01-JAN-04
01-JAN-06
2.7.1.2
01-JAN-04
MISCELLANEOUS FUNCTIONS
a) RANK
This will give the non-sequential ranking.
Ex:
Select empno, ename, sal, r from (select empno, ename, sal, rank () over
(order by sal desc) r from EMP);
Empno
ename
sal
100
5000
200
5000
300
4000
Page 53 of 90
d) DENSE_RANK
This will give the sequential ranking.
The DENSE_RANK function works acts like the RANK function except
that it assigns consecutive ranks:
EX:
Select empno, ename, Sal, from (select empno, ename, sal, dense_rank
() over (order by sal desc) r from emp);
Empno
ename
sal
100
5000
200
5000
300
4000
SUM(SAL)
---------- ---------10
8750
20
10875
Page 54 of 90
30
9400
SUM(SAL)
---------- ---------
----------
10
CLERK
1300
10
MANAGER
10
PRESIDENT
5000
20
ANALYST
6000
20
CLERK
1900
20
MANAGER
30
CLERK
30
MANAGER
2850
30
SALESMAN
5600
2450
2975
950
HAVING
This will work as where clause which can
EMPNO
NAME
ADDRESS
COUNT
Page 55 of 90
---------- --------200
300
SHAM
MOHAN
---------HYD
BANG
-----3
2
DEPTNO
JOB
---------- ---------
TSAL
----------
20
ANALYST
6000
10
PRESIDENT
5000
30
SALESMAN
5600
ORDER OF EXECUTION
Group the rows together based on group by clause.
Calculate the group functions for each group.
Choose and eliminate the groups based on the having clause.
Order the groups based on the specified column.
2.8
Set Operators
Page 56 of 90
2.8.1 UNION
This will combine the records of multiple tables having the same structure.
Ex:
SQL> select * from student1
Union
select * from student2;
2.8.2 UNION ALL
This will combine the records of multiple tables having the same structure
but including duplicates.
Ex:
SQL> select * from student1 union all select * from student2;
2.8.3 INTERSECT
This will give the common records of multiple tables having the same
structure.
Ex:
SQL> select * from student1 intersect select * from student2;
2.8.4 MINUS
This will give the records of a table whose records are not in other tables
having the same structure.
Ex:
SQL> select * from student1 minus select * from student2;
2.9
Constraints
Page 57 of 90
TABLE LEVEL
Alter level
While adding constraints you need not specify the name but the type only,
oracle will internally name the constraint.
If you want to give a name to the constraint, you have to use the
constraint clause.
2.9.1 NOT NULL
This is used to avoid null values.
We can add this constraint in column level only.
Ex:
SQL> create table student(no number(2) not null, name varchar(10),
Page 58 of 90
marks
number(3));
TABLE LEVEL
SQL> create table student(no number(2) , name varchar(10), marks
number(3), check
ALTER LEVEL
SQL> alter table student add check(marks>300);
SQL> alter table student add constraint ch check(marks>300);
2.9.3 UNIQUE
This is used to avoid duplicates but it allow nulls.
We can add this constraint in all three levels.
Page 59 of 90
Ex:
COLUMN LEVEL
SQL> create table student(no number(2) unique, name varchar(10),
marks number(3));
SQL> create table student(no number(2) constraint un unique, name
varchar(10),
marks number(3));
TABLE LEVEL
SQL> create table student(no number(2) , name varchar(10),
marks number(3),
unique(no));
constraint un unique(no));
ALTER LEVEL
SQL> alter table student add unique(no);
SQL> alter table student add constraint un unique(no);
2.9.4 PRIMARY KEY
This is used to avoid duplicates and nulls. This will work as
combination of unique and not null.
Primary key always attached to the parent table.
Primary key will create Unique index by default.
We can add this constraint in all three levels.
Ex:
COLUMN LEVEL
SQL> create table student(no number(2) primary key, name
Page 60 of 90
varchar(10), marks
number(3));
marks number(3));
TABLE LEVEL
SQL> create table student(no number(2) , name varchar(10), marks
number(3),
primary key(no));
ALTER LEVEL
SQL> alter table student add primary key(no);
SQL> alter table student add constraint pk primary key(no);
2.9.5 FOREIGN KEY
This is used to reference the parent table primary key column which
allows duplicates.
Foreign key always attached to the child table.
We can add this constraint in table and alter levels only.
Ex:
TABLE LEVEL
SQL> create table emp(empno number(2), ename varchar(10), deptno
number(2),
Primary
key(empno),
foreign
key(deptno)
references
dept(deptno));
SQL> create table emp(empno number(2), ename varchar(10),
deptno number(2),
dept(deptno));
Page 61 of 90
ALTER LEVEL
SQL> alter table emp add foreign key(deptno) references
dept(deptno);
SQL> alter table emp add constraint fk foreign key(deptno)
references dept(deptno);
Once the primary key and foreign key relationship has been created then
you can not remove any parent record if the dependent childs exists.
USING ON DELTE 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.
Ex:
TABLE LEVEL
SQL> create table emp(empno number(2), ename varchar(10), deptno
number(2),
primary
dept(deptno) on delete
key(empno),
foreign
key(deptno)
references
cascade);
Page 62 of 90
ALTER LEVEL
SQL> alter table emp add foreign key(deptno) references
dept(deptno) on delete
cascade;
delete cascade;
unique(no,name));
constraint un unique(no,name));
primary key(no,name));
Page 63 of 90
dname
varchar(10),
key(deptno,dname) references
primary
key(empno),
foreign
dept(deptno,dname));
key(deptno,dname) references
dept(deptno,dname));
FOREIGN KEY (ALTER LEVEL)
SQL> alter table emp add foreign key(deptno,dname) references
dept(deptno,dname);
SQL> alter table emp add constraint fk foreign key(deptno,dname)
references
dept(deptno,dname);
2.10 Joins
If a join involves in more than two tables then oracle joins first two
tables based on the joins condition and then compares the result with
the next table and so on.
TYPES
Page 64 of 90
Equi join
Non-equi join
Self join
Natural join
Cross join
Outer join
Left outer
Right outer
Full outer
Inner join
Using clause
On clause
LOC
mkt
hyd
20
fin
bang
30
hr
bombay
EMPNO
ENAME
JOB
MGR
DEPTNO
Page 65 of 90
saketh
222
sudha
333
444
analyst
444
10
clerk
333
20
jagan
manager
111
10
madhu
engineer
222
40
ENAME
JOB
DNAME
LOC
saketh
analyst
mkt
333
jagan
manager mkt
222
sudha
clerk
fin
hyd
hyd
bang
USING CLAUSE
SQL> select empno,ename,job ,dname,loc from emp e join dept d
using(deptno);
EMPNO
ENAME
JOB
DNAME
LOC
111
saketh
analyst
mkt
333
jagan
manager mkt
222
sudha
clerk
fin
hyd
hyd
bang
ON CLAUSE
SQL>
on(e.deptno=d.deptno);
EMPNO
ENAME
JOB
DNAME
LOC
saketh
analyst
mkt
333
jagan
manager mkt
222
sudha
clerk
fin
hyd
hyd
bang
d.deptno;
EMPNO
ENAME
JOB
DNAME
LOC
sudha
clerk
mkt
hyd
444
madhu
engineer
mkt
hyd
444
madhu
engineer
fin
bang
444
madhu
engineer
hr
bombay
Page 67 of 90
e1.mgr=e2.empno;
EMPNO
ENAME
JOB
DEPTNO
jagan
analyst
10
222
madhu
clerk
40
333
sudha
manager
20
444
saketh
engineer
10
ENAME
JOB
DNAME
LOC
saketh
analyst
mkt
hyd
333
jagan
manager
mkt
hyd
222
sudha
clerk
fin
bang
Ex:
SQL> select empno,ename,job,dname,loc from emp cross join dept;
EMPNO ENAME
JOB
DNAME
LOC
saketh
analyst
mkt
hyd
222
sudha
clerk
mkt
hyd
333
jagan
manager
mkt
hyd
444
madhu
engineer
mkt
hyd
111
saketh
analyst
fin
bang
222
sudha
clerk
fin
bang
333
jagan
manager
fin
bang
444
madhu
engineer
fin
bang
111
saketh
analyst
hr
bombay
222
sudha
clerk
hr
bombay
333
jagan
manager
hr
bombay
444
madhu
engineer
hr
bombay
This will display the all matching records from both the tables and also
Page 69 of 90
non matching records from opposite side outer join symbol table.
Ex:
SQL> select empno,ename,job,dname,loc from emp e left outer join
dept d
on(e.deptno=d.deptno);
Or
ENAME
JOB
DNAME
LOC
2.10.6.2
111
saketh
analyst
mkt
hyd
333
jagan
manager
mkt
hyd
222
sudha
clerk
fin
bang
444
madhu
engineer
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.
Ex:
SQL> select empno,ename,job,dname,loc from emp e right outer join
dept d on(e.deptno=d.deptno);
Or
SQL> select empno,ename,job,dname,loc from emp e,dept d where
e.deptno(+) =
d.deptno;
Page 70 of 90
EMPNO
ENAME
JOB
DNAME
LOC
saketh
analyst
mkt
hyd
333
jagan
manager
mkt
hyd
222
sudha
clerk
fin
bang
hr
2.10.6.3
bombay
This will display the all matching records and the non-matching records
from both tables.Union between Left and Right outer joins nothing but Full
Outer join.
Ex:
SQL> select empno,ename,job,dname,loc from emp e right outer join
dept d
on(e.deptno=d.deptno)
UNION
d.deptno;
OR
SQL> select empno,ename,job,dname,loc from emp e full outer join
dept d
on(e.deptno=d.deptno);
EMPNO
ENAME
JOB
DNAME
LOC
Page 71 of 90
333
jagan
manager
mkt
hyd
111
saketh
analyst
mkt
hyd
222
sudha
clerk
fin
bang
444
madhu
engineer
hr
bombay
ENAME
JOB
DNAME
LOC
saketh
analyst
mkt
hyd
333
jagan
manager
mkt
hyd
222
sudha
clerk
fin
bang
2.11.1 CASE
Case is similar to decode but easier to understand while going through
coding
Ex:
SQL> Select sal,
Case sal
When 500 then low
Page 72 of 90
From emp;
SAL
CASE
-----
--------
500
low
2500
medium
2000
medium
3500
medium
3000
medium
5000
high
4000
medium
2.11.2 Decode ()
From emp;
Page 73 of 90
You can use merge command to perform insert and update in a single
command.
Ex: Merge into student1 s1
Using (select * from student2) s2
On (s1.no=s2.no)
When matched then
Update set marks = s2.marks
When not matched then
Insert (s1.no, s1.name, s1.marks)
s2.marks);
2.13.1.1
Page 74 of 90
empno = 7566);
EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
2.13.1.2
7788
SCOTT
ANALYST
7566
7839
KING
PRESIDENT
7902
FORD
ANALYST
19-APR-87
3000
20
17-NOV-81 5000
7566
03-DEC-81
3000
10
20
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.
Ex:
SQL> select * from emp where sal > any (select sal from emp where
sal between 2500 and 4000);
EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
7566
JONES
MANAGER
7839 02-APR-81
2975
20
7788
SCOTT
ANALYST
7566 19-APR-87
3000
20
7839
KING
PRESIDENT
7902
FORD
ANALYST
17-NOV-81
7566 03-DEC-81
5000
10
3000
20
Page 75 of 90
Find all employees who earn more than the average salary in their
department.
SQL> SELECT last-named, salary, department_id FROM employees A
WHERE salary > (SELECT AVG (salary) FROM employees B WHERE
B.department_id =A.department_id
Group by B.department_id)
2.13.3 EXISTS
The EXISTS operator tests for existence of rows in the results set of the
subquery.
SQL> Select dname from dept where exists
(select 1 from EMP
where dept.deptno= emp.deptno);
2.14
2.14.1 VIEWS
Page 76 of 90
TYPES
Simple view
Complex view
Simple view can be created from one table where as complex view can be
created from multiple tables.
We can do DML on Simple view but not on Complex views.
WHY VIEWS?
Provides additional level of security by restricting access to a
predetermined set of rows and/or columns of a table.
Ex:
SQL> Create view dept_v as select *from dept;
SQL> Create view dept_v as select deptno, sum(sal) t_sal from emp
group by deptno;
SQL> Select * from dept_v ;
DROPPING VIEWS
SQL> drop view dept_v;
2.14.2 INLINE VIEW
If we write a select statement in from clause that is nothing but inline
view.
Ex: Get dept wise max sal along with empname and emp no.
SQL> Select a.empname, a.empno, b.sal, b.deptno
From EMP a, (Select max (sal) sal, deptno from EMP group by
deptno) b
Page 77 of 90
Where
a.sal=b.sal and
a.deptno=b.deptno
SQL> Select ename, sal, rownum rank from (select *from emp order by
sal);
ENAME
SAL
RANK
800
JAMES
950
ADAMS
1100
WARD
1250
Syntax:
CREATE MATERIALIZED HWMD_MTH_ALL_METRICS_CURR_MV
REFRESH COMPLETE
START WITH sysdate
NEXT TRUNC(SYSDATE+1)+ 4/24
WITH PRIMARY KEY
AS
Select * from HWMD_MTH_ALL_METRICS_CURR_VW;
Another Method to refresh MV:
DBMS_MVIEW.REFRESH('MV_COMPLEX', 'C');
Or
we can use Informatica mapping to refresh Materialized views.
Page 78 of 90
Materialized view
2.15 Indexes
We can create indexes explicitly to speed up SQL statement execution on
a table. The index points directly to the location of the rows containing the
value.
WHY INDEXES?
Indexes are most useful on larger tables, on columns that are likely to
appear in where clauses as simple equality.
TYPES
Unique index
Non-unique index
Btree index
Bitmap index
Page 79 of 90
Composite index
Function-based index
Cluster index
2.15.1 UNIQUE INDEX
Unique indexes guarantee that no two rows of a table have duplicate
values in the columns that define the index. Unique index is automatically
created when primary key or unique constraint is created.
Ex:
SQL> create unique index stud_ind on student(sno);
2.15.2 NON-UNIQUE INDEX
Non-Unique indexes do not impose the above restriction on the column
values.
Ex:
SQL> create index stud_ind on student(sno);
2.15.3 BTREE INDEX or ASCENDING INDEX
The default type of index used in an oracle database is the btree index. A
btree index is designed to provide both rapid access to individual rows and
quick access to groups of rows within a range. The btree index does this
by performing a succession of value comparisons. Each comparison
eliminates many of the rows.
Ex:
SQL> create index stud_ind on student(sno);
2.15.4 BITMAP INDEX
This can be used for low cardinality columns: that is columns in which the
number of distinct values is snall when compared to the number of the
rows in the table.
Page 80 of 90
Ex:
SQL> create bitmap index stud_ind on student(sex);
2.15.5 COMPOSITE INDEX
A composite index also called a concatenated index is an index created on
multiple columns of a table. Columns in a composite index can appear in
any order and need not be adjacent columns of the table.
Ex:
SQL> create bitmap index stud_ind on student(sno, sname);
2.16 Query Tuning approach
What is your tuning approach if SQL query taking long time? Or how do u
tune SQL query?
If query taking long time then we need to run the query in Explain Plan it
will give us execution plan of the query like whether the query is using the
relevant indexes on the joining columns or not .
If joining columns doesnt have index then it will do the full table scan if it
is full table scan the cost will be more then we have to create the indexes
on the joining columns and will run the query it should give better
performance .
And also needs to analyze the tables if analyzation happened long back. It
may causes performance.
The ANALYZE statement can be used to gather statistics for a specific
table, index or cluster using
ANALYZE TABLE employees COMPUTE STATISTICS;
If still has performance issue then will use HINTS, hint is nothing but a
clue. We can use hints in select statement like
Use Hint to force using index
SELECT /*+INDEX (TABLE_NAME INDEX_NAME) */ COL1,COL2 FROM
TABLE_NAME
Page 81 of 90
ALL_ROWS
One of the hints that 'invokes' the Cost based optimizer
ALL_ROWS is usually used for batch processing or data warehousing
systems.
FIRST_ROWS
One of the hints that 'invokes' the Cost based optimizer
FIRST_ROWS is usually used for OLTP systems.
CHOOSE
One of the hints that 'invokes' the Cost based optimizer
This hint lets the server choose (between ALL_ROWS and
FIRST_ROWS, based on statistics gathered.
HASH
Hashes one table (full scan) and creates a hash index for that table.
Then hashes other table and uses hash index to find corresponding
records. Therefore not suitable for < or > join conditions.
/*+ use_hash */
Select ( /*+ hash */ ) empno from
Page 82 of 90
Rowid
Row-num
Rowid is permanent.
Row-num is temporary.
Having clause
Both where and having clause can be used to filter the data.
Where as in where clause it is not
mandatory.
Page 83 of 90
Co-related sub-query
Example:
Example:
Functions
Stored as a pseudo-code in
Stored Procedures
Page 85 of 90
Packages:
Packages provide a method of encapsulating related procedures,
functions, and associated cursors and variables together as a unit in the
database.
package that contains several procedures and functions that process
related to same transactions.
A package is a group of related procedures and functions, together with
the cursors and variables they use,
Packages provide a method of encapsulating related procedures,
functions, and associated cursors and variables together as a unit in the
database.
2.18.2 Triggers:
Oracle lets you define procedures called triggers that run implicitly when
an INSERT, UPDATE, or DELETE statement is issued against the
associated table
Triggers are similar to stored procedures. A trigger stored in the
database can include SQL and PL/SQL
Types of Triggers
This section describes the different types of triggers:
Page 86 of 90
INSTEAD OF Triggers
Row Triggers
A row trigger is fired each time the table is affected by the triggering
statement. For example, if an UPDATE statement updates multiple rows of
a table, a row trigger is fired once for each row affected by the UPDATE
statement. If a triggering statement affects no rows, a row trigger is not
run.
A statement trigger is fired once on behalf of the triggering statement,
regardless of the number of rows in the table that the triggering statement
affects, even if no rows are affected. For example, if a DELETE statement
deletes several rows from a table, a statement-level DELETE trigger is fired
only once.
BEFORE and AFTER Triggers
When defining a trigger, you can specify the trigger timing--whether the
trigger action is to be run before or after the triggering statement.
BEFORE and AFTER apply to both statement and row triggers.
BEFORE and AFTER triggers fired by DML statements can be defined only
on tables, not on views.
CREATE
OR
REPLACE
AFTER INSERT
TRIGGER
EMP_AUR
ON EMP
DECLARE
BEGIN
Delete from X;
Commit;
END;
2.19 IMPORTANT QUERIES
1. Get duplicate rows from the table:
Select empno, count (*) from EMP group by empno having count (*)>1;
Page 87 of 90
No
Add1
Add2
Abc
100
Hyd
bang
Xyz
200
Mysore
pune
Hierarchical queries
Starting at the root, walk from the top down, and eliminate employee
Higgins in the result, but
process the child rows.
Page 89 of 90
Page 90 of 90