Oracle Study
Oracle Study
Table of Contents
1 INTRODUCTION 3
1.1 Purpose 3
2 ORACLE 3
2.1 What is Oracle? 3
2.2 SQL is divided into the following 3
2.2.1 CREATE (DDL) 4
2.2.2 INSERT (DML) 5
2.2.3 Commit (TCL) 7
2.2.4 SELECT (DRL) 7
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
2.5 How to take Backup table data? 28
2.6 Aliases 29
2.7 Functions 30
2.7.1 SINGLE ROW FUNCTIONS 30
2.7.2 GROUP BY AND HAVING 55
2.8 Set Operators 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 88
2.9.6 COMPOSITE KEYS 64
2.10 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 () 74
2.11.1 CASE 74
2.11.2 Decode () 75
2.12 Merge Statement 75
2.13 Sub Queries, Co-Related Queries and EXISTS clause 75
2.13.1 SUB QUERIES 75
2.13.2 CORRELATED SUBQUERIES 77
2.13.3 EXISTS 77
2.14 Views, Inline Views and Materialized Views 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 BTREE INDEX or ASCENDING INDEX 82
2.15.4 BITMAP INDEX 82
2.15.5 COMPOSITE INDEX 82
2.16 Query Tuning approach 82
2.17 Differences 84
2.17.1 ROWID & ROW_NUM 84
2.17.2 WHERE & HAVING 85
2.17.3 SUB QUERY & CO_RELATED SUB QUERY 85
2.17.4 STORE PROCEDURE & FUNCTION 86
2.17.5 Trigger & Procedure 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 88
1 INTRODUCTION
1.1 Purpose
The purpose of this document is to provide the detailed information
about Oracle-SQL based on Real-Time for beginners.
2 ORACLE
Page 3 of 88
DRL -- select
Max Size:
Data types Description
Oracle 11g
Page 4 of 88
Ex:
SQL> create table student (no number (2), name varchar2 (10),
Address varchar2 (50));
By value method
By address method
Syntax:
Ex:
EMP
NO NAME DOJ
Page 5 of 88
command, if there are lot of records this will be difficult.
Syntax:
This will prompt you for the values but for every insert you have to use
forward slash.
Ex:
SQL> /
Syntax:
Page 6 of 88
Ex:
SQL> commit;
Syntax:
Or
Ex:
NO NAME address
1 sham hyd
2 mohan mpl
Page 7 of 88
SQL> select no, name, address from student;
NO NAME address
1 sham hyd
2 mohan mpl
NO NAME
--- -------
1 Sham
2 mohan
Where
Order by
USING WHERE
Syntax:
The following are the different types of operators used in where clause.
Arithmetic operators
Comparison operators
Page 8 of 88
Logical operators
Arithmetic operators -- highest precedence
+, -, *, /
Comparison operators
=, !=, >, <, >=, <=, <>
between, not between
in, not in
null, not null
like
Logical operators
And
Or -- lowest precedence
Not
a) USING =, >, <, >=, <=, !=, <>
Ex:
NO NAME MARKS
2 Saketh 200
2 Naren 400
NO NAME MARKS
Page 9 of 88
1 Sudha 100
1 Jagan 300
NO NAME MARKS
3 Ramesh
4 Madhu
5 Visu
6 Rattu
NO NAME MARKS
1 Sudha 100
2 Saketh 200
1 Jagan 300
2 Naren 400
NO NAME MARKS
2 Saketh 200
2 Naren 400
Page 10 of 88
3 Ramesh
4 Madhu
5 Visu
6 Rattu
NO NAME MARKS
1 Sudha 100
1 Jagan 300
3 Ramesh
4 Madhu
NO NAME MARKS
1 Sudha 100
1 Jagan 300
3 Ramesh
4 Madhu
5 Visu
6 Rattu
b) USING AND
Page 11 of 88
This will gives the output when all the conditions become true.
Syntax:
Ex:
NO NAME MARKS
2 Saketh 200
2 Naren 400
c) USING OR
This will gives the output when either of the conditions becomes true.
Syntax:
Ex:
NO NAME MARKS
2 Saketh 200
1 Jagan 300
d) USING BETWEEN
Page 12 of 88
This will gives the output based on the column and its lower bound,
upper bound.
Syntax:
Ex:
SQL> select * from student where marks between 200 and 400;
NO NAME MARKS
2 Saketh 200
1 Jagan 300
2 Naren 400
This will gives the output based on the column which values are not in
its lower bound, upper bound.
Syntax:
Ex:
SQL> select * from student where marks not between 200 and 400;
NO NAME MARKS
Page 13 of 88
1 Sudha 100
f) USING IN
This will gives the output based on the column and its list of values
specified.
Syntax:
Ex:
NO NAME MARKS
1 Sudha 100
2 Saketh 200
1 Jagan 300
2 Naren 400
3 Ramesh
g) USING NOT IN
This will gives the output based on the column which values are not in
the list of values specified.
Syntax:
Page 14 of 88
Ex:
NO NAME MARKS
4 Madhu
5 Visu
6 Rattu
h) USING NULL
This will gives the output based on the null values in the specified
column.
Syntax:
Ex:
NO NAME MARKS
3 Ramesh
4 Madhu
5 Visu
6 Rattu
Page 15 of 88
i) USING NOT NULL
This will gives the output based on the not null values in the specified
column.
Syntax:
Ex:
NO NAME MARKS
1 Sudha 100
2 Saketh 200
1 Jagan 300
2 Naren 400
j) USING LIKE
This will be used to search through the rows of database column based
on the pattern you specify.
Syntax:
Ex:
NO NAME MARKS
Page 16 of 88
--- ------- ---------
1 Sudha 100
ii) This will give the rows whose name start with ‘S’.
NO NAME MARKS
1 Sudha 100
2 Saketh 200
iii) This will give the rows whose name ends with ‘h’.
NO NAME MARKS
2 Saketh 200
3 Ramesh
iV) This will give the rows whose name’s second letter start with ‘a’.
NO NAME MARKS
2 Saketh 200
1 Jagan 300
Page 17 of 88
2 Naren 400
3 Ramesh
4 Madhu
6 Rattu
V) This will give the rows whose name’s third letter start with ‘d’.
NO NAME MARKS
1 Sudha 100
4 Madhu
Vi) This will give the rows whose name’s second letter start with ‘t’
from ending.
NO NAME MARKS
2 Saketh 200
6 Rattu
Viii) This will give the rows whose name cotains 2 a’s.
NO NAME MARKS
Page 18 of 88
1 Jagan 300
USING ORDER BY
Syntax:
If you want output in descending order you have to use desc keyword after
the column.
Ex:
NO NAME MARKS
1 Sudha 100
1 Jagan 300
2 Saketh 200
2 Naren 400
3 Ramesh
4 Madhu
NO NAME MARKS
Page 19 of 88
--- ------- ---------
4 Madhu
3 Ramesh
2 Saketh 200
2 Naren 400
1 Sudha 100
1 Jagan 300
USING UPDATE
Syntax:
Ex:
If you are not specifying any condition this will update entire table.
Page 20 of 88
Need to issue commit since Delete is DML
Syntax:
Ex:
If you are not specifying any condition this will delete entire table.
Syntax:
Ex:
Page 21 of 88
No need commit since drop is DDL
Syntax:
Ex:
USING ALTER
This can be used to add or remove columns and to modify the precision of
the data type.
a) ADDING COLUMN
Syntax:
Ex:
b) REMOVING COLUMN
Syntax:
Ex:
Page 22 of 88
Syntax:
Ex:
e) RENAMING COLUMN
Syntax:
Ex:
USING RENAME
Syntax:
Ex:
USING COMMIT
Page 23 of 88
Commit is of two types.
Implicit
Explicit
a) IMPLICIT
Syntax:
USING ROLLBACK
Up to previous commit
Up to previous rollback
Syntax:
Or
* While process is going on, if suddenly power goes then oracle will
rollback the transaction.
Page 24 of 88
USING SAVEPOINT
Syntax:
Savepoint <savepoint_name>;
USING GRANT
Syntax:
Ex:
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.
The abc user can not grant permission on student table to other users.
To get this type of option use the following.
Page 25 of 88
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:
Ex:
SQL> revoke select, insert on student from abc; -- you can revoke set
of privileges
SQL> revoke all on student from abc; -- you can revoke all privileges
2.3 Synonym
A synonym is a similar named object, which is used as an alias for a table,
view or sequence.
TYPES
Private
Public
Private synonym is available to the particular user who creates.
ADVANTAGES
Page 26 of 88
CREATE AND DROP
2.4 Dblink
To access a tables or views or sequence from one database to another
database.
Syntax:
We can create a table using existing table [along with data] Called it as
Back up tables.
Syntax:
Ex:
Page 27 of 88
student;
In the above where clause give any condition which does not satisfy.
Using this we can insert existing table data to another table in a single
trip. But the table structure should be same.
Syntax:
Ex:
SQL> insert into student1 (no, name) select no, name from student;
2.6 Aliases
COLUMN ALIASES
Syntax:
Ex:
Page 28 of 88
Or
TABLE ALIASES
If you are using table aliases you can use dot method to the columns.
Syntax:
Ex:
2.7 Functions
SQL functions are built into Oracle Database and are available for use in
various appropriate SQL statements.
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
Page 29 of 88
Numeric functions accept numeric input and return numeric values
MOD:
Ex:
SQL> select mod(7,4), mod(1,5), mod(null, null), mod(0,0), mod(-7,4) from dual;
3 1 0 -3
NVL:
This will substitutes the specified value in the place of null values.
Ex:
SQL> select * from student; -- here for 3rd row marks value is null
NO NAME MARKS
1 a 100
2 b 200
3 c
Page 30 of 88
NO NAME NVL(MARKS,300)
1 a 100
2 b 200
3 c 300
ROUND:
Ex:
GREATEST:
Ex:
GREATEST(1,2,3) GREATEST(-1,-2,-3)
-------------------- -----------------------
3 -1
TRUNC (number) :
Page 31 of 88
The TRUNC (number) function returns n truncated to m decimal places.
Truncate
----------
15.7
Character functions that return character values return values of the same
datatype as the input argument.
Initcap
Upper
Lower
Length
Rpad
Lpad
Ltrim
Rtrim
Trim
Translate
Replace
Soundex
Concat ( ‘ || ‘ Concatenation operator)
Ascii
Chr
Substr
Instr
Decode
Greatest
Least
Coalesce
a) INITCAP
Page 32 of 88
Syntax: initcap (string)
Ex:
INITCAP
-----------
Computer
b) UPPER
Ex:
UPPER
-----------
COMPUTER
c) LOWER
Ex:
LOWER
-----------
Page 33 of 88
computer
d) LENGTH
Ex:
LENGTH
-----------
e) RPAD
This will allows you to pad the right side of a column with any set of
characters.
Ex:
RPAD('COMPUTER' RPAD('COMPUTER'
---------------------- ----------------------
computer******* computer*#*#*#*
f) LPAD
This will allows you to pad the left side of a column with any set of
characters.
Page 34 of 88
Syntax: lpad (string, length [, padding_char])
Ex:
LPAD('COMPUTER' LPAD('COMPUTER'
--------------------- ---------------------
*******computer *#*#*#*computer
g) LTRIM
This will trim off unwanted characters from the left end of string.
Ex:
LTRIM( LTRIM
-------- ---------
mputer puter
LTRIM('C LTRIM('C
---------- ----------
computer computer
Page 35 of 88
h) RTRIM
This will trim off unwanted characters from the right end of string.
Ex:
RTRIM( RTRIM
-------- ---------
comput compu
RTRIM('C RTRIM('C
---------- ----------
computer computer
i) TRIM
This will trim off unwanted characters from the both sides of string.
Ex:
TRIM(
Page 36 of 88
-----
ndian
SQL> select trim( leading'i' from 'indiani') from dual; -- this will work
as LTRIM
TRIM(L
------
ndiani
SQL> select trim( trailing'i' from 'indiani') from dual; -- this will work
as RTRIM
TRIM(T
------
Indian
j) TRANSLATE
Ex:
TRANS
--------
xydxa
k) REPLACE
Page 37 of 88
Syntax: replace (string, old_chars [, new_chars])
Ex:
REPLACE REPLACE
----------- -----------
Xydia dia
m) CONCAT
Ex:
Name
-------------------------
computer operator
If you want to combine more than two strings you have to use
concatenation
Operator(||).
'HOW'||'ARE
---------------
Page 38 of 88
n) ASCII
This will return the decimal representation in the database character set
of the first
Ex:
ASCII('A') ASCII('APPLE')
------------ ------------------
97 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.
Ex:
CHR
-----
p) SUBSTR
Page 39 of 88
Ex:
q) INSTR
This will allows you for searching through a string for set of characters.
Ex:
INSTR('INFORMATION','O',4,1) INSTR('INFORMATION','O',4,2)
------------------------------------ -------------------------------------
4 10
r) DECODE
For every value of field, it will checks for a match in a series of if/then
Page 40 of 88
tests.
Ex:
SAL DECODE
----- ---------
500 Low
2500 Medium
2000 Medium
3500 Medium
DECODE(1,1,3) DECODE(1,2,3,4,4,6)
----------------- ------------------------
3 6
If the number of parameters are odd and different then decode will
display
nothing.
If all the parameters are null then decode will display nothing.
If all the parameters are zeros then decode will display zero.
Page 41 of 88
s) GREATEST
Ex:
GREAT GREAT
------- -------
c srinu
Ex:
LEAST LEAST
------- -------
a saketh
Page 42 of 88
2.7.1.1.3 DATE FUNCTIONS
Sysdate
Current_date
Current_timestamp
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
Ex:
SYSDATE
-----------
Page 43 of 88
24-DEC-06
b) CURRENT_DATE
Ex:
CURRENT_DATE
------------------
24-DEC-06
c) CURRENT_TIMESTAMP
This will returns the current timestamp with the active time zone
information.
Ex:
CURRENT_TIMESTAMP
---------------------------------------------------------------------------
d) SYSTIMESTAMP
This will returns the system date, including fractional seconds and time
zone of the
database.
Ex:
Page 44 of 88
SYSTIMESTAMP
---------------------------------------------------------------------------
h) TO_CHAR
DATE FORMATS
D -- No of days in week
DD -- No of days in month
MM -- No of month
Page 45 of 88
YYYY -- Full four digit year
CC -- Century
Q -- No of quarters
W -- No of weeks in month
WW -- No of weeks in year
HH -- Hours
MI -- Minutes
SS -- Seconds
FF -- Fractional seconds
Page 46 of 88
FM -- Prefix to month or day, suppresses padding of
month or day
TH -- Suffix to a number
TO_CHAR(SYSDATE,'DDMONTHYEAR')
-------------------------------------------------------
-------------------------------------------------------
TO_CHAR(S
------------
24th 24TH
i) TO_DATE
Page 47 of 88
Ex:
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
Ex:
ADD_MONTHS
----------------
11-JUN-90
ADD_MONTH
---------------
11-AUG-89
Page 48 of 88
If no_of_months is zero then it will display the same date.
If no_of_months is null then it will display nothing.
k) MONTHS_BETWEEN
Ex:
MONTHS_BETWEEN(TO_DATE('11-AUG-1990','DD-MON-YYYY'),TO_DATE('11-JAN-1990','DD-MON-
YYYY'))
-----------------------------------------------------------------------------------------------
MONTHS_BETWEEN(TO_DATE('11-JAN-1990','DD-MON-YYYY'),TO_DATE('11-AUG-1990','DD-
MON-YYYY'))
-------------------------------------------------------------------------------------------------
-7
l) NEXT_DAY
This will produce next day of the given day from the specified date.
Ex:
Page 49 of 88
NEXT_DAY(
-------------
31-DEC-06
m) LAST_DAY
Ex:
LAST_DAY(
-------------
31-DEC-06
o) GREATEST
Ex:
GREATEST(
-------------
Page 50 of 88
11-APR-90
p) LEAST
Ex:
LEAST(
-------------
11-JAN-90
r) TRUNC
Trunc will chops off the date to which it was equal to or less than the
given date.
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 51 of 88
trunc(to_date('11-mar-06','dd-mon-yy'),'year') from dual;
TRUNC(TO_ TRUNC(TO_
------------- --------------
01-JAN-04 01-JAN-06
TRUNC(TO_ TRUNC(TO_
------------- -------------
01-JAN-04 01-JAN-04
a) RANK
Ex:
Select empno, ename, sal, r from (select empno, ename, sal, rank () over
(order by sal desc) r from EMP);
100 A 5000 1
200 B 5000 1
300 C 4000 3
d) DENSE_RANK
Page 52 of 88
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);
100 A 5000 1
200 B 5000 1
300 C 4000 2
GROUP BY
Columns used in select must be used with group by, otherwise it was not a
group by expression.
Ex:
DEPTNO SUM(SAL)
---------- ----------
10 8750
20 10875
30 9400
Page 53 of 88
SQL> select deptno,job,sum(sal) from emp group by deptno,job;
10 CLERK 1300
10 MANAGER 2450
10 PRESIDENT 5000
20 ANALYST 6000
20 CLERK 1900
20 MANAGER 2975
30 CLERK 950
30 MANAGER 2850
30 SALESMAN 5600
HAVING
This will work as where clause which can be used only with group by
because of absence of where clause in group by.
On top of the Group by if we want to filter the groups then we use having
clause.
Ex:
Page 54 of 88
200 SHAM HYD 3
20 ANALYST 6000
10 PRESIDENT 5000
30 SALESMAN 5600
ORDER OF EXECUTION
TYPES
Union
Union all
Intersect
Minus
2.8.1 UNION
This will combine the records of multiple tables having the same structure.
Page 55 of 88
Ex:
Union
This will combine the records of multiple tables having the same structure
but including duplicates.
Ex:
2.8.3 INTERSECT
This will give the common records of multiple tables having the same
structure.
Ex:
2.8.4 MINUS
This will give the records of a table whose records are not in other tables
having the same structure.
Ex:
2.9 Constraints
Constraints required maintaining consistence data in a database.
Page 56 of 88
Domain integrity constraints
Not null
Check
Entity integrity constraints
Unique
Primary key
Referential integrity constraints
Foreign key
Constraints are always attached to a column not a table.
If you want to give a name to the constraint, you have to use the
constraint clause.
Ex:
Page 57 of 88
2.9.2 CHECK
Ex:
COLUMN LEVEL
TABLE LEVEL
ALTER LEVEL
2.9.3 UNIQUE
Ex:
COLUMN LEVEL
Page 58 of 88
SQL> create table student(no number(2) unique, name varchar(10),
marks number(3));
TABLE LEVEL
ALTER LEVEL
COLUMN LEVEL
Page 59 of 88
TABLE LEVEL
ALTER LEVEL
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
ALTER LEVEL
Page 60 of 88
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.
By using this clause you can remove the parent record even it childs
exists.
Ex:
TABLE LEVEL
ALTER LEVEL
Page 61 of 88
references dept(deptno) on delete cascade;
Ex:
Page 62 of 88
SQL> create table emp(empno number(2), ename varchar(10), deptno
number(2), dname varchar(10), primary key(empno), foreign
key(deptno,dname) references dept(deptno,dname));
2.10 Joins
Equi join
Non-equi join
Self join
Natural join
Cross join
Outer join
Page 63 of 88
Left outer
Right outer
Full outer
Inner join
Using clause
On clause
10 mkt hyd
20 fin bang
30 hr bombay
Page 64 of 88
2.10.1 EQUI JOIN
Ex:
USING CLAUSE
ON CLAUSE
Page 65 of 88
on(e.deptno=d.deptno);
A join which contains an operator other than ‘=’ in the joins condition.
Ex:
Ex:
Page 66 of 88
EMPNO ENAME JOB DEPTNO
Ex:
Ex:
Page 67 of 88
111 saketh analyst mkt hyd
Outer join gives the non-matching records along with matching records
from both the tables. Its divided into Left, Right and Full outer join
This will display the all matching records from both the tables and also non
matching records from opposite side outer join symbol table.
Ex:
Or
Page 68 of 88
SQL> select empno,ename,job,dname,loc from emp e,dept d where
e.deptno=d.deptno(+);
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:
Or
Page 69 of 88
222 sudha clerk fin bang
hr 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:
UNION
OR
Page 70 of 88
hr bombay
Ex:
Ex:
SAL CASE
Page 71 of 88
----- --------
500 low
2500 medium
2000 medium
3500 medium
3000 medium
5000 high
4000 medium
2.11.2 Decode ()
‘BANG,‘Bangulure’,address) as Address
From emp;
You can use merge command to perform insert and update in a single
command.
Page 72 of 88
Using (select * from student2) s2
On (s1.no=s2.no)
TYPES
Ex:
SQL> select * from emp where sal > (select sal from emp where empno
= 7566);
Page 73 of 88
7902 FORD ANALYST 7566 03-DEC-81 3000 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);
Ex: Find all employees who earn more than the average salary in their
department.
Page 74 of 88
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.
2.14.1 VIEWS
TYPES
Simple view
Complex view
Simple view can be created from one table where as complex view can be
created from multiple tables.
WHY VIEWS?
Page 75 of 88
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 deptno, sum(sal) t_sal from emp
group by deptno;
DROPPING VIEWS
Ex: Get dept wise max sal along with empname and emp no.
From EMP a, (Select max (sal) sal, deptno from EMP group by
deptno) b
SQL> Select ename, sal, rownum rank from (select *from emp order by
sal);
ENAME SAL RANK
---------- ---------- ----------
SMITH 800 1
JAMES 950 2
ADAMS 1100 3
WARD 1250 4
Page 76 of 88
2.14.3 MATERILIZED VIEW
Syntax:
REFRESH COMPLETE
AS
DBMS_MVIEW.REFRESH('MV_COMPLEX', 'C');
Or
Page 77 of 88
In view we cannot schedule to In materialized view we can
refresh. schedule to refresh.
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
Composite index
Function-based index
Cluster index
2.15.1 UNIQUE INDEX
Ex:
Page 78 of 88
2.15.2 NON-UNIQUE INDEX
Ex:
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:
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.
Ex:
Ex:
Page 79 of 88
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 doesn’t 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.
If still has performance issue then will use HINTS, hint is nothing but a
clue. We can use hints in select statement like
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.
Page 80 of 88
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 */
You should first get the explain plan of your SQL and determine what
changes can be done to make the code operate without using hints if
possible.
2.17 Differences
Rowid Row-num
Page 81 of 88
destroyed when it is removed rows.
from a table.
Both where and having clause can be used to filter the data.
Example: Example:
Select * from emp where deptno Select a.* from emp e where sal
in (select deptno from dept); >= (select avg(sal) from emp a
where a.deptno=e.deptno group
by a.deptno);
Page 82 of 88
2.17.4 STORE PROCEDURE & FUNCTION
Stored procedure may or may not Function should return at least one
return values. output parameter. Can return more
than one parameter using OUT
argument.
Can affect the state of database Cannot affect the state of database.
using commit.
Page 83 of 88
2.18 PL/SQL Basics
2.18.1 Store Procedure
Pprerequisites:
Before creating a procedure, the user SYS must run a SQL script commonly
called DBMSSTDX.SQL. The exact name and location of this script depend
on your operating system.
To create a procedure in your own schema, you must have the CREATE
PROCEDURE system privilege. To create a procedure in another user's
schema, you must have the CREATE ANY PROCEDURE system privilege. To
replace a procedure in another schema, you must have the ALTER ANY
PROCEDURE system privilege.
BEGIN
Commit;
END;
b In Number,
c Out Number) IS
BEGIN
c=a+b;
DBMS_OUTPUT.PUT_LINE(c);
END;
Page 84 of 88
Packages:
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
Types of Triggers
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.
Page 85 of 88
deletes several rows from a table, a statement-level DELETE trigger is fired
only once.
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.
DECLARE
BEGIN
Delete from X;
Commit;
END;
Select empno, count (*) from EMP group by empno having count (*)>1;
Delete from EMP where rowid not in (select max (rowid) from EMP group
by empno);
UNION
Page 86 of 88
Select name, no, add2 from A;
select
emp_id,
max(decode(row_id,0,address))as address1,
max(decode(row_id,1,address)) as address2,
max(decode(row_id,2,address)) as address3
group by emp_id
Other query:
select
emp_id,
max(decode(rank_id,1,address)) as add1,
max(decode(rank_id,2,address)) as add2,
max(decode(rank_id,3,address))as add3
from
group by
emp_id
5. Rank query:
Select empno, ename, sal, r from (select empno, ename, sal, rank () over
(order by sal desc) r from EMP);
The DENSE_RANK function works acts like the RANK function except that it
assigns consecutive ranks:
Select empno, ename, Sal, from (select empno, ename, sal, dense_rank ()
over (order by sal desc) r from emp);
Page 87 of 88
7. Top 5 salaries by using rank:
Or
8. 2 nd highest Sal:
Select empno, ename, sal, r from (select empno, ename, sal, dense_rank
() over (order by sal desc) r from EMP) where r=2;
9. Top sal:
Select * from EMP where sal= (select max (sal) from EMP);
Starting at the root, walk from the top down, and eliminate employee
Higgins in the result, but
FROM employees
Page 88 of 88