Satya.oracle Notes by Sudhakar Sir (1)
Satya.oracle Notes by Sudhakar Sir (1)
Satya.oracle Notes by Sudhakar Sir (1)
Introduction of
DBMS:
DATA: IT IS A RAW FACT (i.e. CHARACTERS & NUMBERS)
EX:
3. DBMS / DATABASE
2. DATAINTEGRITY :
==============
THIS IS ABOUT MAINTAING PROPER DATA IN EVERY ORAGANIZATION
IMPOSE SET INTEGRITY RULES ON DATA AND WE WILL CALL THESE RULES
ARE BUSINESS RULES.
DATABASE PROVIDES AN OPTIONS FOR IMPOSING THE BUSINESS
RULES WITH THE HELP OF CONSTRAINTS AND TRIGGERS.
3. DATARETRIEVE:
==============
IT IS PROCESS OF DATA RETRIEVING FROM DATA SOURCES.WHICH IS
VERY COMPLEX WHILE RETRIEVING DATA FROM FILES WHICH WAS
ADDRESSED WITH HIGH LEVEL LANGUAGE.
WHERE AS IF YOU WANT TO RETRIEVE DATA FROM DATABASE
THEN WE ARE USING SQL LANGUAGE.
4. DATASECURITY:
==============
DATA IS NEVER SECURE UNDER BOOKS AND FLAT FILE WHERE AS
DATABASE ARE PROVIDING AN EXCELLENT CONCEPT IS CALLED AS
ROLE BASED SECURITY MECHANISM FOR ACCESSING DATA FROM
DATABASE WITH SECURITY MANNER WITH THE HELP OF AUTHENTICATION
AND AUTHORIZATION.
5. DATAINDEXING:
==============
INDEXES ARE USING FOR ACCESSING DATA MUCH MORE FASTER
BUT FLAT FILES DOES NOT PROVIDE ANY INDEX
MECHANISM WHERE AS DATABASE WILL PROVIDE INDEXING MECHANISM.
3. DBMS / DATABASE:
TYPES DATABASES:
OLAP: USED FOR DATA ANALYSIS (OR) DATA SUMMERIZED (OR) HISTORY OF
DATA OF PARTICULAR BUSSINESS.
EX: DATAWAREHOUSE.
DBMS: IT IS A SOFTWARE.WHICH IS USED TO MANAGE DATA IN DATABASE.
WHY DBMS:
EX:
2. TO AVOID DATAINCONSISTANCY.
HDBMS:
EX:
NDBMS:
EX:
ADVANTAGES OF NDBMS:
E.F.CODD WITH ALL THESE IDEAS FOR THE NEW MODEL CALLED AS
“RELATIONAL MODEL” HAS PUBLISHED AN ARTICLE WITH THE TITLE AS “A
RELATIONAL MODEL OF DATA FOR LARGE SHARED DATA BANK”.
FEATURES OF RDBMS:
- EASY TO ACCESS DATA FROM DB WITH THE HELP OF "SQL QUERY (SELECT)".
In this relationship one object can have a relationship with another object
One – Many / Many – One relationship:
In this relationship one object can have a relationship with many objects
In this relationship many vendors (or) many objects can have the relationship
with many other objects
INTRODUCTION TO ORACLE:
ORACLE IS A RELATIONAL DATABASE AN RDBMS PRODUCT
FROM ORACLE CORPORATION IN 1979.WHICH IS USED TO STORE
DATA (OR) INFORMATION PERMANANTLY i.e., IN HARD DISK ALONG
WITH SECURITY.
PLATFORM:
1) PLATFORM INDEPENDENT:
2) PLATFORM DEPENDENT:
EX: C - LANGUAGE.
Versions of ORACLE:
1. ORACLE CLIENT
2. ORACLE SERVER
1. ORACLE CLIENT:
INSTANCE
DATABASE
1) CONNECT TO ORACLE:
IF USER WANTS TO CONNECT TO ORACLE THEN WE
REQUIRED A DATABASE TOOL IS CALLED AS “SQLPLUS”
WHICH WAS INBUILTED IN ORALCE SOFTWARE.
2) COMMUNICATE WITH DATABASE:
IF USER WANTS TO COMMUNICATE WITH DATABASE THEN
WE NEED A DATABASE COMMUNICATION LANGUAGE IS
CALLED AS “SQL”.
HOW TO CONNECT TO ORACLE:
SYNTAX:
CONNECTED.
SYNTAX:
EX:
CONNECTED.
1) NUMERIC DATATYPES
3) LONG DATATYPE
4) DATE DATATYPES
1) NUMERIC DATATYPES:
i) INT
NUMBER (P, S): STORING BOTH INTEGER & FLOAT FORMAT VALUES. HERE THIS
DATATYPE IS HAVING FOLLOWING TWO ARGUMENTS ARE PRECISION(P),
SCALE(S).
PRECISION(P):
> COUNTING ALL DIGITS INCLUDING LEFT & RIGHT SIDES OF GIVEN
FLOAT EXPRESSION.
Ex: 25.12
PRECISION = 4
Ex: 856.45
PRECISION = 5
Ex: 9999.99
PRECISION = 6
SCALE(S):
> COUNTING ONLY RIGHT DIGITS OF A FLOAT EXPRESSION.
Ex: 25.12
SCALE = 2
PRECISION = 4
Ex:
7456.123
SCALE = 3
PRECISION = 7
Ex:
CHARACTER DATATYPES
| |
@,#,$,%,&,_,.......etc ]
1) CHAR(SIZE):
- IT IS A FIXED LENGTH DATATYPE(STATIC).
2) VARCHAR2(SIZE):
1) NCHAR(SIZE):
1 CHAR = 1 BYTE.
2) NVARCHAR2(SIZE):
3) LONG:
- IT IS VARIBALE LENGTH DATATYPE(DYNAMIC).
4) DATE DATATYPES:
i) DATE: STORING DATE & TIME INFORMATION BUT TIME IS OPTIONAL.IF NOT
ENTERED TIME BY USER, THEN ORACLE "12:00:00AM".DEFAULT FORMAT OF DATE
DATATYPE IS 'DD-MON-YYYY / YY HH: MI: SS '.IT OCCUPIED 7 BYTES OF MEMORY
(FIXED MEMORY).
5) RAW & LONG RAW: STORING IMAGE / AUDIO / VIDEO FILES IN THE FORM OF
010010101001 BINARY FORMAT.THE MAXIMUM SIZE OF RAW DATATYPE IS 2000
BYTES AND LONG RAW SIZE IS 2 GB.
NOTE:
> CHAR IS UPTO 2000 BYTES > NCHAR IS UPTO 2000 BYTES
> RAW IS UPTO 2000 BYTES > LONG RAW IS UPTO 2GB
> SELECT
> CREATE
> ALTER
> RENAME
> TRUNCATE
> DROP
SYNTAX:
; EX:
CREATE TABLE STUDENT (STID INT, SNAME CHAR (10), SFEE NUMBER
(6,2));
SYNTAX:
EX:
2. ALTER:
SYNTAX:
SYNTAX:
EX:
SYNTAX:
EX:
SYNTAX:
EX:
SYNTAX:
EX:
SYNTAX:
EX:
DATABASE. SYNTAX:
EX:
1) RECYCLEBIN
2) FLASHBACK
3) PURGE
SYNTAX:
SYNTAX:
OBJECT_NAME ORIGINAL_NAME
--------------------------------------------------------- --------------------
---
BIN$EenuRFtsT7ahnHV7rbI71Q==$0 STUDENT
SYNTAX:
EX:
EX:
EX:
EX:
> INSERT
> UPDATE
> DELETE
SYNTAX1:
EX:
1 row created.
SYNTAX2:
EX:
METHOD1:
METHOD2:
INSERT INTO EMP (EID, ENAME, EADDRESS) VALUES (NULL, NULL, NULL);
SYNTAX1 (&):
EX:
1500
4500
SYNTAX2 (&):
; EX:
1026 SQL> /
1027 SQL> /
EX:
8000 SQL> /
WARNER SQL> /
...........................................
...........................................
SYNTAX2 (&&):
SYNTAX:
EX1:
SET SAL=NULL;
SYNTAX:
EX:
EX:
DELETE TRUNCATE
MANNER) TIME)
> SELECT
SYNTAX:
(OR)
DEPT; EX:
SYNTAX:
SYNTAX:
EX:
1) PAGESIZE n:
SYNTAX:
EX:
SYNTAX:
EX:
SYNTAX:
SQL> CL SCR;
(OR)
SQL> EXIT;
i) COLUMN LEVEL:
SYNTAX:
EX:
DEPTNO X
SYNTAX:
DEPT D
EX:
EX:
OUTPUT:
WELCOME TO ORACLE
EX:
OUTPUT:
DISTINCT KEYWORD:
EX:
syntax1:
create table <new table name> as select * from <old table name>;
EX:
NOTE: created a new table with copy of all rows & columns from the
old table.
syntax2:
create table <new table name> as select * from <old table name> where
<false condition>;
Ex:
NOTE: created a new table without copy rows from old table. (Columns
copy)
EX:
NOTE: created a new table with specific columns from the old
table. EX:
NOTE: created a new table with specific rows from the old
syntax:
name>; EX:
EX:
INSERT ALL:
SYNTAX:
....................................................................................................................
.
...............
....................................................................................................................
.
...............
EX:
STEP1:
STEP4:
MERGE COMMAND:
SYNTAX:
STEP1:
STEP2:
STEP3:
STEP4:
STEP5:
S. DNAME, S.LOC);
Operators in Oracle
Operators are used to express the conditions in Select statements.
Operator manipulates individual data items and returns a result. The data
items are called operands or arguments.
Arithmetic operators
Assignment operator
Relational operators
Logical operators
Special Operators
Set Operators
Arithmetic operators:
• Sql * plus ignores the blank spaces before and after the
arithmetic operator .
Example:-
dates. Example:
Example:-
Display the details of the employees Incrementing their salary two times.
Used to perform Division test. Division will display only the Quotient value
not the remainder value. Example 6/2 gives 3 because 2 divides 6 by 3
times.
Example:-
Assignment operators:-
This operator is used for equality test. Used to test the equality of two
operands.
Example:-
----------------------------------------------------------------------------------------
-----------------
This operator is used for less than test. Example a<b checks that
operand ‘a’ is less than ‘b’ or not.
Example: Display the details of the employees whose salary is less than
3000.
----------------------------------------------------------------------------------------
---------------------
Here if you observe we got a result values whose salary is less than the
operand 3000.
This operator is used for Greater than test. For example a>b checks the
operand ‘a’ is greater than ‘b’ or not.
Example:
----------------------------------------------------------------------------------------
-----------
This operator is used for Less than or Equal to test. For example a<=b,
here checks whether operand ‘a’ is less than or equals to operand ‘b’. If
a<b then condition is true and if a=b then also condition is true but if a>b
then condition is false.
Example :-
This operator is used to check the Greater than or equal test. For example
a>=b checks the operand ‘a’ is greater than operand ‘b’ or operand ‘a’ is
equals to the operand ‘b’.
Example:-
----------------------------------------------------------------------------------------
------------------
Examples:
Logical operators:-
AND operator:-
Example:-
Display the details of Employees whose salary is Greater than 1000 AND
also whose salary is less than 2000.
Sql> SELECT *FROM emp WHERE sal > 1000 AND sal <2000;
----------------------------------------------------------------------------------------
------------
job='MANAGER';
Example:
Display the details of Employees whose salary is Greater than 1000 OR also
whose salary is less than 2000.
Sql> SELECT *FROM emp WHERE sal> 1000 OR sal < 2000;
Explination:-whose salaries more than 1000 or less than 2000 that all emp
table display.
The NOT operator returns ‘True’ if the condition is False and returns
‘False’ if the following condition is True.
Example:
Explination:-whose salary less than 3000 that salaries all are comming.
deptno=20;
Special operators:-
IN operator:-
----------------------------------------------------------------------------------------
----------------
Not in operator:-
('SMITH','ALLEN','WARD');
BETWEEN Operator:-
Sql> SELECT *FROM emp WHERE sal BETWEEN 2000 AND 3000;
----------------------------------------------------------------------------------------
--------------
Whenever lower bound value is larger than upper bound then it shows ‘no
rows selected’
Example:-
Sql> SELECT *FROM emp WHERE sal BETWEEN 3000 AND 2000;
Output:
-- No rows selected
Example:-
Sql> SELECT *FROM emp WHERE sal NOT BETWEEN 2000 AND 3000;
----------------------------------------------------------------------------------------
----------------------
Note:-
Lower bound – ‘value ‘must be lower when compare to ‘upper bound ‘value
Upper bound- ‘value’ must be higher when compare to ‘lower bound ‘value
input. Syntax:-
Example:- Display the employees whose name is starting with ‘S’ in EMP
table.
----------------------------------------------------------------------------------------
-------------
Display the employees whose name ends with ‘S’ in EMP table
----------------------------------------------------------------------------------------
------------------
----------------------------------------------------------------------------------------
-------------
Sql> select ename ,hiredate from emp where hiredate like '%JAN%';
Sql> select empno,ename,job from emp where job like ' ';
EX:
EX:
EX:
EX:
NOTE:
- syntax:-
Display the employees whose name is not ends with ‘S’ in EMP
table? Sql> SELECT *FROM emp WHERE ename NOT LIKE '%S';
----------------------------------------------------------------------------------------
-------------
Display the employees whose names are not having second letter as ‘L’
in EMP table?
Display the employees whose names are not start with ‘S’ in EMP table.?
Sql> select ename ,hiredate from emp where hiredate not like '%JAN%';
Sql> select empno,ename,job from emp where ename not like '_O%';
Display the employees whose names are second letter start with ‘R’ from
ending.?
----------------------------------------------------------------------------------------
-------------
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
----------------------------------------------------------------------------------------
-------------
syntax:
Ex:
Ex:
Ex:
Ex: If x=1000;
> If Exp1 is null ------------> returns Exp2 value (user defined value)
Ex:
NVL(NULL,0)
-----------
NVL(NULL,100)
-------------
100
----------
SQL> SELECT ENAME, JOB, SAL, COMM, NVL (COMM,0)+SAL FROM EMP
WHERE ENAME='SMITH';
Set Operators:
SQL set operators allows combine results from two or more SELECT
statements. At first sight this looks similar to SQL joins although there is
big difference. SQL joins tends to combine columns i.e. with each
additionally joined table it is possible to select more and more columns.
SQL set operators on the other hand combine rows from different queries
with strong preconditions - all involved SELECTS must. Joins we are
collecting the data from two tables when there is a common data. But in
set operators the data is not joined, in this the data is merged
Operator Returns
You can combine multiple queries using the set operators UNION, UNION
ALL, INTERSECT, and MINUS. All set operators have equal precedence. If a
SQL statement contains multiple set operators, then Oracle Database
evaluates them from the left to right unless parentheses explicitly specify
another order.
If component queries select character data, then the datatype of the return
values are determined as follows:
In queries using set operators, Oracle does not perform implicit conversion
across datatype groups. Therefore, if the corresponding expressions of
component queries resolve to both character data and numeric data,
Oracle returns an error.
• The set operators are not valid on columns of type BLOB, CLOB,
BFILE, VARRAY, ornested table.
• The UNION, INTERSECT, and MINUS operators are not valid on LONG
columns.
1. The result sets of both the queries must have the same number
of columns.
2. The datatype of each column in the second result set must match
the datatype of its corresponding column in the first result set.
<component query>
<component query>
Example:-
• union
• select empno,ename from emp where deptno=30 order by 1;
union
Union All:-
Example:-
order by 1;
Explination:- The UNION operator returns only distinct rows that appear in
either result, while the UNION ALL operator returns all rows. The UNION
ALL operator does not eliminate duplicate selected rows:
union all
INTERSECT:-
intersect
deptno=30 order by 1;
Explination:- The above statement combines the results with the
INTERSECT operator, which returns only those rows returned by both
queries.
intersect
MINUS:-
MINUS Operator takes the result set of first select statement and
removes those rows that are returned by a second select statement.
Example:-
minus
1;
Explination:- The above statement combines results with the MINUS
operator, which returns only unique rows returned by the first query
but not by the second:
minus
The following query uses both MINUS and UNION ALL to compare two
tables for equality. The query depends on each table having either a
primary key or at least one unique index.
Example:-
Sql>DESC CUSTOMER_KNOWN_GOOD
CUST_NBR NAME
----------- ------------------------------
1 Sony
1 Sony
2 Samsung
3 Panasonic
3 Panasonic
3 Panasonic
Sql>DESC CUSTOMER_TEST
CUST_NBR NAME
----------- ------------------------------
1 Sony
1 Sony
2 Samsung
2 Samsung
3 Panasonic
Example:-
MINUS
MINUS
Explination:-Let's talk a bit about how this query works. We can look at it
as the union of two compound queries. The parentheses ensure that both
MINUS operations take place first before the UNION ALL operation is
performed. The result of the first MINUS query will be those rows in
CUSTOMER_KNOWN_GOOD that are not also in CUSTOMER_TEST. The
result of the second MINUS query will be those rows in CUSTOMER_TEST
that are not also in CUSTOMER_KNOWN_GOOD. The UNION ALL operator
simply combines these two result sets for convenience. If no rows are
returned by this query, then we know that both tables have identical rows.
Any rows returned by this query represent differences between the
CUSTOMER_TEST and CUSTOMER_KNOWN_GOOD tables.
FROM CUSTOMER_KNOWN_GOOD C1
MINUS
FROM CUSTOMER_TEST C2
UNION ALL
FROM CUSTOMER_TEST C3
MINUS
FROM CUSTOMER_KNOWN_GOOD C4
GROUP BY C4.CUST_NBR, C4.NAME);
TIP: Duplicate rows are not possible in tables that have a primary key
or at least one unique index. Use the short form of the table comparison
query for such tables.
Example:-
union
where deptno=20
union
where deptno=30;
UNION
NUM STRING
---------- -------- 1
DEFINITE
Notice that Oracle considers the character string 'DEFINITE' from the
first component query to be compatible with the NULL value supplied for
the corresponding column in the second component qery. However, if a
NUMBER or a DATE column of a component query is set to NULL, we must
explicitly tell Oracle what "flavor" of NULL to use. Otherwise, we'll
encounter errors. For
example:
UNION
ERROR at line 1:
Note that the use of NULL in the second component query causes a
datatype mismatch between the first column of the first component query,
and the first column of the second component query. Using NULL for a
DATE column causes the same problem, as in the following
Example:-
DUAL UNION
SELECT 2 NUM, NULL DATES FROM
ERROR at line 1:
UNION
NUM STRING
---------- -------- 1
DEFINITE
UNKNOWN
DUAL UNION
NUM DATES
---------- --------- 1
06-JAN-02
NUM STRING
---------- -------- 1
DEFINITE
UNKNOWN
DUAL UNION
---------- --------- 1
06-JAN-02
EX:-
deptno=20 union
EX:-
EX: Waq to display all employee details who are working in NARESHIT
organization?
EX: Waq to display employee details who are working in both branchs ?
EX: Waq to display employee details who are working in HYD BUT NOT IN
CHENNAI branchs ?
EX: Waq to display employee details who are working in CHENNAI BUT NOT
IN HYD branchs ?
1) Pre-Define Functions:
---------------------------------------------
> These Are Again Classified into Two Categories.
What Is Dual:
------------------------
> Pre-Define Table In Oracle.
> Having Single Column & Single Row
> Is Called As Dummy Table In Oracle.
> Testing Functions (Pre-Define & User Define) Functionalities.
Numeric Functions:
--------------------------------------
1) Abs():
> Converts (-Ve) Value Into (+Ve) Value.
Syntax:
---------------
Abs(Number)
Ex:
Sql> Select Abs(-12) From Dual; --------> 12
Sql> Select Ename,Sal,Comm,Abs(Comm-Sal) From Emp;
2) Ceil():
> Returns A Value Which Is Greater Than Or Equal To Given Value.
Syntax:
---------------
Ceil(Number)
Ex:
Sql> Select Ceil(9.0) From Dual;-------9
Sql> Select Ceil(9.3) From Dual;--------10
3) Floor():
Syntax:
Floor(Number)
Ex:
Sql> Select Floor(9.0) From Dual;-------9
Sql> Select Floor(9.8) From Dual;-------9
4) Mod():
Returns Remainder Value.
Syntax:
Mod(M,N)
Ex:
Sql> Select Mod(10,2) From Dual;--------0
5) Power():
The Power Of Given Expression
Syntax:
Power(M,N)
Ex:
Sql> Select Power(2,3) From Dual;-----------8
Round():
> Nearest Value Given Expression.
Syntax:
Round(Number,[Decimal Places])
Ex:
Sql> Select Round(5.50) From Dual;-------6
Sql> Select Round(32.456,2) From Dual;-------32.46
Trunc:
-------
> Returns A Value Which Will Specified Number Of Decimal Places.
Syntax:
Trunc(Number,Decimal Places)
Ex:
Sql> Select Trunc(5.50) From Dual;----------5
Sql> Select Trunc(32.456,2) From Dual;-----32.45
String Functions:
--------------------
Length():
------------------
> Length Of Given String.
Syntax:
Length(String)
Ex:
Sql> Select Length('Hello') From Dual;---------------------------5
Sql> Select Length('Good Morning') From Dual;---------12
Lower():
----------------
To Convert Upper Case Char's Into Lower Case Char's.
Syntax:
Lower(String)
Ex:
Sql> Select Lower('Hello') From Dual;
Sql> Update Emp Set Ename=Lower(Ename) Where Job='Clerk';
Upper():
---------------
Syntax:
Upper(String)
Ex:
Sql> Select Lower('Hello') From Dual;
Initcap():
------------------
To Convert First Char. Is Capital.
Syntax:
Initcap(String)
Ex:
Sql> Select Initcap('Hello') From Dual;
Sql> Select Initcap('Good Morning') From Dual;
Ltirm():
---------------
To Remove Unwanted Spaces (Or) Unwanted Characters From Left
Side
Of Given String.
Syntax:
Ltrim(String1[,String2])
Ex:
Sql> Select Ltrim(' Sai') From Dual;
Sql> Select Ltrim('Xxxxxxsai','X') From Dual;
Sql> Select Ltrim('123SAI','123') From Dual;
Rtrim():
---------------
To Remove Unwanted Spaces (Or) Unwanted Characters From
Right Side
Of Given String.
Syntax:
Rtrim(String1[,String2])
Ex:
Sql> Select Rtrim('Saixxxxxxx','X') From Dual;
Trim():
------------
To Remove Unwanted Spaces (Or) Unwanted Characters From Both
Sides
Of Given String.
Syntax:
----------------
Trim('Trimming Char' From 'String')
Ex:
Sql> Select Trim('X' From 'Xxxxxxsaixxxx') From Dual;
Lpad():
------------
To Fill A String With Specific Char. On Left Side Of
Given String.
Syntax:
---------------
Lpad(String1,Length,String2)
Ex:
Sql> Select Lpad('Hello',10,'@') From Dual;
@@@@@Hello
Rpad():
-------------
To Fill A String With Specific Char. On Right Side Of
Given String.
Syntax:
---------------
Rpad(String1,Length,String2)
Ex:
Sql> Select Rpad('Hello',10,'@') From Dual;
Hello@@@@@
Concat():
-----------------
Adding Two String Expressions.
Syntax:
--------------
Concat(String1,String2)
Ex:
Sql> Select Concat('Good','Bye') From Dual;
Replace():
-------------------
To Replace One String With Another String.
Syntax:
---------------
Replace(String1,String2,String3)
Ex:
Sql> Select Replace('Hello','Ell','Xyz') From Dual;
Hxyzo
Translate():
------------------------
To Translate A Single Char With Another Single Char.
Syntax:
--------------
Translate(String1,String2,String3)
Ex:
Sql> Select Translate('Hello','Elo','Xyz') From Dual;
Hxyyz
Sol: E = X , L=Y , O=Z
Hello => Hxyyz
Ex:
Sql> Select Ename,Sal,Translate(Sal,'0123456789','$B@Gh*V#T%')
Salary From Emp;
Sol: 0=$,1=B,2=@,3=G,4=H,5=*,6=V,7=#,8=T,9=%.
Substr():
-----------------
It Returns Req.Substring From Given String Expression.
Syntax:
---------------
Substr(String1,<Starting Position Of Char.>,<Length Of
Char's>)
Ex:
Sql> Select Substr('Hello',2,3) From Dual;
Ell
Sql> Select Substr('Welcome',4,2) From Dual;
Co
Instr():
--------------
Returns Occurence Position Of A Char. In The Given String.
Syntax:
---------------
Instr(String1,String2,<Starting Position Of Char.>,<Occurence
Position Of Char.>)
Ex:
Sql> Select Instr('Hello Welcome','O') From Dual;---------> 5
Sql> Select Instr('Hello Welcome','Z') From Dual;-----> 0
Sql> Select Instr('Hello Welcome','O',1,2) From Dual;------11
Sql> Select Instr('Hello Welcome','E',5,2) From Dual;--------13
Sql> Select Instr('Hello Welcome','E',1,4) From Dual;---------8
Note:
----------
Position Of Char's Always Fixed Either Count From Left To Right
(Or) Right To Left.
Ex:
Sql> Select Instr('Hello Welcome','E',-1,3) From Dual;----------2
Sql> Select Instr('Hello Welcome','L',-4,3) From Dual;--------3
Sql> Select Instr('Hello Welcome','L',-6,3) From Dual;------------0
Date Functions:
------------------
1) Sysdate:
---------------------
> Current Date Information Of The System.
Ex:
Sql> Select Sysdate From Dual;
Sql> Select Sysdate+10 From
Dual; Sql> Select Sysdate-10 From
Dual;
Add_Months():
--------------------------
> Adding No.Of Months To The Date.
Syntax:
---------------
Add_Months(Date,<No.Of Months>)
Ex:
Sql> Select Add_Months(Sysdate,3) From Dual;
Sql> Select Add_Months(Sysdate,-3) From Dual;
Last_Day():
---------------------
> Returns The Last Day Of The Month.
Syntax:
--------------
Last_Day(Date)
Ex:
Sql> Select Last_Day(Sysdate) From Dual;
Next_Day():
--------------------
> Returns The Next Specified Day From The Given Date.
Syntax:
---------------
Next_Day(Date,'<Day Name>')
Ex:
Sql> Select Next_Day(Sysdate,'Sunday') From Dual;
Months_Between():
------------------------------------
> Returns No.Of Months Between Two Date Expressions.
Syntax:
---------------
Months_Between(Date1,Date2)
Ex:
Sql> Select Months_Between('05-Jan-81','05-Jan-80') From Dual;---
-- 12
Sql> Select Months_Between('05-Jan-80','05-Jan-81') From Dual;---
-- -12
Conversion Functions:
-------------------------
1. To_Char()
2. To_Date()
To_Char():
-------------------
> Date Type To Char Type To Display Date In Different Fromat.
Syntax:
To_Char(Date,[<Format>])
Year Formats:
---------------------------
Yyyy - 2020
Yy - 20
Year - Twenty Twenty
Cc - Centuary 21
Ad / Bc - Ad Yaer / Bc Year
Ex:
Sql> Select To_Char(Sysdate,'Yyyy Yy Year Cc Ad') From Dual;
To_Char(Sysdate,'Yyyyyyyearccad')
----------------------------------------------------------
2020 20 Twenty Twenty 21 Ad
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Yyyy')=1982;
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Yyyy')
In(1980,1982,1987);
Month Format:
----------------------------
Mm - Month Number
Mon - First Three Char From Month
Spelling Month - Full Name Of Month
Ex:
Sql> Select To_Char(Sysdate,'Mm Mon Month') From Dual;
To_Char(Sysdate,
----------------
08 Aug August
To_Char(Sysdate,
----------------
08 Aug August
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Mm')
In(02,05,12);
Q: To Display Employee Who Are Joined In Feb 1981
By Using To_Char() ?
Sol:
Sql> Select * From Emp Where
To_Char(Hiredate,'Mmyyyy')='021981';
Day Formats:
-------------------------
Ddd - Day Of The Year.
Dd - Day Of The
Month. D - Day Of
The Week
Sun - 1
Mon - 2
Tue - 3
Wen - 4
Thu - 5
Fri - 6
Sat - 7
To_Char(Sysdate,'Ddddd
----------------------------------------------
220 07 6 Friday Fri
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Day')='Friday';
Sol:
Sql> Select Ename||' '||'Joined On'||' '||To_Char(Hiredate,'Day') From
Emp;
Note:
------
In Oracle Whenever We Using To_Char() And Also Within To_Char()
When We use Day / Month Format Then Oracle Server Internally
Allocate Some Extra Memory For Day/Month Format Of Data.
To Overcome The Above Problem That Is To Remove Extra
Memory Which Was Allocate By Oracle Server Then We Use A
Pre- Define Specifier Is
Called "Fm" (Fill Mode).
Ex:
Select * From Emp Where To_Char(Hiredate,'Fmday')='Friday';
Quater Format:
----------------------------
Q - One Digit Quater Of The Year
1 - Jan - Mar
2 - Apr - Jun
3 - Jul - Sep
4 - Oct - Dec
Ex:
Sql> Select To_Char(Sysdate,'Q') From Dual;
T
---
3
Sol:
Sql> Select * From Emp Where To_Char(Hiredate,'Yyyy')='1981'
And To_Char(Hiredate,'Q')=2;
Week Format:
--------------------------
Ww - Week Of The Year
W - Week Of Month
Ex:
Sql> Select To_Char(Sysdate,'Ww W') From Dual;
To_C
---------
32 2
Time Format:
-------------------------
Hh - Hour Part
Hh24- 24 Hrs Fromat
Mi - Minute Part
Ss - Seconds Part
Am / Pm - Am Tme (Or) Pm Time
Ex:
Sql> Select To_Char(Sysdate,'Hh:Mi:Ss Am') From Dual;
To_Char(Sys
------------------------
12:04:21 Pm
To_Date():
------------------
To Convert Char Type To Oracle Date Format Type.
Syntax:
To_Date(String[,Fromat])
Ex:
Sql> Select To_Date('08/August/2020') From Dual;
To_Date('
--------- 08-
Aug-20
To_Date('
---------
18- Aug-20
Multiple Row Functions:
-----------------------------------------------
These Functions Are Returns Either Group Of Values
(Or) A Single Value.
Sum():
-----------
> It Returns Sum Of A Specific Column Values.
Ex:
Sql> Select Sum(Sal) From Emp;
Sql> Select Sum(Sal) From Emp Where Job='Clerk';
Avg():
----------
> It Returns Average Of A Specific Column Values.
Ex:
Sql> Select Avg(Sal) From Emp;
Sql> Select Avg(Sal) From Emp Where Deptno=10;
Min():
----------
> It Returns Min.Value From Group Of Values.
Ex:
Sql> Select Min(Hiredate) From Emp;
Sql> Select Min(Hiredate) From Emp Where Job='Manager';
Sql> Select Min(Sal) From Emp;
Max():
-----------
> It Returns Max.Value From Group Of Values.
Ex:
Sql> Select Max(Sal) From Emp;
Count():
----------------
> It Returns No.Of Rows In A Tbale / No.Of Values In A Column
> Three Types,
I) Count(*)
Ii) Count(<Column Name>) Iii)
Count(Distinct <Column Name>)
Ex:
Test
--------
Sno Name
--- -----
101 A
102 B
103
104 C
105 A
106 C
Count(*):
----------------
> Counting All Rows (Duplicates & Nulls) In A Table.
Ex:
Sql> Select Count(*) From Test;
Count(*)
------------------
6
Count(<Column Name>):
--------------------------------------------
> Counting All Values Including Duplicate Values But Not Null
Values From A Column.
Ex:
Sql> Select Count(Name) From Test;
Count(Name)
-----------------------
5
Ex:
Sql> Select Count(Distinct Name) From Test;------- 3
CLAUSES:
- Clause Is Statement Which Is Used To Add To Sql Pre-Define Query For
Providing Additional Facilities Are Like Filtering Rows, Sorting Values, Grouping
Similar Values, Finding
Sub Total and Grand Total Based On the Given Values Automatically.
> Rollup - Finding Sub Total & Grand Total (Single Column)
> Cube - Finding Sub Total & Grand Total (Multiple Columns)
Syntax:
Where Clause:
> Filtering Rows in One By One Manner before Grouping Data in Table.
Syntax:
Ex:
Note: "Where" Clause Can Be Used In "Select " ,"Update" And "Delete" Commands
Only.
Order by Clause:
Syntax:
Select * / <List Of Column Names> From <Tn> Order By <Column Name1> <Asc /
Desc>,<Column Name2> <Asc/Desc>,.............;
Ex1:
Sol:
(Or)
Ex2:
Sol:
Ex3:
Descending Order?
Sol:
Sol:
Note:
Ex:
Note:
Using Order by Clause On "Null" Values Column Then Oracle Returns "Null" Values
Last In Ascending Order And "Null" Values Are Displayed First In Descending By
Default.
If We Want To Change This Default Order Of "Null" Then We Use Null Clauses
Are “Nulls First" And " Nulls Last ".
Ex:
Group By:
> When We Use "Group by "We Must Use "Aggregative Functions" Are
Sum(),Avg(),Min(),Max(),Count().
Syntax:
Group By
Aggregative Functions. |
(4) (4)
Ex1:
Sol:
Sol:
Deptno Wise ?
Sol:
Group By Job,Deptno;
Ex4:
Sol:
Ex5:
Sol:
Having:
> Filtering Rows after Grouping Data in Table. It Can Be Used Along With "Group
By" Clause.
Syntax:
Ex1:
Waq To Find Out No.Of Employee Of Each Job In Which Job No.Of Employee
Sol:
Having Count(*)>3;
Ex
Waq To Display Sum Of Salary Of Deptno's From Emp Table.If Sum Of Salary
Sol:
Where Having
A Table. Of A Table.
Syntax:
Group By <Col1>,<Col2>,......................
];
Ex:
Where Sal>1000
Group By Deptno
Having Count(*)>3
Order By Deptno;
Deptno Count(*)
20 4
30 5
Order of Execution:
> From
> Where
> Group By
> Having
> Select
> Order By
> Rollup Will Find Sub & Grand Total Based On a Single Column.
> Cube Will Find Sub & Grand Total Based On Multiple Columns.
Synta
Group By Rollup (<Col1>,<Col2>,<Col3>,.........,<Col N>)
Deptno Count(*)
10 3
20 5
30 6
14
Sql> Select Deptno, Job, Count (*) From Emp Group By Rollup(Deptno,Job);
Note: In The Above Ex. Rollup Is Finding Sub & Grand Total Based On A Single
Column (Deptno).If We Want To Find Sub & Grand Total Then Use "Cube" Clause.
Syntax:
Sql> Select Deptno, Count (*) From Emp Group By Cube(Deptno) Order By
Deptno;
Sql> Select Deptno, Job, Count (*) From Emp Group By Cube(Deptno , Job)
Order by Deptno;
Grouping_ID ():
> It Used More Compact Way To Identify Sub And Grand Total Rows.
Ex:
Select Deptno, Job, Count (*), Grouping_ID (Deptno, Job) From Emp
- OUTER JOIN
- LEFT OUTER JOIN
- RIGHT OUTER JOIN
- NATURAL JOIN
1021 SAI 10
1022 ADAMS 20
1023 JONES 30
COURSE_TABLE
CID CNAME CFEE
------
---------- ----------
10 ORACLE 2500
20 JAVA 6000
40 PHP 4500
WHEN WE USE EQUI JOIN BETWEEN TWO (OR) MORE THAN TWO
TABLES THERE MUST BE COMMON COLUMN (OR) COMMON FIELD
NAME IS NO NEED TO BE SAME NAME (BUT RECOMMEND). COMMON
COLUMN (OR) COMMON FIELD DATATYPE MUST BE MATCH.
WHEN WE PERFORM ANY JOIN OPERATION BETWEEN TABLES
THERE IS NO NEED TO HAVE RELATIONSHIP(OPTIONAL).(I.E PRIMARY
KEY & FOREIGN KEY RELATION).EQUI JOIN ALWAYS RETRIEVING ONLY
MATCHING DATA / MATCHNG ROWS.
SYNTAX:
EX3:
SOL:
EX6:
EX7:
SQL> SELECT D. DEPTNO, DNAME, COUNT (*) FROM EMP E, DEPT D
INNER JOIN:
- INNER JOIN IS SIMILAR TO EQUI JOIN.RETRIEVING DATA
FROM MULTIPLE
TABLES WITH "ON" CLAUSE CONDITION.
SYNTAX:
ON <TABLE NAME1>.<COMMON COLUMN> =
<TABLE NAME2>.<COMMON COLUMN>;
(OR)
EX2:
WHERE LOC='CHICAGO';
WHY ANSI JOINS:
THESE JOINS ARE INTRODUCED IN ORACLE 9I.THE MAIN
ADVANTAGE OF ANSI JOINS ARE PORTABILITY. IT MEANS THAT WE
CAN MOVE JOIN STATEMENTS FROM ONE DATABASE TO ANOTHER
DATABASE WITHOUT MAKING ANY CHANGES AS IT IS THE JOIN
STATEMENTS ARE EXECUTED IN OTHER DATABASES.
OUTER JOINS:
(OR)
NON - ANSI FORMAT:
(OR)
NON - ANSI FORMAT:
NON-EQUI JOIN:
- RETRIEVING DATA FROM MULTIPLE TABLES BASED ON ANY
CONDITION EXCEPT EQUAL OPERATOR CONDITION IS CALLED AS
NON-EQUI JOIN.IN THIE JOIN WE CAN USE THE FOLLOWING
OPERATORS ARE <,>,<=,>=,AND,BETWEEN,........ETC.
EX1:
NON-ANSI:
ROWS AND A SECOND TABLE IS HAVING "N" NO.OF ROWS THEN THE
RESULT IS MXN NO.OF ROWS.
EX1:
OUTPUT:
--------------
EX3:
SELECT * FROM COLORS CROSS JOIN SIZES;--------ANSI
(OR)
SELECT * FROM COLORS,SIZES;-----NON - ANSI
NATURAL JOIN:
- NATURAL JOIN IS SIMILAR TO EQUI JOIN. WHEN WE USE
NATURAL JOIN, WE SHOULD HAVE A COMMON COLUMN NAME. THIS
COLUMN DATA TYPE MUST BE MATCH.
SELF JOIN:
- JOINING A TABLE BY ITSELF IS CALLED AS SELF JOIN. IN SELF JOIN
A ROW IN ONE TABLE JOINED WITH THE ROW OF SAME TABLE.
AND T2.ENAME='SCOTT';
WHERE M.EMPNO=E.MGR;
EX2:
ERROR AT LINE 2:
ORA-01748: ONLY SIMPLE COLUMN NAMES ALLOWED HERE
NOTE: WHEN WE USE "USING" CLAUSE WITH COMMON COLUMN
NAME THERE IS NO NEED TO PREFIX WITH TABLE ALIAS NAME.
EX:
USING(S.CID);----------ERROR
USING(CID);--------ALLOWED
EX:
CONSTRAINTS:
- CONTSRAINTS ARE USED TO RESTRICTED UNWANTED(INVALID) DATA
INTO TABLE.ALL DATABASES ARE SUPPORTING THE FOLLOWING CONSTRAINT
TYPES ARE
- UNIQUE
- NOT NULL
- CHECK
- PRIMARY KEY
- FOREIGN KEY (REFERENCES KEY)
- DEFAULT
- ALL DATABASES ARE SUPPORTING THE FOLLOWING TWO TYPES OF METHODS
TO DEFINE CONSTRAINTS.THOSE ARE
I) COLUMN LEVEL:
- IN THIS METHOD WE ARE DEFINING CONSTRAINTS ON INDIVIDUAL
COLUMNS.
SYNTAX:
CREATE TABLE <TN> (<COLUMN NAME1><DATATYPE>[SIZE] <CONSTRAINT
TYPE>,......);
UNIQUE:
- TO RESTRICTED DUPLICATE VALUES BUT ACCEPTING NULLS INTO A
COLUMN.
I) COLUMN LEVEL:
EX:
SQL> CREATE TABLE TEST1(SNO INT UNIQUE, NAME VARCHAR2(10) UNIQUE);
TESTING:
SQL> INSERT INTO TEST1 VALUES(1,'A');- - - -ALLOWED
SQL> INSERT INTO TEST1 VALUES(1,'A');- - - -NOT ALLOWED
SQL> INSERT INTO TEST1 VALUES(NULL,NULL);---- -ALLOWED
II) TABLE LEVEL:
EX:
SQL> CREATE TABLE TEST2(SNO INT, NAME VARCHAR2(10), UNIQUE (SNO,
NAME));
TESTING:
SQL> INSERT INTO TEST2 VALUES(1,'A');- - - -ALLOWED
SQL> INSERT INTO TEST2 VALUES(1,'A');- - - -NOT ALLOWED
SQL> INSERT INTO TEST2 VALUES(2,'A');- - - -ALLOWED
NOTE: WHEN WE APPLY UNIQUE CONSTRAINT ON GROUP OF COLUMNS THEN
WE CALLED AS "COMPOSITE UNIQUE" CONSTRAINT.IN THIS MECHANISM
INDIVIDUAL COLUMNS ARE ACCEPTING DUPLICATE VALUES BUT DUPLICATE
COMBINATION OF COLUMNS DATA IS NOT ALLOWED.
NOT NULL:
- TO RESTRICTED NULLS BUT ACCEPTING DUPLICATE VALUES INTO A COLUMN.
- NOT NULL CONSTRAINT NOT SUPPORTS "TABLE LEVEL".
COLUMN LEVEL:
EX:
SQL> CREATE TABLE TEST3(STID INT NOT NULL, SNAME VARCHAR2(10) NOT
NULL);
TESTING:
SQL> INSERT INTO TEST3 VALUES(101,'A');------ALLOW
SQL> INSERT INTO TEST3 VALUES(101,'A');- - - -ALLOW
SQL> INSERT INTO TEST3 VALUES(NULL,NULL);---- -NOT ALLOW
CHECK:
- TO CHECK VALUES WITH USER DEFINED CONDITION BEFORE ACCEPTING
VALUES INTO A COLUMN.
I) COLUMN LEVEL:
EX:
SQL> CREATE TABLE TEST4(EID INT, SAL NUMBER(10) CHECK(SAL>=10000));
TESTING:
SQL> INSERT INTO TEST4 VALUES (1021,9500);-----NOT ALLOW
SQL> INSERT INTO TEST4 VALUES (1021,10000);-----ALLOW
PRIMARY KEY:
============
- TO RESTRICTED DUPLICATES & NULLS INTO A COLUMN.
- A TABLE SHOULD HAVE ONLY "ONE PRIMARY KEY".
I) COLUMN LEVEL:
EX:
SQL> CREATE TABLE TEST6(PCODE INT PRIMARY KEY, PNAME VARCHAR2(10)
PRIMARY KEY);
ERROR AT LINE 1:
ORA-02260: TABLE CAN HAVE ONLY ONE PRIMARY KEY.
SOL:
SQL> CREATE TABLE TEST6(PCODE INT PRIMARY KEY, PNAME VARCHAR2(10));
TESTING:
SQL> INSERT INTO TEST6 VALUES(10021,'C');-------ALLOW
SQL> INSERT INTO TEST6 VALUES(10021,'C++');------NOT ALLOW
SQL> INSERT INTO TEST6 VALUES(NULL,'C++');------NOT ALLOW
3. ONE TABLE FOREIGN KEY MUST BELONGS TO ANOTHER TABLE PRIMARY KEY.
AND HERE PRIMARY KEY & FOREIGN KEY COLUMN MUST BE COMMON
COLUMN.
4. PRIMARY KEY TABLE IS CALLED AS "PARENT TABLE" AND FOREIGN KEY
TABLE IS CALLED AS "CHID TABLE"(I.E PARENT & CHILD RELATIONSHIP).
5. FOREIGN KEY COLUMN VALUES SHOULD BE MATCH WITH PRIMARY KEY
COLUMN
VALUES ONLY.
6. GENERALLY PRIMARY KEY IS NOT ALLOWED DUPLICATE AND NULL VALUES
WHERE AS FOREIGN KEY IS ALLOWED DUPLICATE & NULL VALUES.
I) COLUMN LEVEL:
SYNTAX:
<COMMON COLUMN NAME OF CHILD> <DT>[SIZE] REFERENCES
<PARENT TABLE NAME> (<COMMON COLUMN NAME OF PARENT>)
EX:
STEP1:
SQL> CREATE TABLE DEPT1(DEPTNO INT PRIMARY KEY, DNAME
VARCHAR2(10));
STEP2:
SQL> INSERT INTO DEPT1 VALUES (10,'ORACLE');
SQL> INSERT INTO DEPT1 VALUES (20,'JAVA');
STEP3:
SQL> CREATE TABLE EMP1(EID INT PRIMARY KEY, ENAME VARCHAR2(10),
DEPTNO INT REFERENCES DEPT1(DEPTNO));
STEP4:
SQL>INSERT INTO EMP1 VALUES (1021,'SAI',10);
SQL>INSERT INTO EMP1 VALUES (1022,'JONES',10);
SQL>INSERT INTO EMP1 VALUES (1023,'MILLER',20);
1) INSERTION RULE:
- WE CANNOT INSERT VALUES INTO FOREIGN KEY(REFERENCES KEY)
COLUMN THOSE VALUES ARE NOT EXISTING UNDER PRIMARY KEY COLUMN OF
PARENT TABLE.
EX:
SQL> INSERT INTO EMP1 VALUES (1026,'SCOTT',30);
ERROR AT LINE 1:
ORA-02291: INTEGRITY CONSTRAINT (SCOTT.SYS_C005468) VIOLATED -
PARENT KEY NOT FOUND.
2) DELETION RULE:
- WHEN WE TRY TO DELETE A RECORD FROM PARENT TABLE AND
THOSE ASSOCIATED RECORDS ARE AVAILABLE IN CHILD TABLE THEN ORACLE
RETURNS
AN ERROR IS,
EX:
SQL> DELETE FROM DEPT1 WHERE DEPTNO=20;
ERROR AT LINE 1:
ORA-02292: INTEGRITY CONSTRAINT (SCOTT.SYS_C005468) VIOLATED -
CHILD RECORD FOUND.
NOTE:
IF WE WANT TO DELETE A RECORD FROM PARENT TABLE WHEN THEY HAVE
CORRESPONDING CHILD RECORDS IN CHILD TABLE THEN WE PROVIDE SOME
SET OF RULES TO PERFORM DELETE OPERATIONS ON PARENT TABLE.THOSE
RULES ARE CALLED AS "CASCADE RULES".
I) ON DELETE CASCADE
II) ON DELETE SET NULL
I) ON DELETE CASCADE:
- WHENEVER WE ARE DELETING A RECORD FROM PARENT TABLE THEN
THAT ASSOCIATED CHILD RECORDS ARE DELETED FROM CHILD TABLE
AUTOMATICALLY.
EX:
STEP1:
SQL> CREATE TABLE DEPT2(DEPTNO INT PRIMARY KEY,DNAME
VARCHAR2(10));
STEP2:
SQL> INSERT INTO DEPT2 VALUES (10,'ORACLE');
SQL> INSERT INTO DEPT2 VALUES (20,'JAVA');
STEP3:
SQL> CREATE TABLE EMP2(EID INT PRIMARY KEY, ENAME VARCHAR2(10),
DEPTNO INT REFERENCES DEPT2(DEPTNO) ON DELETE CASCADE);
STEP4:
SQL>INSERT INTO EMP2 VALUES (1021,'SAI',10);
SQL>INSERT INTO EMP2 VALUES (1022,'JONES',10);
SQL>INSERT INTO EMP2 VALUES (1023,'MILLER',20);
TESTING:
SQL> DELETE FROM DEPT2 WHERE DEPTNO=20;-----ALLOWED
EX:
STEP1:
SQL> CREATE TABLE DEPT3(DEPTNO INT PRIMARY KEY,DNAME
VARCHAR2(10));
STEP2:
SQL> INSERT INTO DEPT3 VALUES (10,'ORACLE');
SQL> INSERT INTO DEPT3 VALUES (20,'JAVA');
STEP3:
SQL> CREATE TABLE EMP3(EID INT PRIMARY KEY, ENAME VARCHAR2(10),
DEPTNO INT REFERENCES DEPT3(DEPTNO) ON DELETE SET NULL);
STEP4:
SQL>INSERT INTO EMP3 VALUES (1021,'SAI',10);
SQL>INSERT INTO EMP3 VALUES (1022,'JONES',10);
SQL>INSERT INTO EMP3 VALUES (1023,'MILLER',20);
TESTING:
SQL> DELETE FROM DEPT3 WHERE DEPTNO=10;-----ALLOWED
EX:
SQL> CREATE TABLE TEST8(SNO INT PRIMARY KEY, NAME VARCHAR2(10));
TESTING:
SQL> INSERT INTO TEST8 VALUES(1,'A');- - - -ALLOWED
SQL> INSERT INTO TEST8 VALUES(1,'B');- - - -NOT ALLOWED
ERROR:
ORA-00001: UNIQUE CONSTRAINT (SCOTT.SYS_C005475) VIOLATED
USER DEFINE CONSTRAINT NAME:
- IN PLACE OF PRE-DEFINE CONSTRAINT NAME WE CAN ALSO CREATE A
USER DEFINED CONSTRAINT KEY NAME (OR) CONSTRAINT ID FOR
IDENTIFYING A CONSTRAINT.
SYNTAX:
<COLUMN NAME> <DT>[SIZE] CONSTRAINT <USER DEFINED CONSTRAINT
NAME> <CONSTRAINT TYPE>
EX:
SQL> CREATE TABLE TEST10(SNO INT CONSTRAINT PK_SNO PRIMARY KEY,
NAME VARCHAR2(10) CONSTRAINT UQ_NAME UNIQUE);
TESTING:
SQL> INSERT INTO TEST10 VALUES(1,'A');
SYNTAX:
SQL> SELECT * FROM DICT;
NOTE1:
IF WE WANT TO VIEW ALL CONSTRAINTS INFROMATION OF A
PARTICULAR TABLE THEN WE USE "USER_CONSTRAINTS" DATA DICTIONARY.
EX:
SQL> DESC USER_CONSTRAINTS;
SQL> SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE FROM
USER_CONSTRAINTS WHERE TABLE_NAME='TEST10';
CONSTRAINT_NAME CONSTRAINT_TYPE
---------------------------------- -------------------------------
PK_SNO P
UQ_NAME U
NOTE2:
- IF WE WANT TO VIEW CONSTRAINT NAME ALONG WITH COLUMN NAME
OF A PARTICULAR TABLE THEN WE USE " USER_CONS_COLUMNS "
DATADICTIONARY.
EX:
SQL> DESC USER_CONS_COLUMNS;
SQL> SELECT CONSTRAINT_NAME, COLUMN_NAME FROM
USER_CONS_COLUMNS WHERE TABLE_NAME='TEST10';
CONSTRAINT_NAME COLUMN_NAME
---------------------------------- ----------------------------
UQ_NAME NAME
PK_SNO SNO
NOTE3:
TO VIEW A LOGICAL CONDITION OF CHECK CONSTRAINT THEN WE NEED
TO CALL "SEARCH_CONDITION" COLUMN FROM "USER_CONSTRAINTS" DATA
DICTIONARY.
EX:
SQL> CREATE TABLE TEST11(SNO INT, SAL NUMBER(10) CHECK(SAL>5000));
E
SQL> DESC USER_CONSTRAINTS;
SQL> SELECT SEARCH_CONDITION FROM USER_CONSTRAINTS
WHERE TABLE_NAME='TEST11';
SEARCH_CONDITION
SAL>5000
NOTE4:
TO VIEW ALL COLUMNS INFORMATION OF A PARTICULAR TABLE THEN
WE USE "USER_TAB_COLUMNS" DATADICTIONARY.
EX:
SQL> DESC USER_TAB_COLUMNS;
SQL> SELECT COLUMN_NAME FROM USER_TAB_COLUMNS
WHERE TABLE_NAME='EMP';
COUNT (*)
14
COUNT (*)
8
EX:
SQL> ALTER TABLE TEST12 MODIFY ENAME CONSTRAINT NN_ENAME NOT
NULL;
EX:
SQL> CREATE TABLE TEST13(DNAME VARCHAR2(10), EID INT);
TABLE CREATED.
EX:
SQL> ALTER TABLE TEST13 ADD CONSTRAINT FK_EID FOREIGN KEY(EID)
REFERENCES TEST12(EID) ON DELETE CASCADE;
HOW TO DROP CONSTRAINT FROM AN EXISTING TABLE:
SYNTAX:
ALTER TABLE <TN> DROP CONSTRAINT <CONSTRAINT KEY NAME>;
METHOD2:
- WHEN WE DROP PRIMARY KEY ALONG WITH FOREIGN KEY CONSTRAINT
FROM PARENT AND CHILD TBALES THEN WE USE "CASCADE" STATEMENT.
EX:
SQL> ALTER TABLE TEST12 DROP CONSTRAINT PK_EID CASCADE;
EX:
SQL> CREATE TABLE TEST14(SNO INT PRIMARY KEY);
SQL> SELECT CONSTRAINT_NAME FROM USER_CONS_COLUMNS
WHERE TABLE_NAME='TEST14';
CONSTRAINT_NAME
------------------------------
SYS_C005489
SQL> ALTER TABLE TEST14 RENAME CONSTRAINT SYS_C005489 TO SNO_PK;
SQL> SELECT CONSTRAINT_NAME FROM USER_CONS_COLUMNS
WHERE TABLE_NAME='TEST14';
CONSTRAINT_NAME
------------------------------
SNO_PK
SYNTAX:
ALTER TABLE <TN> DISABLE / ENABLE CONSTRAINT <CONSTRAINT KEY
NAME>;
EX:
SQL> CREATE TABLE TEST15(ENAME VARCHAR2(10), SAL NUMBER (10)
CHECK(SAL=5000));
EX:
SQL> ALTER TABLE TEST15 ENABLE CONSTRAINT SYS_C005492;
ERROR AT LINE 1:
ORA-02293: CANNOT VALIDATE (SCOTT.SYS_C005492) - CHECK CONSTRAINT
VIOLATED
EX:
SQL> ALTER TABLE TEST15 ENABLE NOVALIDATE CONSTRAINT SYS_C005492;
TABLE ALTERED.
TESTING:
SQL> INSERT INTO TEST15 VALUES('SCOTT',6000); ---NOT ALLOWED
ERROR AT LINE 1:
ORA-02290: CHECK CONSTRAINT (SCOTT.SYS_C005492) VIOLATED
DEFAULT CONSTRAINT:
- IT A SPECIAL TYPE OF CONSTRAINT WHICH IS USED TO ASSIGN A
USER DEFINE DEFAULT VALUE TO A COLUMN.
SYNTAX:
<COLUMN NAME> <DATATYPE>[SIZE] DEFAULT <VALUE /
EXPRESSION>
EX:
SQL> CREATE TABLE TEST17(SNO INT, SAL NUMBER (10) DEFAULT 5000);
TABLE CREATED.
TESTING:
SQL> INSERT INTO TEST17 VALUES (1,8500);
SQL> INSERT INTO TEST17(SNO)VALUES (2);
OUTPUT:
SNO SAL
--------------- ----------
1 8500
2 5000
NOTE:
- IF WE WANT TO VIEW DEFAULT VALUE OF A COLUMN THEN WE USE
"USER_TAB_COLUMNS" DATADICTIONARY.
EX:
SQL> DESC USER_TAB_COLUMNS;
SQL> SELECT COLUMN_NAME, DATA_DEFAULT FROM USER_TAB_COLUMNS
WHERE TABLE_NAME='TEST18';
COLUMN_NAME DATA_DEFAULT
-------------------------- --------------------------------
SAL 8000
COLUMN_NAME DATA_DEFAULT
-------------------------- --------------------------------
SAL NULL
TRANSACTION CONTROL LANGUAGE (TCL)
TRANSACTION:
- A TRANSACTION IS A UNIT OF WORK THAT IS PERFORMED
AGAINST DATABASE.
Ex:
- IF WE ARE INSERTING / UPDATING / DELETING DATA TO /
FROM A TABLE THEN WE ARE PERFORMING A TRANSACTION ON A
TABLE.
- TO MANAGE TRANSACTIONS ON DATABASE TABLES THEN
WE PROVIDE THE FOLLOWING COMMAND ARE
1) COMMIT
2) ROLLBACK
3) SAVEPOINT
COMMIT:
- THIS COMMAND IS USED TO MAKE A TRANSACTION IS
PERMANENT.THESE ARE TWO TYPES.
i) IMPLICIT COMMIT:
- THESE TRANSACTIONS ARE COMMITTED BY SYSTEM
(ORACLE DB) BY DEFAULT.
Ex: DDL COMMANDS
STEP1:
SQL> INSERT INTO BRANCH VALUES (1021,'SBI','HYD');
SQL> COMMIT;
STEP2:
SQL> UPDATE BRANCH SET BLOC='MUMBAI' WHERE
BCODE=1021;
SQL> COMMIT;
STEP3:
SQL> DELETE FROM BRANCH WHERE BCODE=1021;
SQL> COMMIT;
ROLLBACK:
- THIS COMMAND IS USED TO CANCEL TRANSACTION.BUT
ONCE A TRANSACTION IS COMMITTED THEN WE CANNOT
"ROLLBACK(CANCEL)".
EX:
SQL> DELETE FROM BRANCH WHERE BCODE=1021;
SQL> ROLLBACK;
RULE OF TRANSACTION:
- THE RULE OF TRANSACTION TELLS THAT EITHER ALL THE
STATEMENTS IN THE TRANSACTION SHOULD BE EXECUTED (ALL
ARE COMMITTED) SUCCESSFULLY OR NONE OF THOSE
STATEMENTS TO BE EXECUTED. (i.e., ALL ARE CANCELLED)
SAVEPOINT:
- WHENEVER A USER CREATE SAVEPOINT WITH IN THE
TRANSACTION THEN INTERNALLY SYSTEM IS ALLOCATING A
SPECIAL MEMORY FOR A SAVEPOINT AND STORE A TRANSACTION
INFROMATION WHICH WE WANT TO ROLLBACK(CANCEL).
HOW TO CREATE A SAVEPOINT:
SYNTAX:
SQL> SAVEPOINT <POINTER NAME>;
EX1:
SQL> DELETE FROM BRANCH WHERE BCODE=1021;
SQL> DELETE FROM BRANCH WHERE BCODE=1025;
CASE1:
======
SQL> ROLLBACK TO S1; ------1023 RECORD ONLY
CASE2:
======
SQL> ROLLBACK; ----- 1021,1025 ROLLBACK
(OR)
SQL> COMMIT; ------ 1021,1025 COMMITTED
EX2:
SQL> DELETE FROM BRANCH WHERE BCODE=1021;
CASE1:
SQL> ROLLBACK TO S1; ----- 1023,1025 RECORDS ARE ROLLBACK
CASE2:
SQL> ROLLBACK; ------1021 ROLLBACK
(OR)
SQL> COMMIT; ------1021 COMMITTED
NOTE:
- GENERALLY, ALL DATABASES ARE MAINTAINING "ACID"
PROPERTIES BY DEFAULT TO MAINTAIN
ACCURATE AND CONSISTENCY DATA.
ATOMICITY:
THE ENTIRE TRANSACTION TAKES PLACE AT ONCE OR DOESNOT
HAPPEN AT ALL.
CONSISTENCY:
THE DATABASE MUST BE CONSISTENT BEFORE AND AFTER THE
TRANSACTION.
ISOLATION:
MULTIPLE TRANSACTIONS OCCURE INDEPENDENTLY WITHOUT
INTERFERENCE.
DURABILITY:
MEANS ONCE A TRANSACTION HAS BEEN COMMITTED IT WILL
REMAIN SO, EVEN IN THE EVENT OF ERRORS, POWER LOSS
.............................................................................................
etc
SUBQUERY / NESTED QUERY:
> A QUERY INSIDE ANOTHER QUERY IS CALLED AS SUBQUERY OR NESTED
QUERY.
> A SUBQUERY IS HAVING TWO MORE QUERIES THOSE ARE,
I) INNER / CHILD / SUB QUERY
II) OUTER / PARENT / MAIN QUERY
SYNTAX:
SELECT * FROM <TN> WHERE <CONDITION> (SELECT * FROM...................);
> AS PER THE EXECUTION PROCESS OF SUBQUERY IT AGAIN CLASSIFIED INTO
TWO CATEGORISED.
1) NON - CORELETED SUBQUERIES:
- IN NON-CO RELATED SUBQUERY FIRST INNER QUERY IS EXECUTED
AND RETURN A VALUE BASED ON RETURN VALUE OF INNER QUERY LATER
OUTER QUERY WILL EXECUTE AND PRODUCE THE FINAL RESULT.
2) CORELATED SUBQUERIES:
- IN CO RELATED SUBQUERY FIRST OUTER QUERY IS EXECUTED AND
RETURN VALUES BASED ON RETURN VALUES OF OUTER QUERY LATER INNER
QUERY WILL EXECUTE AND PRODUCE THE FINAL RESULT.
TYPES OF NON - CORELETED SUBQUERIES:
> SINGLE ROW SUBQUERY
> MULTIPLE ROW SUBQUERY
> MULTIPLE COLUMN SUBQUERY
> INLINE VIEW
STEP2:(OUTER QUERY):
SELECT * FROM EMP WHERE SAL= (INNER QUERY);
EX2:
WHOSE EMPLOYEE JOB IS SAME AS THE JOB OF 'SMITH’?
SOL:
SQL> SELECT * FROM EMP WHERE JOB= (SELECT JOB FROM EMP WHERE
ENAME='SMITH');
EX3:
WHOSE SALARY IS MORE THAN MAX.SALARY OF THE JOB IS "SALESMAN"?
SOL:
SQL> SELECT * FROM EMP WHERE SAL> (SELECT MAX(SAL) FROM EMP WHERE
JOB='SALESMAN');
EX4:
WHOSE EMPLOYEE JOB IS SAME AS THE JOB OF "BLAKE" AND WHO ARE
EARNING
SALARY MORE THAN "BLAKE" SALARY?
SOL:
SELECT * FROM EMP WHERE JOB= (SELECT JOB FROM EMP WHERE
ENAME='BLAKE')
AND SAL> (SELECT SAL FROM EMP WHERE ENAME='BLAKE');
EX5:
DISPLAY SENIOR EMPLOYEE?
SOL:
SQL> SELECT * FROM EMP WHERE HIREDATE=(SELECT MIN(HIREDATE) FROM
EMP);
EX6:
TO FIND SECOND HIGH. SALARY FROM EMP TABLE ?
SOL:
SQL> SELECT MAX(SAL) FROM EMP WHERE SAL<(SELECT MAX(SAL) FROM
EMP);
MAX(SAL)
-------------------
3000
EX7:
WASQ DISPLAY EMPLOYEE DETAILS WHO ARE GETTING
SECOND HIGH. SALARY IN EMP TABLE?
SOL:
SQL> SELECT * FROM EMP WHERE SAL= (SELECT MAX(SAL) FROM EMP WHERE
SAL< (SELECT MAX(SAL) FROM EMP));
EX8:
DISPLAY EMPLOYEE DETAILS WHO ARE GETTING
3RD HIGH. SALARY IN EMP TABLE?
SOL:
SQL> SELECT * FROM EMP WHERE SAL=
(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP WHERE SAL<
(SELECT MAX(SAL) FROM EMP)));
EX9:
TO DISPLAY NO. OF EMPLOYEE OF DEPARTMENT NUMBERS.IN WHICH DEPTNO
NO. OF EMPLOYEE IS LESS THAN THE NO. OF EMPLOYEE OF DEPTNO IS 20?
SOL:
SQL> SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO
HAVING COUNT(*)<(SELECT COUNT(*) FROM EMP WHERE DEPTNO=20);
EX10:
SUM OF SALARY OF JOBS.IF SUM OF SALARY OF JOBS ARE
MORE THAN SUM OF SALARY OF THE JOB IS 'CLERK’?
SOL:
SQL> SELECT JOB,SUM(SAL) FROM EMP GROUP BY JOB
HAVING SUM(SAL)>(SELECT SUM(SAL) FROM EMP WHERE JOB='CLERK');
SOL:
SQL> UPDATE EMP SET SAL=(SELECT MAX(SAL) FROM EMP) WHERE
EMPNO=7900;
SOL:
SQL> DELETE FROM EMP WHERE JOB=(SELECT JOB FROM EMP WHERE
ENAME='SCOTT');
SOL:
SQL> SELECT * FROM EMP WHERE JOB IN(SELECT JOB FROM EMP WHERE
ENAME='SMITH' OR ENAME='CLARK');
EX2:
DISPLAY EMPLOYEE DETAILS WHO ARE GETTING MIN, MAX SALARIES?
SOL:
SELECT * FROM EMP WHERE SAL IN(
SELECT MIN(SAL) FROM EMP
UNION
SELECT MAX(SAL) FROM EMP);
EX3:
TO DISPLAY THE SENIOR MOST EMPLOYEES FROM EACH DEPTNO WISE?
SOL:
SQL> SELECT * FROM EMP WHERE HIREDATE IN(SELECT MIN(HIREDATE) FROM
EMP GROUP BY DEPTNO);
EX4:
TO DISPLAY EMPLOYEES WHO ARE EARNING HIGHEST SALARY FROM EACH JOB
WISE?
SQL> SELECT * FROM EMP WHERE SAL IN(SELECT MAX(SAL) FROM EMP GROUP
BY JOB);
WORKING WITH "ANY”, "ALL" OPERATORS:
ANY: IS USED TO SATISFIED ANY OF THE VALUES IN THE GIVEN
LIST WITH USER DEFINED CONDITION.
EX:
WASQ TO DISPLAY EMPLOYEES WHOSE SALARY IS MORE THAN ANY
"SALESMAN"SALARY?
SOL:
SQL> SELECT * FROM EMP WHERE SAL>ANY (SELECT SAL FROM EMP WHERE
JOB='SALESMAN');
EX:
WASQ TO DISPLAY EMPLOYEES WHOSE SALARY IS MORE THAN OF ALL
"SALESMAN"SALARY?
SOL:
SQL> SELECT * FROM EMP WHERE SAL>ALL (SELECT SAL FROM EMP WHERE
JOB='SALESMAN');
E
TO DISPLAY EMPLOYEES WHO ARE EARNING HIGHEST SALARY FROM EACH JOB
WISE BY USING MULTIPLE ROW SUBQUERY?
SQL> UPDATE EMP SET SAL=1300 WHERE EMPNO=7902;
SQL> SELECT * FROM EMP WHERE SAL IN (SELECT MAX(SAL) FROM EMP
GROUP BY JOB);
OUTPUT:
JOB SAL
--------- ----------
ANALYST 1300
CLERK 1300
SALESMAN 1600
MANAGER 2975
ANALYST 3000
PRESIDENT 5000
--------- ----------
CLERK 1300
SALESMAN 1600
MANAGER 2975
ANALYST 3000
PRESIDENT 5000
E
WAQ TO DISPLAY EMPLOYEE WHOSE JOB, MGR ARE SAME AS THE JOB, MGR OF
THE EMPLOYEE "SCOTT”?
SOL:
SQL> SELECT * FROM EMP WHERE (JOB, MGR) IN (SELECT JOB,MGR FROM EMP
WHERE ENAME='SCOTT');
PSEUDO COLUMNS:
PSEUDO COLUMN IS JUST LIKE A TABLE COLUMN.
I) ROWID
II) ROWNUM
ROWID:
WHEN WE INSERT A NEW ROW INTO A TABLE INTERNALLY SYSTE IS
CREATES A UNIQUE ID ADDRESS /NUMBER FOR EACH ROW WISE
AUTOMATICALLY.
THESE ROWID’S ARE STORED IN DATABASE SO THAT THESE ARE
PERMANENT ID’S.
EX:
SQL> SELECT ROWID, ENAME FROM EMP;
ROWID ENAME
------------------ ----------
AAAPLMAAEAAAAADAAA SMITH
EX:
SQL> SELECT MIN(ROWID) FROM EMP;
MIN(ROWID)
------------------
AAAPLMAAEAAAAADAAA
SQL> SELECT MAX(ROWID) FROM EMP;
MAX(ROWID)
------------------
AAAPLMAAEAAAAADAAN
SNO NAME
---------- ----------
10 A
10 A
10 A
20 B
20 B
30 C
30 C
30 C
40 D
40 D
50 E
50 E
50 E
SOL:
SQL> DELETE FROM TEST WHERE ROWID NOT IN (SELECT MAX(ROWID) FROM
TEST GROUP BY SNO);
OUTPUT:
SQL> SELECT * FROM TEST;
SNO NAME
---------- ----------
10 A
20 B
30 C
40 D
50 E
ROWNUM:
TO GENERATE ROW NUMBERS TO EACH ROW WISE / GROUP OF ROWS
WISE AUTOMATICALLY.THESE ROWNUMBERS ARE NOT SAVED IN DB.SO THAT
THESE ARE TEMPORARY NUMBERS.
EX:
SQL> SELECT ROWNUM, ENAME FROM EMP;
ROWNUM ENAME
---------- ----------
1 SMITH
2 ALLEN
1 MILLER 10
2 CLARK 10
3 KING 10
E
WAQ TO FETCH THE FIRST ROW EMPLOYEE DETAILS FROM EMP
TABLE BY USING ROWNUM?
SOL:
SQL> SELECT * FROM EMP WHERE ROWNUM=1;
EX:
WAQ TO FETCH THE SECOND ROW EMPLOYEE DETAILS FROM EMP
TABLE BY USING ROWNUM?
SOL:
SQL> SELECT * FROM EMP WHERE ROWNUM=2;
NO ROWS SELECTED
EX:
WAQ TO FETCH THE FIRST FIVE ROWS FROM EMP TABLE BY USING ROWNUM?
SOL:
SQL> SELECT * FROM EMP WHERE ROWNUM<=5;
EX:
WAQ TO FETCH THE FIFTH ROW EMPLOYEE DETAILS FROM EMP TABLE BY
USING ROWNUM?
SOL:
SELECT * FROM EMP WHERE ROWNUM<=5
MINUS
SELECT * FROM EMP WHERE ROWNUM<=4;
E
WAQ TO FETCH FROM 3RD TO 9TH ROW FROM EMP TABLE BY USING ROWNUM?
SOL:
SELECT * FROM EMP WHERE ROWNUM<=9
MINUS
SELECT * FROM EMP WHERE ROWNUM<3;
EX:
WAQ TO FETCH THE LAST TWO ROWS FROM EMP TABLE BY
ROWNUM? SOL:
SELECT * FROM EMP WHERE ROWNUM<=14
MINUS
SELECT * FROM EMP WHERE ROWNUM<=12;
(OR)
SELECT * FROM EMP
MINUS
SELECT * FROM EMP WHERE ROWNUM<=(SELECT COUNT(*)-2 FROM EMP);
INLINE VIEW:
IT IS SPECIAL TYPE OF SUBQUERY.PROVIDING A SELECT QUERY IN
PLACE OF TABLE NAME IN SELECT STATEMENT.
IN INLINE VIEW SUBQUERY,THE RESULT OF INNER QUERY WILL ACT AS A
TABLE FOR THE OUTER QUERY.
SYNTAX:
SELECT * FROM <TABLE NAME>;----------SQL SELECT QUERY
SELECT * FROM (<SELECT QUERY>);-------INLINE VIEW
NOTE:
1. GENERALLY SUBQUERY IS NOT ALLOWED TO USE “ORDER BY" CLAUSE.SO
THAT WE USE "INLINE VIEW".
2. GENERALLY COLUMN ALIAS NAMES ARE NOT ALLOWED TO USE IN "WHERE"
CLAUSE CONDITION.SO THAT WE USE "INLINE VIEW ".
USING COLUMN ALIAS NAMES IN WHERE CLAUSE CONDITION:
EX:
WAQ TO DISPLAY EMPLOYEE WHOSE EMPLOYEE ANNUAL SALARY IS MORE
THAN 25000?
SOL:
SQL> SELECT * FROM (SELECT ENAME,SAL,SAL*12 ANNUSAL FROM EMP)
WHERE ANNUSAL>25000;
EX:
WAQ TO DISPLAY 5TH HIGHEST SALARY OF EMPLOYEE FROM EMP
TABLE BY USING ROWNUM ALONG WITH INLINE VIEW?
SOL:
SELECT * FROM (SELECT * FROM EMP ORDER BY SAL DESC) WHERE
ROWNUM<=5
MINUS
SELECT * FROM (SELECT * FROM EMP ORDER BY SAL DESC) WHERE
ROWNUM<=4;
EX:
WAQ TO DISPLAY FIRST ROW AND LAST ROW FROM EMP TABLE BY USING
ROWNUM ALIAS NAME ALONG WITH INLINE VIEW?
SQL> SELECT * FROM (SELECT ROWNUM R,EMP.* FROM EMP) WHERE R=1 OR
R=(SELECT COUNT(*) FROM EMP);
ANALYTICAL FUNCTIONS:
- ORACLE SUPPORTING THE FOLLOWING THREE TYPES OF ANALYTICAL
FUNCTIONS THOSE ARE,
1. ROW_NUMBER ()
2. RANK ()
3. DENSE_RANK ()
THESE ANALYTICAL FUNCTIONS ARE AUTOMATICALLY GENERATE
RANKING NUMBERS TO EACH ROW WISE (OR) GROUP OF ROWS WISE EXCEPT
ROW_NUMBER (). THIS FUNCTION WILL GENERATE ROW NUMBERS FOR EACH
ROW WISE / GROUP OF ROWS WISE.
EX:
ENAME SALARY ROW_NUMBER () RANK () DENSE_RANK ()
A 85000 1 1 1
B 72000 2 2 2
C 72000 3 2 2
D 68000 4 4 3
E 55000 5 5 4
RANK (), DENSE_RANK () WILL ASSIGN SAME RANK NUMBER TO SAME
VALUE BUT RANK () WILL SKIP THE NEXT RANK NUMBER IN THE ORDER
WHERE AS DENSE_RANK () WILL NOT SKIP THE NEXT RANK NUMBER IN THE
ORDER.
SYNTAX:
ANALYTICAL FUNCTION NAME () OVER () [ PARTITION BY <COLUMN NAME>]
ORDER BY <COLUMN NAME> [ASC / DESC ])
HERE,
PARTITION BY CLAUSE IS OPTIONAL.
ORDER BY CLAUSE IS MANDATORY.
OUTPUT:
ENAME SAL DEPTNO RANKS
KING 5000 10 1
CLARK 2450 10 2
MILLER 1300 10 3
EX1:
WAQ TO DISPLAY 3RD HIGHEST SALARY EMPLOYEE DETAILS FROM EMP TABLE
IN EACH DEPTNO WISE BY USING DENSE_RANK () ALONG WITH INLINE VIEW?
SOL:
SELECT * FROM (SELECT ENAME,SAL,DEPTNO,DENSE_RANK()OVER(PARTITION
BY DEPTNO ORDER BY SAL DESC) R FROM EMP) WHERE R=3;
EX2:
WAQ TO DISPLAY THE 4TH SENIOR MOST EMPLOYEE FROM EACH JOB WISE?
SOL:
SELECT * FROM (SELECT ENAME, JOB, HIREDATE, DENSE_RANK () OVER
(PARTITION BY JOB ORDER BY HIREDATE) R FROM EMP) WHERE R=4;
2. CO-RELATED SUBQUERY:
- IN CO-RELATED SUBQUERY FIRST OUTER QUERY IS EXECUTED AND
LATER INNER QUERY WILL EXECUTE.
EX1: TO FIND OUT EMPLOYEE WHO ARE GETTING FIRST HIGHEST SALARY
FROM EMPLOYEE TABE?
SOL:
SELECT * FROM EMPLOYEE E1 WHERE 0= (SELECT COUNT (DISTINCT SAL)
FROM EMPLOYEE E2 WHERE E2.SAL>E1.SAL);
EX2: TO FIND OUT EMPLOYEE WHO ARE GETTING FOURTH HIGHEST SALARY
FROM EMPLOYEE TABLE?
SOL:
SQL> SELECT * FROM EMPLOYEE E1 WHERE=(SELECT COUNT(DISTINCT SAL)
FROM EMPLOYEE E2 WHERE E2.SAL>E1.SAL);
EXISTS OPERATOR:
- IT A SPECIAL OPERATOR WHICH IS USED IN CO-RELATED SUBQUERY
ONLY.THIS OPERATOR IS USED TO CHECK WETHER ROW / ROWS EXISTS IN
THE TABLE OR NOT.
- IT RETRUNS EITHER TRUE (OR) FALSE.IF SUBQUERY RETRUNS AT
LEAST ONE ROW THEN RETRUNS TRUE OR ELSE IF SUBQUERY NOT RETRUNS
ANY ROW THEN RETURN FALSE.
SYNTAX:
WHERE EXISTS (<SELECT STATEMENT>)
EX1:
WAQ TO DISPLAY DEPARTMENT DETAILS IN WHICH DEPARTMENT EMPLOYEE
ARE WORKING?
SOL:
SQL> SELECT * FROM DEPT D WHERE EXISTS (SELECT DEPTNO FROM EMP E
WHERE E. DEPTNO=D.DEPTNO);
EX2:
WAQ TO DISPLAY DEPARTMENT DETAILS IN WHICH DEPARTMENT EMPLOYEE
ARE NOT WORKING?
SOL:
SQL> SELECT * FROM DEPT D WHERE NOT EXISTS (SELECT DEPTNO FROM EMP
E WHERE E. DEPTNO=D.DEPTNO);
SCALAR SUBQUERY:
- SUBQUERIES IN SELECT CLAUSE IS CALLED AS SCALAR
SUBQUERY.EVERY SUBQUERY OUTPUT WILL ACT AS A COLUMN.
SYNTAX:
--------------
SELECT (SUBQUERY1), (SUBQUERY2),...............FROM <TABLE NAME> [ WHERE
<COND>];
EX:
SQL> SELECT (SELECT COUNT (*) FROM EMP) AS EMPTOTAL, (SELECT COUNT
(*) FROM DEPT) AS DEPTTOTAL FROM DUAL;
EMPTOTAL DEPTTOTAL
----------------- ----------
14 4
EX:
SQL> SELECT (SELECT SUM(SAL) FROM EMP WHERE DEPTNO=10) AS "10",
(SELECT SUM(SAL) FROM EMP WHERE DEPTNO=20) AS "20",
(SELECT SUM(SAL) FROM EMP WHERE DEPTNO=30) AS "30"
FROM DUAL;
10 20 30
------------
---------- ----------
8750 10875 9400
DB Security
Authentication: Authentication is a process of verifying
the credentials (username & password) of a user to login into
the system.
GRANT
REVOKE
CONNECTED.
SYNTAX:
ERROR:
CONNECTED.
CONNECTED.
SQL> PASSWORD
A Old password: A
Password changed
Connected
.
NOTE:
EX:
CONNECTED.
GRANTED.
EX:
TABLE CREATED
GRANTED.
SQL> COMMIT;
SQL> COMMIT;
SQL> COMMIT;
i) SYSTEM PRIVILEGES
i) SYSTEM PRIVILEGES:
SYNTAX:
EX:
Connected.
Grant succeeded.
Connected.
Synonym created.
View created.
SYNTAX:
EX:
(OR)
ERROR at line 1:
EX:
Connected.
Grant succeeded.
SQL> CONN A/123;
Connected.
EX:
EX:
EX:
EX:
A;
ERROR:
EX:
Grant succeeded.
EX:
User created.
ERROR:
CONNECTED.
ERROR at line 1:
TABLE CREATED.
EX:
EX:
SYNTAX:
SYNTAX:
SYNTAX:
Role created.
Grant succeeded.
Grant succeeded.
EX:
ROLE PRIVILEGE
----------- --------------------------------
R1 CREATE SYNONYM
EX:
R1 SELECT DEPT
EX:
USERNAME GRANTED_ROLE
---------------- ---------------------------
U1 R1
EX:
ERROR at line 1:
EX:
SYNTAX:
&
SYNTAX:
&
TYPES OF SYNONYMS:
1. PRIVATE SYNONYM (DEFAULT)
2. PUBLIC SYNONYM
1. PRIVATE SYNONYMS:
> THESE SYNONYMS ARE CREATED BY USERS WHICH HAVE
PERMISSION.
SYNTAX:
CREATE SYNONYM <SYNONYM NAME> FOR [USERNAME]. <DB
OBJECT NAME>;
EX:
SQL> CONN SCOTT/TIGER;
SQL> CREATE USER U1 IDENTIFIED BY U1;
SQL> GRANT CONNECT, CREATE TABLE, UNLIMITED TABLESPACE
TO U1;
SQL> CONN U1/U1;
SQL> CREATE TABLE STUDENTDETAILS (STID INT, SNAME
VARCHAR2(10));
SQL> INSERT INTO STUDENTDETAILS VALUES (1021,'SAI');
SQL> INSERT INTO STUDENTDETAILS VALUES (1022,'JONES');
SQL> COMMIT;
TESTING:
SQL> SELECT * FROM SYN1;
SQL> INSERT INTO SYN1 VALUES (1023,'MILLER');
SQL> UPDATE SYN1 SET SNAME='SCOTT' WHERE STID=1022;
SQL> DELETE FROM SYN1 WHERE STID=1023;
2. PUBLIC SYNONYMS:
THESE SYNONYMS ARE CREATED BY DBA.WE SHOULD HAVE
"CREATE PUBLIC SYNONYM " PRIVILEGE.AND IT CAN ACCESSING
BY ALL USERS.FOR HIDING THE INFORMATION ABOUT
USERNAME, OBJECT NAME(TABLE).
SYNTAX:
CREATE PUBLIC SYNONYM <SYNONYM NAME> FOR [USER NAME].
<DB OBJECT NAME>;
EX:
SQL> CONN SCOTT/TIGER;
SQL> CREATE PUBLIC SYNONYM PUB_SYN FOR DEPT;
SQL> GRANT ALL ON PUB_SYN TO U1, U2, U3;
(OR)
SQL> GRANT ALL ON PUB_SYN TO PUBLIC;
EX:
SQL> DESC ALL_SYNONYMS;
SQL> SELECT SYNONYM_NAME, TABLE_NAME FROM
ALL_SYNONYMS WHERE TABLE_NAME='DEPT';
SYNTAX TO DROP SYNONYMS:
SQL> DROP SYNONYM <SYNONYM NAME>;
EX:
SQL> DROP SYNONYM SYN_DEPT;
EX:
SQL> DROP PUBLIC SYNONYM PUB_SYN;
TYPES OF VIEWS:
A USER CAN CREATE THE FOLLOWING TWO TYPES OF VIEWS
ON BASE TABLES THOSE ARE,
1. SIMPLE VIEWS
2. COMPLEX VIEWS
1. SIMPLE VIEWS:
WHEN WE CREATE A VIEW TO ACCESS REQUIRED DATA
FROM A SINGLE BASE TABLE IS CALLED AS SIMPLE VIEWS.
THROUGH A SIMPLE VIEW WE CAN PERFORM ALL DML
(INSERT, UPDATE, DELETE) OPERATIONS ON BASE TABLE.
SYNTAX:
CREATE VIEW <VIEW NAME> AS SELECT * FROM <TN> [ WHERE
<CONDITION>];
EX1:
SQL> CREATE VIEW SV1 AS SELECT * FROM DEPT;
SQL> SELECT * FROM SV1;
TESTING:
SQL> INSERT INTO SV2 VALUES (1122,'SAI','HR',8000); ---ALLOW
SQL> INSERT INTO SV2 VALUES (1122,'WARNER','SR.HR',9500); -
---NOT ALLOW (EMPNO COLUMN IS PRIMARY KEY COLUMN IN
EMP TABLE)
EX:
SQL> CREATE VIEW SV3 AS SELECT * FROM TEST1 WHERE
SAL=18000 WITH CHECK OPTION;
TESTING:
SQL> INSERT INTO SV3 VALUES (1025,'SCOTT',12000); ---NOT
ALLOW
SQL> INSERT INTO SV3 VALUES (1025,'SCOTT',58000); ---NOT
ALLOW
SQL> INSERT INTO SV3 VALUES (1025,'SCOTT',18000); ---
ALLOWED
WITH READ ONLY:
IF WE CREATED A VIEW "WITH READ ONLY" CLAUSE THEN WE
RESTRICT DML OPERATIONS.WE ALLOW "SELECT" AND "DESC"
COMMANDS.
EX:
SQL> CREATE VIEW SV4 AS SELECT * FROM DEPT WITH READ
ONLY;
EX1:
SQL> CREATE VIEW CV1 AS SELECT * FROM STUDENT S INNER
JOIN COURSE C
ON S.CID=C.CID;
ERROR AT LINE 1:
ORA-00957: DUPLICATE COLUMN NAME
NOTE: WHEN WE CREATE A VIEW ON BASE TABLES THEN WE
SHOULD NOT ALLOW DUPLICATE COLUMN NAMES.TO AVOID THIS
PROBLEM THEN USE "USING" CLAUSE.
SQL> CREATE VIEW CV1 AS SELECT * FROM STUDENT S INNER
JOIN COURSE C USING(CID);
NOW WE CREATED A COMPLEX VIEW ON MULTIPLE
TABLES.BUT NOT ALLOW DML OPERATIONS.
EX
SQL> CREATE VIEW CV2 AS
SELECT * FROM EMP_HYD
UNION
SELECT * FROM EMP_CHENNAI;
EX3:
SQL> CREATE VIEW CV3 AS SELECT DEPTNO, SUM(SAL) FROM
EMP GROUP BY DEPTNO;
ERROR AT LINE 1:
ORA-00998: MUST NAME THIS EXPRESSION WITH A COLUMN
ALIAS
EX:
SQL> CREATE VIEW CV3 AS SELECT DEPTNO, SUM(SAL) AS
SUMSAL FROM EMP
GROUP BY DEPTNO;
TESTING:
SQL> UPDATE CV4 SET SAL=500 WHERE EMPNO=7788; ---
ALLOWED
SQL> DELETE FROM CV4 WHERE EMPNO=7782;-----ALOOWED
SQL> INSERT INTO CV4 VALUES (1122,'SAI',6000,10,'SAP','HYD');
---NOT ALLOW
FORCE VIEWS:
GENERALLY, VIEWS ARE CREATED BASED ON TABLES, BUT
FORCE VIEWS ARE CREATE WITHOUT TABLES.
SYNTAX:
CREATE FORCE VIEW <VIEW NAME> AS SELECT * FROM <TN>;
EX:
SQL> CREATE FORCE VIEW FV1 AS SELECT * FROM TEST;
WARNING: VIEW CREATED WITH COMPILATION ERRORS.
TESTING:
SQL> SELECT * FROM FV1;
ERROR AT LINE 1:
ORA-04063: VIEW "SCOTT.FV1" HAS ERRORS
SQL> DESC FV1;
ERROR:
ORA-24372: INVALID OBJECT FOR DESCRIBE
EX:
SQL> CREATE TABLE TEST (SNO INT, NAME VARCHAR2(10));
TABLE CREATED.
TESTING:
SQL> SELECT * FROM FV1;-----ACTIVATED
SQL> DESC FV1;-----ACTIVATED
EX:
SQL> DESC USER_VIEWS;
SQL> SELECT VIEW_NAME FROM USER_VIEWS;
EX:
SQL> DROP VIEW SV1;
SQL> DROP VIEW CV1;
SQL> DROP VIEW FV1;
ADVANTAGES OF VIEWS:
1. IT IS PROVIDING SECURITY.IT MEANS THAT TO EACH USER
CAN BE GIVEN PERMISSION TO ACCESS SPECIFIC COLUMNS &
SPECIFIC ROWS FROM A TABLE.
2. IF DATA IS ACCESSED AND ENTERED THROUGH A VIEW,THE DB
SERVER WILL CHECK DATA TO ENSURE THAT IT MEETS SPECIFIED
INTERGRITY CONSTRAINTS RULES OR NOT.
3. QUERY SIMPLIFY IT MEANS THAT TO REDUCE COMPLEX QUERY.
SYNONYM VIEW
1. IT IS A MIRROR OF TABLE. 1. IT IS A SUBSET OF
TABLE.
2. CREATED ON A SINGLE TABLE. 2. CREATED ON
MULTIPLE TABLES.
SYNTAX:
CREATE MATERIALIZED VIEW <VIEW NAME> AS SELECT * FROM
<TABLE NAME>;
EX:
SQL> CREATE TABLE TEST1 (SNO INT, NAME VARCHAR2 (20));
ON DEMAND / ON COMMIT:
IN ORACLE WE ARE REFRESHING MATERIALIZED VIEW IN TWO
WAYS THOSE ARE,
I) ON DEMAND:
SYNTAX:
EXECUTE DBMS_MVIEW.REFRESH ('MVIEW NAME');
EX:
EXECUTE DBMS_MVIEW.REFRESH ('MV1');
II) ON COMMIT:
WE CAN REFRESHING A MATERIALIZED VIEW WITHOUT USING
"DBMS_MVIEW" BUT USING "ON COMMIT" METHOD.
SYNTAX:
ERROR:
TABLE 'TEST2' DOES NOT CONTAIN A PRIMARY KEY CONSTRAINT.
EX:
CREATE TABLE TEST2 (EID INT PRIMARY KEY, SAL NUMBER (10));
EX:
CREATE MATERIALIZED VIEW MV2 REFRESH ON COMMIT
AS SELECT * FROM TEST2;
1) RANGE PARTITION:
- IN THIS METHOD WE ARE CREATING PARTITIONS TABLE
BASED ON A PARTICULAR RANGE VALUE.
SYNTAX:
CREATE TABLE <TN> (<COLUMN NAME1> <DATATYPES>[SIZE],
......................................) PARTITION BY RANGE (<KEY
COLUMN NAME>) (PARTITION <PARTITION NAME1> VALUES
LESS THAN(VALUE), PARTITION <PARTITION NAME2> VALUES
LESS THAN(VALUE),.................................................);
EX:
CREATE TABLE TEST1(EID INT, ENAME VARCHAR2(10), SAL
NUMBER (10)) PARTITION BY RANGE(SAL) (PARTITION P1
VALUES LESS THAN (1000),PARTITION P2 VALUES LESS THAN
(2000), PARTITION P3 VALUES LESS THAN (3000));
TESTIN
SQL> INSERT INTO TEST1 VALUES(1,'SAI',2500); SQL>
INSERT INTO TEST1 VALUES(2,'JONES',500);
....................................................................................;
.....................................................................................;
2) LIST PARTITION:
- IN THIS METHOD WE ARE CREATING PARTITIONS BASED
ON LIST OF VALUES.
SYNTAX:
CREATE TABLE <TN> (<COLUMN NAME1> <DATATYPE>[SIZE],
........................................)
PARTITION BY LIST (<KEY COLUMN NAME>) (PARTITION
<PARTITION NAME1> VALUES (VALUE1, VALUE2,.......),
PARTITION <PARTITION NAME2> VALUES (VALUE1, VALUE2,
......), ............, PARTITION OTHERS VALUES(DEFAULT));
EX:
CREATE TABLE TEST2(SNO INT, CNAME VARCHAR2(10))
PARTITION BY LIST(CNAME) (PARTITION P1
VALUES('ORACLE','MYSQL'),
PARTITION P2 VALUES('JAVA','PHP'), PARTITION OTHERS
VALUES(DEFAULT));
TESTIN
SQL> INSERT INTO TEST2 VALUES(1,'ORACLE');
SQL> INSERT INTO TEST2 VALUES(2,'C');
...................................................................
SNO CNAME
-------------- ----------
1 ORACLE
3) HASH PARTITION:
- IN THIS METHOD PARTITIONS ARE CREATED BY THE
SYSTEM BY DEFAULT.
SYNTAX:
CREATE TABLE <TN> (<COLUMN NAME1> <DATATYPE>[SIZE],
........................................) PARTITION BY HASH (<KEY
COLUMN NAME>) PARTITIONS <NUMBER>;
EX:
SQL> CREATE TABLE TEST3(SNO INT, SAL NUMBER (10))
PARTITION BY HASH(SAL) PARTITIONS 5;
NOTE: IF WE WANT TO VIEW ALL PARTITIONS INFORMATION IN
ORACLE DATABASE THEN WE USE "USER_TAB_PARTITIONS" DATA
DICTIONARY.
EX:
SQL> DESC USER_TAB_PARTITIONS;
SQL> SELECT PARTITION_NAME FROM USER_TAB_PARTITIONS
WHERE TABLE_NAME='TEST3';
ADDING A NEW PARTITION:
SYNTAX:
ALTER TABLE <TN> ADD PARTITION <PARTITION NAME> VALUES
LESS THAN(VALUE);
EX:
SQL> ALTER TABLE TEST1 ADD PARTITION P4 VALUES LESS THAN
(4000);
DROPPING A PARTITION:
SYNTAX:
ALTER TABLE <TN> DROP PARTITION <PARTITION NAME>;
EX:
SQL> ALTER TABLE TEST1 DROP PARTITION P1;
EX:
SQL> DESC USER_TABLES;
SQL> SELECT PARTITIONED FROM USER_TABLES WHERE
TABLE_NAME='EMP';
SEQUENCE:
- SEQUENCE IS A DB OBJECT.WHICH IS USED TO GENERATE
SEQUENCE NUMBERS ON A PARTICULAR COLUMN
AUTOMATICALLY.
SYNTAX:
CREATE SEQUENCE <SEQUENCE NAME>
[ START WITH N]
[ MINVALUE N]
[ INCREMENT BY N]
[ MAXVALUE N]
[ NO CYCLE / CYCLE]
[ NO CACHE / CACHE N];
START WITH N:
- IT REPRESENT THE STARTING SEQUENCE NUMBER.HERE "N" IS
REPRESENT WITN NUMBER.
MINVALUE N:
- IT SPECIFY THE MINIMUM VALUE OF THE SEQUENCE.HERE "N"
IS REPRESENT WITN NUMBER.
INCREMENT BY N:
- IT SPECIFY THE INCREMENTAL VALUE IN BETWEEN SEQUENCE
NUMBERS.HERE "N" IS REPRESENT WITN NUMBER.
MAXVALUE N:
- IT SPECIFY THE MAXIMUM VALUE OF THE SEQUENCE.HERE "N"
IS REPRESENT WITN NUMBER.
NO CYCLE:
- IT IS DEFAULT PARAMETER.IF WE CREATED SEQUENCE WITH "
NO CYCLE " THEN SEQUENCE STARTS FROM START WITH VALUE
AND GENERATE VALUES UPTO MAX VALUE.AFTER REACHING MAX
VALUE THEN SEQUENCE IS STOP.
CYCLE:
- IF WE CREATED A SEQUENCE WITH "CYCLE" THEN SEQUENCE
STARTS FROM START WITH VALUE AND GENERATE VALUES UPTO
MAXVALUE.AFTER REACHING MAX VALUE THEN SEQUENCE WILL
STARTS WITH MINVALUE.
NO CACHE:
- IT IS DEFAULT PARAMETER.WHEN WE CREATED A SEQUENCE
WITH "NO CACHE"
PARAMETER THEN THE SET OF SEQUENCE VALUES ARE STORING
INTO DATABASE
MEMORY.EVERY TIME WE WANT ACCESS SEQUENCE NUMBERS
THEN ORACLE SERVER WILL GO TO DATABASE MEMORY AND
RETURN TO USER.SO THAT IT WILL DEGRADE THE PERFORMANCE
OF AN APPLICATION.
CACHE N:
- WHEN WE CREATED A SEQUENCE WITH "CACHE " PARAMETER
THEN SYSTEM IS ALLOCATING TEMP. MEMORY(CACHE) AND IN
THIS MEMORY WE WILL STORE THE SET SEQUENCE
NUMBERS.WHENEVER USER WANT TO ACCESS SEQUENCE
NUMBERS THEN ORACLE SERVER WILL GO TO CACHE MEMORY
AND RETURN TO USER.
- ACCESSING DATA FROM CACHE IS MUCH FASTER THAN
ACCESSING DATA FROM DATABASE.IT WILL INCRESE THE
PERFORMANCE OF AN APPLICATION.HERE "N" IS REPRESENT THE
SIZE OF CACHE FILE.MINIMUM SIZE OF CACHE IS 2KB AND
MAXIMUM SIZE OF CACHE IS 20KB.
NOTE:
- TO WORK WITH SEQUENCE OBJECT WE SHOULD USE THE
FOLLOWING TWO PSEUDO COLUMNS ARE "NEXTVAL" AND
"CURRVAL".
NEXTVAL:
- IT IS USED TO GENERATE SEQUENCE NUMBERS ON A
PARTICULAR COLUMN.
SYNTAX:
SELECT <SEQUENCE NAME>. <NEXTVAL> FROM DUAL;
CURRVAL:
- IT IS USED TO SHOW THE CURRENT VALUE OF THE SEQUENCE.
SYNTAX:
SELECT <SEQUENCE NAME>. <CURRVAL> FROM DUAL;
EX1:
STEP1:
SQL> CREATE SEQUENCE SQ1
START WITH 1
MINVALUE 1
INCREMENT BY 1
MAXVALUE 3;
SEQUENCE CREATED.
STEP2:
SQL> CREATE TABLE TEST1(SNO INT, NAME VARCHAR2(10));
TABLE CREATED.
TESTING:
=========
SQL> INSERT INTO TEST1 VALUES (SQ1.NEXTVAL,'&NAME');
ENTER VALUE FOR NAME: A
/
ENTER VALUE FOR NAME: B
/
ENTER VALUE FOR NAME: C
/
ENTER VALUE FOR NAME: D
ERROR AT LINE 1:
ORA-08004: SEQUENCE SQ1.NEXTVAL EXCEEDS MAXVALUE AND
CANNOT BE INSTANTIATED.
ALTERING A SEQUENCE:
SYNTAX:
ALTER SEQUENCE <SEQUENCE NAME> <PARAMETER NAME> N;
EX:
SQL> ALTER SEQUENCE SQ1 MAXVALUE 5;
SEQUENCE ALTERED.
TESTING:
SQL> INSERT INTO TEST1 VALUES (SQ1.NEXTVAL,'&NAME');
ENTER VALUE FOR NAME: D
/
ENTER VALUE FOR NAME: E
OUTPUT:
SQL> SELECT * FROM TEST1;
SNO NAME
------- ----------
1 A
2 B
3 C
4 D
5 E
TESTING:
SQL> INSERT INTO TEST2 VALUES (SQ2.NEXTVAL,'&NAME');
ENTER VALUE FOR NAME: A
/
ENTER VALUE FOR NAME: B
/
ENTER VALUE FOR NAME: C
/
.....................................
.....................................
OUTPUT:
SQL> SELECT * FROM TEST2;
SNO NAME
------- ----------
1 A
2 B
3 C
1 D
2 E
3 F
EX3:
SQL> CREATE SEQUENCE SQ3
START WITH 3
MINVALUE 1
INCREMENT BY 1
MAXVALUE
5 CYCLE
CACHE 2;
SEQUENCE CREATED.
TESTING:
SQL> INSERT INTO TEST3 VALUES (SQ3.NEXTVAL,'&NAME');
ENTER VALUE FOR NAME: A
/
......................................
......................................
OUTPUT:
SQL> SELECT * FROM TEST3;
SNO NAME
-------------- ----------
3 A
4 B
5 C
1 M
2 N
3 O
4 P
5 Q
EX:
SQL> DESC USER_SEQUENCES;
SQL> SELECT SEQUENCE_NAME FROM USER_SEQUENCES;
EX:
SQL> DROP SEQUENCE SQ1;
LOCKS: IT IS A MECHANISM WHICH IS USED TO PREVENT
UNAUTHORIZED ACCESS FOR OUR RESOURCE. ALL DATABASE
SYSTEMS ARE HAVING TWO TYPES OF LOCKS. THOSE ARE,
USER - 2:
WHEN WE ARE LOCKING SET OF ROWS FROM TABLE THEN USE “FOR
UPDATE” CLAUSE IN SELECT QUERY.
USER - 1:
SQL> CONN SYSTEM / MANAGER;
USER - 2:
SQL> CONN SCOTT / TIGER;
i) SHARE LOCK
ii) EXCLUSIVE LOCK
SHARE LOCK: SHARED LOCK EXISTS WHEN TWO TRANSACTIONS
(USERS) ARE GRANTED READ ACCESS. ONE TRANSACTION GETS
SHARED LOCK ON DATA AND WHEN THE SECOND TRANSACTION
REQUESTS THE SAME DATA IT IS ALSO GIVEN A SHARED LOCK.
BOTH TRANSACTIONS ARE READ-ONLY MODE. HERE AT A TIME NO.
OF USERS ARE LOCKS THE RESOURCES.
UPDATING DATA NOT ALLOWED UNTIL THE SHARED LOCK
IS RELEASED BY USING COMMIT/ROLLBACK.
SYNTAX:
USER - 2:
1.TABLE SCAN:
- IT IS A DEFAULT SCANNING MECHANISM FOR RETRIEVING
DATA FROM TABLE.IN THIS MECHANISM ORACLE SERVER IS
SCANNING ENTIRE TABLE (TOP - BOTTOM)
EX:
SQL> SELECT * FROM EMP WHERE SAL=3000;
SOL:
SAL
--------
800
1600
1250
2975
1250
2850
2450
3000 (IN THIS TABLE SCAN WE ARE COMPARING WHERE
CONDITION 14 TIMES)
5000
1500
1100
950
3000
1300
2) INDEX SCAN:
- IN INDEX SCAN MECHANISM ORACLE SERVER SCANNING
ONLY INDEXED COLUMN FROM A TABLE. IN THIS MECHANISM WE
AGAIN FOLLOW THE FOLLWOING TWO METHODS,
I) AUTOMATICALLY / IMPLICITLY:
- WHENEVER WE ARE CREATING A TABLE ALONG WITH
"PRIMARY KEY " (OR) "UNIQUE" KEY CONSTRAINT THEN
INTERNALLY SYSTEM IS CREATING AN INDEX OBJECT ON THAT
PARTICULAR COLUMN AUTOMATICALLY.
EX:
SQL> CREATE TABLE TEST1(EID INT PRIMARY KEY, ENAME
VARCHAR2(10));
SQL> CREATE TABLE TEST2(SNO INT UNIQUE, NAME
VARCHAR2(10));
NOTE:
- IF WE WANT TO VIEW INDEX NAME ALONG WITH COLUMN
NAME OF A PARTICULAR TABLE THEN WE USE
"USER_IND_COLUMNS" DATA DICTIONARY.
EX:
SQL> DESC USER_IND_COLUMNS;
SQL> SELECT COLUMN_NAME, INDEX_NAME FROM
USER_IND_COLUMNS WHERE TABLE_NAME='TEST1';
COLUMN_NAME INDEX_NAME
------------------------- ----------------------
EID SYS_C005501
COLUMN_NAME INDEX_NAME
------------------------- ----------------------
SNO SYS_C005502
TYPES OF INDEXES:
1. B - TREE INDEX (DEFAULT INDEX)
- SIMPLE INDEX
- COMPOSITE INDEX
- UNIQUE INDEX
- FUNCTIONAL BASED INDEX
2. BITMAP INDEX
SIMPLE INDEX:
- WHEN WE CREATED AN INDEX ON A SINGLE COLUMN THEN
WE CALLED AS SIMPLE INDEX.
SYNTAX:
CREATE INDEX <INDEX NAME> ON <TN> (<COLUMN NAME>);
EX:
SQL> CREATE INDEX SIND ON EMP(SAL);
INDEX CREATED.
EX:
SQL> SELECT * FROM EMP WHERE SAL=3000;
SOL:
EX:
SQL> SELECT * FROM EMP WHERE DEPTNO=10;(INDEX SCAN)
SQL> SELECT * FROM EMP WHERE DEPTNO=10 AND
JOB='CLERK';(INDEX SCAN)
SQL> SELECT * FROM EMP WHERE JOB='CLERK';(TABLE SCAN)
UNIQUE INDEX:
- WHEN WE CREATE AN INDEX BASED ON "UNIQUE
CONSTRAINT" COLUMN IS CALLED UNIQUE INDEX.UNIQUE INDEX
DOES NOT ALLOW DUPLICATE VALUES.
SYNTAX:
CREATE UINQUE INDEX <INDEX NAME> ON <TN> (<COLUMN
NAME>);
EX:
SQL> CREATE UNIQUE INDEX UIND ON DEPT(DNAME);
INDEX CREATED.
TESTING:
SQL> INSERT INTO DEPT VALUES (50,'SALES','HYD')
ERROR AT LINE 1:
ORA-00001: UNIQUE CONSTRAINT (SCOTT.UIND) VIOLATED.
NOTE: PRIMARY KEY COLUMNS AND UNIQUE COLUMNS ARE
AUTOMATICALLY INDEXED BY ORACLE.
FUNCTIONAL BASED INDEX:
- WHEN WE CREATE AN INDEX BASED ON FUNCTION THEN
WE CALLED AS FUNCTIONAL BASED INDEX.
SYNTAX:
CREATE INDEX <INDEX NAME> ON <TN>(<FUNCTION
NAME>(COLUMN NAME));
E
SQL> CREATE INDEX IND4 ON EMP(UPPER(ENAME));
INDEX CREATED.
SQL> SELECT * FROM EMP WHERE UPPER(ENAME)='SCOTT';
(INDEX SCAN)
2. BITMAP INDEX:
- BITMAP INDEX IS CREATED ON DISTINCT VALUES OF A
PARTICULAR COLUMN.GENERALLY BITMAP INDEXES ARE
CREATED ON LOW CARDINALITY OF COLUMNS.
- WHEN WE CREATE BITMAP INDEX INTERNALLY ORACLE
SERVER IS PREPARING BITMAP INDEXED TABLE WITH BIT
NUMBERS ARE 1 AND 0. HERE 1 IS REPRESENT CONDITION IS
TRUE WHERE AS 0 IS REPRESENT CONDITION IS FALSE.
CARDINALITY:
- IT REFERES TO THE UINQUENESS OF DATA VALUES
CONTAINE IN PARTICULAR COLUMN OF TABLE.
EX:
CARDINALITY OF EMPNO = 14
--------
14
CARDINALITY OF EMPNO IS "1" ----(CREATING BTREE INDEX)
E
CARDINALITY OF JOB = 5
--------
14
SYNTAX:
CREATE BITMAP INDEX <INDEX NAME> ON <TN>(<COLUMN
NAME>);
EX:
CREATE BITMAP INDEX BITIND ON EMP(JOB);
EX:
SELECT * FROM EMP WHERE JOB='MANAGER';
JOB 1 2 3 4 5 6 7 8 9 10 11 12 13 14
===========================================
=============
CLERK 1 0 0 0 0 0 0 0 0 0 1 1 0 1
------------------------------------------------------------------------------
---------------------------------
SALESMAN 0 1 1 0 1 0 0 0 0 1 0 0 0 0
------------------------------------------------------------------------------
---------------------------------
MANAGER 0 0 0 1 0 1 1 0 0 0 0 0 0 0
------------------------------------------------------------------------------
---------------------------------
ANALYST 0 0 0 0 0 0 0 1 0 0 0 0 1 0
------------------------------------------------------------------------------
---------------------------------
PRESIDENT 0 0 0 0 0 0 0 0 1 0 0 0 0 0
===========================================
NOTE: HERE "1" IS REPRESENTED WITH ROWID OF A
PARTICULAR ROW IN A TABLE.
NOTE:
- IF WE WANT TO VIEW INDEX NAME ALONG WITH INDEX
TYPE THEN WE USE "USER_INDEXES" DATADICTIONARY.
EX:
SQL> DESC USER_INDEXES;
SQL> SELECT INDEX_NAME, INDEX_TYPE FROM USER_INDEXES
WHERE TABLE_NAME='EMP';
INDEX_NAME INDEX_TYPE
----------------- ---------------------
SIND NORMAL(B-TREE)
BITIND BITMAP
FIND FUNCTION-BASED NORMAL(B-TREE)
UIND NORMAL(B-TREE)
CIND NORMAL(B-TREE)
HOW TO DROP AN INDEX:
SQL> DROP INDEX <INDEX NAME>;
EX:
SQL> DROP INDEX SIND;
SQL> DROP INDEX BITIND;
CLUSTER:
> CLUSTER IS A DB OBJECT WHICH CONTAIN GROUP OF TABLES
TOGETHER AND ALSO IT SHARES SAME DATABLOCK.
> GENERALLY, CLUSTER ARE USED TO IMPROVE PERFORMANCE
OF THE JOINS AND ALSO CLUSTERS ARE CREATED BY DBA ONLY.
> CLUSTER TABLE MUST HAVE A COMMON COLUMN NAME.THIS
COMMON COLUMN IS ALSO CALLED AS CLUSTER
KEY.GENERALLY CLUSTER ARE CREATED AT THE TIME OF TABLE
CREATION.
EX:
SQL> CREATE CLUSTER EMP_DEPT (DEPTNO INT);
CLUSTER CREATED.
EX:
SQL> CREATE INDEX ABC ON CLUSTER EMP_DEPT;
INDEX CREATED.
TABLE_NAME
------------------------------
DEPT1
EMP1
ERROR AT LINE 1:
ORA-00951: CLUSTER NOT EMPTY
TO UPDATE:
SQL> UPDATE STUDENTS S SET S.COURSE.FEE=2000 WHERE
S.SID=101;
TO DELETE:
SQL> DELETE FROM STUDENTS S WHERE S.COURSE.CID=1022;
2. VARRAY:
IT ALLOWS GROUP OF VALUES /ELEMENTS OF SAME
DATATYPES.VARRAY SHOULD DECLARE WITH SIZE.
SYNTAX:
CREATE TYPE <TYPE NAME> IS VARRAY(SIZE) OF
DATATYPE[SIZE];
/
EX:
CREATE TYPE MBNO_ARRAY1 IS VARRAY (3) OF NUMBER (10);
/
TESTING:
SQL> CREATE TABLE EMPLOYEE (EMPNO NUMBER (4), MBNO
MBNO_ARRAY1);
TABLE CREATED.
SQL> INSERT INTO EMPLOYEE VALUES (1021,
MBNO_ARRAY1(9703542749,8502045789));
SQL> INSERT INTO EMPLOYEE VALUES (1022,
MBNO_ARRAY1(9632587412,8523691478,7412356896));
3.NESTED TABLE:
> A TABLE WITHIN ANOTHER TABLE IS CALLED AS NESTED TABLE.
> NESTED TABLE ALSO ALLOW GROUP OF VALUES /ELEMENTS OF
DIFF. DATATYPES.
> NESTED TABLE IS NOT DECLARE WITH SIZE.
STEP2:
CREATE TYPE ADDR_ARRAY AS TABLE OF ADDR_TYPE;
/
STEP3:
CREATE TABLE CUSTOMER (CID NUMBER (4), CNAME
VARCHAR2(10), CADDRESS ADDR_ARRAY) NESTED TABLE
CADDRESS STORE AS CUST_ADDR;
TESTING:
SQL> INSERT INTO CUSTOMER VALUES (1,'SAI’, ADDR_ARRAY
(ADDR_TYPE (1122,'GANDHI','HYD')));
SQL> INSERT INTO CUSTOMER VALUES (2,'WARD’, ADDR_ARRAY
(ADDR_TYPE (1123,'ASHOK','CHE'), ADDR_TYPE
(1124,'VASATI','MUM')));
SYNTAX:
SELECT / UPDATE / DELETE / INSERT (SELECT <NESTED TABLE
TYPE COLUMN NAME> FROM <TN>);
EX:
SQL> SELECT * FROM TABLE (SELECT CADDRESS FROM CUSTOMER
WHERE CID=1);
SQL> UPDATE TABLE (SELECT CADDRESS FROM
CUSTOMER WHERE CID=2) SET HNO=1024 WHERE
HNO=1124;
SQL> DELETE FROM TABLE (SELECT CADDRESS FROM
CUSTOMER WHERE CID=2) WHERE CITY='MUM';
EX:
DROP TYPE MBNO_ARRAY1 FORCE;
NORMALIZATION: Normalization is a technique of
organizing the data into multiple tables. Normalization process
automatically eliminates data redundancy (repetition) and also
avoiding Insertion, Update and Deletion problems.
STUDENT DETAILS
Deletion problem:
In our Student Details table, two different information’s are
kept together, Student information and Branch information.
Hence, at the end of the academic year, if student records are
deleted, we will also lose the branch information. This is called
as Deletion problem.
HOW NORMALIZATION WILL SOLVE ALL
PROBLEMS:
STUDENT DETAILS
STUDENT DETAILS
A X, Y
B W, X
C Y
D Z
2. A COLUMN SHOULD CONTAIN VALUES THAT ARE SAME
DATATYPE.
SAI 01-JAN-92
JONES 24-APR-84
18-DEC-85 MILLER
1 SAI KUMAR
2 JONES ROY
4 MILLER JOY
3 JAMES WARTON
103 ALLEN C
(PK)
EX: A B C D
EX:
EX: A B C D
SUBJECT_ID SUBJECT_NAME
1 ORACLE
2 JAVA
3 PYTHON
NOTE:
And our Score table is now in the second normal form, with no
partial dependency.
101 1 70
101 2 75
102 1 80
103 3 68
EX: A B C D
with exam name and total marks added to our score table, it
saves more data now. primary key for our score table is a
composite key, which means it's made up of two attributes or
columns → student
+subject
our new column exam name depends on both student and subject.
for example, a mechanical engineering student will have
workshop exam but a computer science student won't. and for
some subjects you have practical exams and for some you don't.
so, we can say that exam name is dependent on both student id
and subject id.
well, the column total marks depend on exam name as with exam
type the total score changes. for example, practical is less marks
while theory exams are having more marks.
but exam name is just another column in the score table. it is not a
primary key and total marks depends on it.
this is transitive dependency. when a non-prime attribute
depends on other non-prime attributes rather than depending
upon the prime attributes or primary key.
How to remove Transitive Dependency: again, the solution
is very simple. take out the column’s exam name and total
marks from score table and put them in an exam table and
use the exam_id wherever required.
Score Table: In 3rd Normal Form
Exam table
1 Workshop 200
2 Mains 70
3 Practical’s 30
(OR)
stid
mailid
reg_number
STUDENT_ID PROFESSOR_ID
101 1
101 2
Professor Table
(COMPOSITE PRIMARY KEY)
1 P. Java Java
2 P. Cpp C++
1 ORACLE Cricket
1 JAVA Reading
1 C# Hockey
in the table above, there is no relationship between the
columns course and hobby. they are independent of each other.so
there is multi-value dependency, which leads to un-necessary
repetition of data.
STUDENT_ID Hobby
1 Cricket
1 Reading
1 Hockey
STUDENT_ID Course
1 ORACLE
1 JAVA
1 C#
Fifth Normal Form (5NF):
If a table having multi valued attributes and also that table cannot d
Generally, in 4NF resource table some attributes are not logically related wher
Fifth normal form is also called as project joined normal
form because if possible decomposing table into number of tables
and also whenever we are joining those tables then the result
records must be available in resource table.
PL/SQL
INTRODUCTION TO PL/SQL:
PL/SQL STANDS FOR PROCEDURAL LANGUAGE WHICH IS AN
EXTENSION OF SQL.PL/SQL WAS INTRODUCED IN ORACLE 6.0
VERSION.
SQL IS A NON-PROCEDURAL LANGUAGE WHEREAS PL/SQL IS
A PROCEDURAL LANGUAGE.
SQL SUPPORTS A SINGLE LINE STATEMENT (QUERY)
EXECUTION PROCESS WHEREAS PL/SQL SUPPORTS MULTI LINES
STATEMENTS(PROGRAM) EXECUTION PROCESS.
IN SQL EVERY QUERY STATEMENT IS COMPILING AND
EXECUTING INDIVIDUALLY.SO THAT NO. OF COMPILATIONS ARE
INCRESED AND REDUCE PERFORMANCE OF DATABASE.
FEATURES OF PL/SQL:
1. TO IMPROVES PERFORMANCE.
2. SUPPORTING CONDITIONAL & LOOPING STATEMENTS.
3. SUPPORTING REUSABILITY.
4. PROVIDING SECURITY BECAUSE ALL PROGRAMS ARE SAVED
IN DATABASE AND AUTHORIZED USER CAN ONLY ACCESS THE
PROGRAMS.
5. SUPPORTING PORTABILITY I.E PL/SQL PROGRAMS CAN BE
MOVED FROM ONE
PLATFORM TO ANOTHER PLATFORM WITHOUT ANY CHANGES.
6. SUPPORTING EXCEPTION HANDLING MECHANISM.
7. SUPPORTING MODULAR PROGRAMMING I.E IN A PL/SQL A BIG
PROGRAM CAN BE DIVIDED INTO SMALL MODULES WHICH ARE
CALLED AS STORED PROCEDURE AND
STORED FUNCTIONS.
PL/SQL ARCHITECTURE:
PL/SQL IS BLOCK STRUCTURE PROGRAMMING
LANGUAGE.WHICH IS HAVING THE FOLLOWING TWO ENGINES
THOSE ARE
1. SQL ENGINE
2. PL/SQL ENGINE
WHAT IS BLOCK:
A BLOCK IS A SET OF STATEMENTS WHICH ARE COMPILE &
EXECUTED BY ORACLE AS A SINGLE UNIT. PL/SQL SUPPORTING
THE FOLLOWING TWO TYPES OF BLOCKS THOSE ARE,
1. ANONYMOUS BLOCK
2. SUB BLOCK
DIFF. B/W ANONYMOUS & SUB BLOCK:
ANONYMOUS BLOCKS:
THESE ARE UNNAMED BLOCKS IN PL/SQL.WHICH CONTAINS
THREE MORE BLOCKS THOSE ARE,
I) DECLARATION BLOCK
II) EXECUTION BLOCK
III) EXCEPTION BLOCK
I) DECLARATION BLOCK:
> THIS BLOCK STARTS WITH " DECLARE " STATEMENT.
> DECLARING VARIABLES, CURSORS, USER DEFINE
EXCEPTIONS.
> IT IS OPTIONAL BLOCK.
II) EXECUTION BLOCK:
> THIS BLOCK STARTS WITH " BEGIN " STATEMENT & ENDS
WITH "END” STATEMENT.
> IMPLEMENTING SQL STATEMENTS(SQL) & LOGICAL CODE
OF A PROGRAM (PL/SQL).
> IT IS MANDATORY BLOCK.
III) EXCEPTION BLOCK:
> THIS BLOCK STARTS WITH "EXCEPTION" STATEMENT.
> HANDLING EXCEPTIONS.
> IT IS An OPTIONAL BLOCK.
VARIABLES IN PL/SQL:
STEP1: DECLARING VARIABLES:
SYNTAX:
DECLARE
<VARIABLE NAME> <DT>[SIZE];
EX:
DECLARE
A NUMBER (10) (OR) A INT;
B VARCHAR2(10);
A: = 1021;
B: = 'SAI';
HERE,
:= - ASSIGNMENT OPERATOR IN PL/SQL
= - COMPARISION OPERATOS IN PL/SQL
EX:
DBMS_OUTPUT.PUT_LINE(A);
DBMS_OUTPUT.PUT_LINE(B); DBMS_OUTPUT.PUT_LINE
('WELCOME TO PL/SQL');
EX1:
TO PRINT "WELCOME TO PL/SQL" STATEMENT.
SOL:
SQL> BEGIN
DBMS_OUTPUT.PUT_LINE ('WELCOME TO PL/SQL');
END;
/
SYNTAX:
SET SERVEROUTPUT OFF / ON;
HERE,
OFF: IT IS DEFAULT.OUTPUT IS NOT DISPLAY
ON: OUTPUT IS DISPLAY
EX2:
TO PRINT VARIABLES VALUES?
SOL:
SQL> DECLARE
X NUMBER (10);
Y NUMBER (10);
BEGIN
X: =100;
Y: =200;
DBMS_OUTPUT.PUT_LINE ('VARIABLES VALUES ARE:'||X||','||Y);
END;
/
VARIABLES VALUES ARE:100,200
EX3:
TO PRINT SUM OF TWO NUMBERS AT RUNTIME?
SOL:
DECLARE
X NUMBER (2);
Y NUMBER (2);
Z NUMBER (10);
BEGIN
X: =&X;
Y: =&Y;
Z: =X+Y;
DBMS_OUTPUT.PUT_LINE(Z);
END;
/
OUTPUT:
ENTER VALUE FOR X: 10
OLD 6: X: =&X;
NEW 6: X: =10;
ENTER VALUE FOR Y: 20
OLD 7: Y: =&Y;
NEW 7: Y: =20;
30
VERIFY:
ON = DISPLAY OLD, NEW BIND VARIABELE STATEMENTS
OFF = DOESNOT DISPLAY OLD, NEW BIND VARIABLES
STATEEMTNS
SYNTAX:
SET VERIFY ON / OFF
EX:
SQL> SET VERIFY OFF;
SQL> /
ENTER VALUE FOR X: 10
ENTER VALUE FOR Y: 20
30
SYNTAX:
SELECT <COLUMN NAME1>, <COLUMN NAME2>,...........INTO
<VARIABLE NAME1>, <VARIABLE NAME2>……………. FROM <TN>
[ WHERE <CONDITION>];
EX1:
WA PL/SQL PRG. TO DISPLAY ENAME, SALARY DETAILS FROM EMP
TABLE AS PER THE GIVEN EMPNO BY USING SELECT.......INTO
STATEMENT?
SOL:
DECLARE
V_ENAME VARCHAR2(10);
V_SAL NUMBER (10);
BEGIN
SELECT ENAME, SAL INTO V_ENAME, V_SAL FROM EMP WHERE
EMPNO=&EMPNO;
DBMS_OUTPUT.PUT_LINE(V_ENAME||','||V_SAL); END;
/
OUTPUT:
ENTER VALUE FOR EMPNO: 7788
SCOTT,3000
EX:
WA PL/SQL PRG. TO FETCH MAX.SALARY OF EMP TABLE BY USING
"SELECT INTO" STATEMENT?
SOL:
DECLARE
V_MAXSAL NUMBER (10);
BEGIN
SELECT MAX(SAL) INTO V_MAXSAL FROM EMP;
DBMS_OUTPUT.PUT_LINE(V_MAXSAL);
END;
/
OUTPUT:
5000
VARIABLES ATTRIBUTES (OR) ANCHOR NOTATIONS:
VARIABLES ATTRIBUTES ARE USED IN PLACE OF DATATYPES
AT VARIABLE DECLARATION.
WHENEVER WE ARE USING VARIABLES ATTRIBUTES
INTERNALLY ORACLE SERVER IS ALLOCATE SOME MEMORY FOR
THESE VARIABLES ATTRIBUTES FOR STORING THE
CORRESPONDING VARIABLE COLUMN DATATYPE WHICH WAS
ASSIGNED AT THE TIME OF TABLE CREATION.
VARIABLES ATTRIBUTES ARE ALSO CALLED AS "ANCHOR
NOTATIONS".
THE ADVANTAGE OF VARIABLES ATTRIBUTES ARE
WHENEVER WE WANT TO CHANGE
A PARTICULAR COLUMN DATATYPE IN A TABLE THEN THE
CORRESPONDING COLUMN VARIABLE DATATYPE ALSO CHANGED
IN VARIABLE ATTRIBUTE MEMORY AUTOMATICALLY.
PL/SQL SUPPORTS THE FOLLOWING TWO TYPE VARIABLES
ATTRIBUTES ARE,
1. COLUMN LEVEL ATTRIBUTES
2. ROW LEVEL ATTRIBUTES
SYNTAX:
<VARIABLE NAME> <TN>. <COLUMN NAME>%TYPE;
EX:
V_ENAME EMP.ENAME%TYPE;
V_SAL EMP.SAL%TYPE;
PROGRAM1:
DECLARE
V_ENAME EMP.ENAME%TYPE;
V_SAL EMP.SAL%TYPE; BEGIN
SELECT ENAME, SAL INTO V_ENAME, V_SAL FROM EMP WHERE
EMPNO=&EMPNO;
DBMS_OUTPUT.PUT_LINE(V_ENAME||','||V_SAL); END;
/
OUTPUT:
ENTER VALUE FOR EMPNO: 7788
SCOTT,3000
SYNTAX:
<VARIABLE NAME> <TABLE NAME>%ROWTYPE;
EX: I EMP%ROWTYPE;
PROGRAM2:
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT ENAME, SAL INTO I. ENAME, I.SAL FROM EMP WHERE
EMPNO=&EMPNO;
DBMS_OUTPUT.PUT_LINE (I. ENAME||','||I.SAL);
END;
/
(OR)
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP WHERE EMPNO=&EMPNO;
DBMS_OUTPUT.PUT_LINE (I. ENAME||','||I.SAL||','||I.DEPTNO);
END;
/
CONTROL STRUCTURES:
- USED TO CONTROL FLOW OF THE PROGRAM.
- THERE ARE THREE TYPES OF CONTROL STRUCTURES.
I. CONDITIONAL CONTROL STRUCTURES
II. BRANCHING CONTROL STRUCTURES
III. ITERATION CONTROL STRUCTURES
I. CONDITIONAL CONTROL STRUCTURES:
I. SIMPLE IF: IT CONTAINS ONLY TRUE BLOCK.
SYNTAX:
IF <CONDITION> THEN
<EXEC-STATEMENTS>; -- TRUE BLOCK
END IF;
II. IF. ELSE: IT CONTAINS BOTH TRUE BLOCK & FALSE BLOCK.
SYNTAX:
IF <CONDITION> THEN
<EXEC-STATEMENTS>; -- TRUE BLOCK
ELSE
<EXEC-STATEMENTS>; -- FALSE BLOCK
END IF;
ELSE
<EXEC-STATEMENTS>;
END IF;
SYNTAX:
LOOP
<EXEC-STATEMENTS>;
END LOOP;
SYNTAX:
FOR <INDEX_VARIABLE> IN <START_VALUE>..<END_VALUE>
LOOP
<EXEC-STATEMENTS>;
END LOOP;
CURSORS:
CURSOR IS A TEMP.MEMORY / A PRIVATE SQL AREA(PSA) /
A WORK SPACE. CURSOR ARE TWO TYPES.THOSE ARE:
I) EXPLICIT CURSOR (USER DEFINE CURSOR)
II) IMPLICIT CURSOR (SYSTEM DEFINE CURSOR)
I) EXPLICIT CURSOR:
THESE CURSOR ARE CREATING BY USER FOR HOLDING
MULTIPLE ROWS BUT WE CAN ACCESS ONLY ONE ROW AT TIME.
(ONE BY ONE / ROW BY ROW MANNER).
IF WE WANT TO CREATE AN EXPLICIT CURSOR, WE NEED
FOLLOW THE FOLLOWING FOUR STEPS.THOSE ARE
1) DECLARING A CURSOR
2) OPEN A CURSOR
3) FETCH ROWS FROM A CURSOR
4) CLOSE A CURSOR
SYNTAX:
DECLARE CURSOR <CURSORNAME> IS < SELECT STATEMENT>;
SYNTAX:
OPEN < CURSORNAME>;
3) FETCHING DATA FROM THE CURSOR: IN THIS PROCESS WE
ACCESS ROW BY ROW FROM CURSOR.
SYNTAX:
FETCH <CURSORNAME> INTO <VARIABLES>;
SYNTAX:
CLOSE <CURSORNAME>;
SYNTAX:
<CURSOR_NAME>%<ATTRIBUTE>;
A. %ISOPEN:
IT RETURNS TRUE, WHEN THE CURSOR OPENS SUCCESSFULLY.
B. %FOUND:
IT RETURNS TRUE, WHEN THE CURSOR CONTAINS DATA.
C. %NOTFOUND:
IT RETURNS TRUE, WHEN THE CURSOR DOESN'T FIND ANY DATA.
D.%ROWCOUNT:
IT RETURS NO. OF FETCH STATEMENTS EXECUTED.RETURN TYPE
IS NUMBER.
EX1:
WA CURSOR PROGRAM TO FETCH A SINGLE ROW FROM EMP
TABLE?
SOL:
DECLARE CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
V_ENAME VARCHAR2(10);
V_SAL NUMBER (10);
BEGIN
OPEN C1;
FETCH C1 INTO V_ENAME, V_SAL;
DBMS_OUTPUT.PUT_LINE(V_ENAME||','||V_SAL); CLOSE
C1;
END;
/
OUTPUT:
SMITH,800
OUTPUT:
SMITH,800
ALLEN,1600
WARD,1250
..................
...................
EX3:
WA CURSOR PROGRAM TO FETCH TOP FIVE HIGHEST SALARIES
EMPLOYEE ROWS FROM EMP TABLE?
SOL:
DECLARE CURSOR C1 IS SELECT ENAME, SAL FROM EMP ORDER BY
SAL DESC;
V_ENAME VARCHAR2(10);
V_SAL NUMBER (10);
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO V_ENAME, V_SAL;
EXIT WHEN C1%ROWCOUNT>5;
DBMS_OUTPUT.PUT_LINE(V_ENAME||','||V_SAL); END
LOOP;
CLOSE C1;
END;
/
OUTPUT:
KING,5000
FORD,3000
SCOTT,3000
JONES,2975
BLAKE,2850
EX4:
WA CURSOR PROGRM TO FETCH EVEN POSITION ROWS FROM EMP
TABLE?
SOL:
DECLARE CURSOR C1 IS SELECT EMPNO, ENAME FROM
EMP; V_EMPNO NUMBER (10);
V_ENAME VARCHAR2(10);
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO V_EMPNO, V_ENAME;
EXIT WHEN C1%NOTFOUND;
IF MOD(C1%ROWCOUNT,2) =0 THEN
DBMS_OUTPUT.PUT_LINE(V_EMPNO||','||V_ENAME);
END IF;
END LOOP;
CLOSE C1;
END;
/
OUTPUT:
7499, ALLEN
7566, JONES
7698, BLAKE
7788, SCOTT
7844, TURNER
EX5: WA CURSOR PROGRAM TO FETCH 9TH POSITION ROW FROM
EMP TABLE?
SOL:
DECLARE CURSOR C1 IS SELECT ENAME FROM EMP;
V_ENAME VARCHAR2(10);
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO V_ENAME;
EXIT WHEN C1%NOTFOUND;
IF C1%ROWCOUNT=9 THEN
DBMS_OUTPUT.PUT_LINE(V_ENAME);
END IF;
END LOOP;
CLOSE C1;
END;
/
OUTPUT:
KING
PARAMETERIZED CURSORS:
- WHENEVER WE ARE PASSING PARAMETERS TO THE
CURSOR AT THE TIME DECLARATION IS CALLED AS
PARAMETERIZED CURSOR. THESE PARAMETERIZED CURSOR
WANT TO DECLARE THEN WE FOLLOW THE FOLLOWING TWO
STEPS ARE
EX1:
WA CURSOR PROGRAM TO ACCEPT DEPTNO AS A PARAMETER
AND DISPLAY THE NO. OF EMPLOYEE WORKING IN THE GIVEN
DEPTNO FROM EMP TABLE?
SOL:
DECLARE CURSOR C1(P_DEPTNO NUMBER) IS SELECT ENAME,
DEPTNO FROM EMP
WHERE DEPTNO=P_DEPTNO;
V_ENAME VARCHAR2(10);
V_DEPTNO NUMBER (10);
BEGIN
OPEN C1(&P_DEPTNO);
LOOP
FETCH C1 INTO V_ENAME, V_DEPTNO;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(V_ENAME||','||V_DEPTNO);
END LOOP;
CLOSE C1;
END;
/
OUTPUT:
ENTER VALUE FOR P_DEPTNO: 10
MILLER,10
CLARK,10
KING,10
SOL:
DECLARE CURSOR C1(P_EMPNO NUMBER) IS SELECT ENAME FROM
EMP
WHERE EMPNO=P_EMPNO;
V_ENAME VARCHAR2(10);
BEGIN
OPEN C1(&P_EMPNO);
FETCH C1 INTO V_ENAME;
IF C1%FOUND THEN
DBMS_OUTPUT.PUT_LINE ('EMPLOYEE EXISTS, NAME IS: -
'||V_ENAME);
ELSE
DBMS_OUTPUT.PUT_LINE ('EMPLOYEE NOT EXISTS');
END IF;
CLOSE C1;
END;
/
OUTPUT:
ENTER VALUE FOR P_EMPNO: 7788
EMPLOYEE EXISTS, NAME IS: -SCOTT
IMPLICIT CURSOR:
- THESE CURSOR ARE DECLARING BY ORACLE SERVER BY
DEFAULT.ORACLE DECLARE THESE CURSOR AFTER EXECUTION OF
DML COMMAND (INSERT / UPDATE / DELETE).
- IMPLICIT CURSOR TELLING US THE STATUS OF LAST DML
COMMAND WHETHER SUCCESSFULL OR NOT.
1. %ISOPEN:
- IT RETURNS TRUE THEN CURSOR SUCCESSFUL OPEN
OTHERWISE RETURNS FALSE.
2. %NOTFOUND:
- IT RETURNS TRUE THEN LAST DML COMMAND IS FAIL
OTHERWISE RETURNS FALSE.
3. %FOUND:
- IT RETRUNS TRUE THEN LAST DML COMMAND IS
SUCCESSFULLY EXECUTED
OTHERWISE RETURNS FALSE.
4.%ROWCOUNT:
- IT RETURNS NO. OF ROWS AFFECTED BY LAST DML
COMMAND.
EX:
DECLAR
V_EMPNO NUMBER (10);
BEGIN
V_EMPNO: =&V_EMPNO;
DELETE FROM EMP WHERE EMPNO=V_EMPNO;
IF SQL%FOUND THEN
DBMS_OUTPUT.PUT_LINE ('RECORD IS DELETED');
ELSE
DBMS_OUTPUT.PUT_LINE ('RECORD IS NOT EXISTS');
END IF;
END;
/
OUTPUT:
ENTER VALUE FOR V_EMPNO: 7788
RECORD IS DELETED
REF. CURSORS:
- WHEN WE ASSIGN "SELECT STATEMENT" AT THE TIME OF
OPENING CURSOR IS CALLED AS "REF.CURSOR".
- REF.CURSORS ARE TWO TYPES.THOSE ARE,
1. WEAK REF.CURSOR
2. STRONG
REF.CURSOR 1. WEAK
REF.CURSOR:
WHEN WE DECLARE REF.CURSOR WITHOUT RETURN TYPES
IS CALLED AS WEAK REF.CURSOR.
SYNTAX:
<CURSOR VARIABLE NAME> SYS_REFCURSOR; ------> (IT
IS PRE-DEFINE TYPE)
EX:
DECLAR
C1 SYS_REFCURSOR;
I EMP%ROWTYPE;
BEGIN
OPEN C1 FOR SELECT * FROM EMP WHERE DEPTNO=10;
LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE (I. EMPNO||','||I.ENAME||','||I.SAL||','||
I.DEPTNO);
END LOOP;
CLOSE C1;
END;
/
2)STRONG REF.CURSOR:
- WHEN WE DECLARE A REF. CURSOR ALONG WITH RETURN
TYPE IS CALLED AS STRONG REF.CURSOR.
<ERROR STATEMENTS….....>;
END;
1) SYSTEM/PRE-DEFINED EXCEPTION:
THESE ARE DEFINED BY ORACLE BY DEFAULT. WHENEVER
RUNTIME ERROR IS OCCURRED IN PL/SQL THEN WE USE AN
APPROPRIATE PRE-DEFINED EXCEPTION IN THE PROGRAM.
EX:
DBMS_OUTPUT.PUT_LINE(TENAME||','||TSAL);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE ('RECORD IS NOT FOUND');
END;
/
TOO_MANY_ROWS: WHEN SELECT…. INTO CLAUSE TRY TO RETURN
MORE THAN ONE VALUE OR ONE ROW THEN ORACLE SERVER
RETURNS AN ERROR.
EX:
EX:
Y: =&Y;
Z: =X/Y;
DBMS_OUTPUT.PUT_LINE ('RESULT: -'||Z);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE ('SECOND NUMBER SHOULD NOT BE
ZERO');
END;
/
INVALID CURSOR: WHEN WE ARE NOT OPENING THE CURSOR BUT
WE ARE TRY TO PERFORM OPERATIONS ON CURSOR THEN ORACLE
RETURNS AN ERROR.
EX:
DECLARE
BEGIN
CLOSE C1;
EXCEPTION
WHEN INVALID_CURSOR THEN
DECLARE
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO TEID, TENAME, TSAL, TAGE;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE (TEID||' '||TENAME||' '||TSAL||' '||TAGE);
END LOOP;
OPEN C1;
EXCEPTION
WHEN CURSOR_ALREADY_OPEN THEN
END;
X NUMBER (10);
Y NUMBER (20);
Z NUMBER (10);
BEGIN
X:=&X;
Y:=&Y;
Z:=X/Y;
DBMS_OUTPUT.PUT_LINE(Z);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLCODE);
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
OUTPUT:
ENTER VALUE FOR X:
10 ENTER VALUE FOR Y:
25
ENTER VALUE FOR X: 10
ENTER VALUE FOR Y: 0
-1476---------ERROR CODE
ORA-01476: DIVISOR IS EQUAL TO ZERO------ERROR MESSAGE
EX:
EX EXCEPTION;
EX:
RAISE EX;
SYNTAX:
<STATEMENTS>;
END;
/
EX:
WHEN EX THEN
EX:
DECLARE
X INT;
Y INT;
Z INT;
EX EXCEPTION;-----------------(1)
BEGIN
X:=&X;
Y:=&Y;
IF Y=0 THEN
RAISE EX;-------------------(2)
ELSE
Z:=X/Y;
DBMS_OUTPUT.PUT_LINE(Z); END
IF;
EXCEPTION
WHEN EX THEN---------------(3)
HERE,
NUMBER - NUMBER SHOULD BE -20001 TO -20999
MESSAGE - USER DEFINE EXCEPTION MESSAGE.
EX:
DECLARE
X INT;
Y INT;
Z INT;
EX EXCEPTION;
BEGIN
X:=&X;
Y:=&Y;
IF Y=0 THEN
RAISE EX;
ELSE
Z:=X/Y;
DBMS_OUTPUT.PUT_LINE(Z);
END IF;
EXCEPTION
WHEN EX THEN
RAISE_APPLICATION_ERROR(-20457,'SECOND NUMBER NOT BE
ZERO');
END;
SYNTAX:
PRAGMA EXCEPTION_INIT (<USER DEFINE EXCEPTION NAME>,
ERROR NUMBER)
EX:
DECLARE
X EXCEPTION;
END;
/
EXCEPTION PROPAGATION:
- EXCEPTION BLOCK HANDLES EXCEPTION WHICH WAS RAISED
IN BODY (EXECUTION BLOCK) BUT CANNOT HANDLE EXCEPTION
WHICH WILL RAISE IN DECLARATION BLOCK.
EX:
DECLARE
X VARCHAR2(3):='PQRS';
BEGIN
DBMS_OUTPUT.PUT_LINE(X);
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('INVALID STRING LENGTH');
END;
/
ERROR AT LINE 1:
BEGIN
DECLARE
X VARCHAR2(3):='PQRS';
BEGIN
DBMS_OUTPUT.PUT_LINE(X);
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('INVALID STRING LENGTH');
END;
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('STRING LENGTH IS GREATER THAN THE
SIZE OF VARIABLE X');
END;
/
OUTPUT:
STRING LENGTH IS GREATER THAN THE SIZE OF VARIABLE X.
NOTE:
- IN PL/SQL EXCEPTIONS ARE OCCURRED IN EXECUTION BLOCK,
DECLARATION BLOCK.WHENEVER EXCEPTIONS ARE OCCURRED IN
EXECUTION BLOCK THOSE EXCEPTIONS ARE HANDLED IN INNER
BLOCK WHERE AS WHEN EXCEPTIONS ARE OCCURED IN
DECLARATION BLOCK THOSE EXCEPTIONS ARE
HANDLED IN OUTER BLOCK ONLY.THIS MECHANISM IS CALLED AS
"EXCEPTION PROPAGATION".
SUB BLOCKS:
A SUB BLOCK IS A NAMED BLOCK OF CODE THAT IS
DIRECTLY SAVED ON THE DB SERVER AND IT CAN BE EXECUTED
WHEN AND WHERE IT IS REQUIRED. WE HAVE FOUR TYPES OF
SUB BLOCKS IN ORACLE.
1. STORED PROCEDURES
2. STORED FUNCTIONS
3. PACKAGES
4. TRIGGERS
STORED PROCEDURES:
A STORED PROCEDURE IS A DATABASE OBJECT WHICH
CONTAINS PRECOMPILED QUERIES. STORED PROCEDURES ARE A
BLOCK OF CODE DESIGNED TO PERFORM A TASK WHENEVER WE
CALLED AND MAY BE OR MAY NOT BE RETURN A VALUE.
[ EXCEPTION BLOCK
<EXEC-STATEMENTS>;]
END;
SYNTAX2:(ANONYMOUS BLOCK)
BEGIN
<PROCEDURE_NAME>;
END;
SYNTAX2:
EX: BEGIN
MY_PROC;
END;
EX6:
CREATE A SP TO INPUT EMPNO AND DISPLAY THAT EMPLOYEE
NAME, SAL FROM EMP TABLE?
SQL> CREATE OR REPLACE PROCEDURE SP1(P_EMPNO IN
NUMBER)
IS
V_ENAME VARCHAR2(10);
V_SAL NUMBER (10);
BEGIN
SELECT ENAME, SAL INTO V_ENAME, V_SAL FROM EMP WHERE
EMPNO=P_EMPNO;
DBMS_OUTPUT.PUT_LINE(V_ENAME||','||V_SAL);
END;
/
PROCEDURE CREATED.
RY
----------
125
EX8:
CREATE A SP TO INPUT EMPNO AS A "IN" PARAMETER AND
RETURNS THAT EMPLOYEE PROVIDENT FUND, PROFESSIONAL TAX
AT 10%,20% ON BASIC SALARY BY USING "OUT" PARAMETERS?
SQL> CREATE OR REPLACE PROCEDURE SP3(P_EMPNO IN
NUMBER, PF OUT NUMBER, PT OUT NUMBER)
IS
V_SAL NUMBER (10);
BEGIN
SELECT SAL INTO V_SAL FROM EMP WHERE EMPNO=P_EMPNO;
PF: = V_SAL*0.1;
PT: = V_SAL*0.2;
END;
/
PROCEDURE CREATED.
SQL> VAR RPF NUMBER;
SQL> VAR RPT NUMBER;
SQL> EXECUTE SP3(7788,:RPF,:RPT);
PL/SQL PROCEDURE SUCCESSFULLY COMPLETED.
SQL> PRINT RPF RPT;
EX9:
CREATE OR REPLACE PROCEDURE ADD_PROC (A IN NUMBER, B IN
NUMBER, C OUT NUMBER)
IS
BEGIN
C: =A+B;
END ADD_PROC;
OUTPUT:
VAR R NUMBER;
EXECUTE ADD_PROC (10,20,:R);
PRINT R;
EX. ON “IN OUT” PARAMETERS:
EX10:
SQL> CREATE OR REPLACE PROCEDURE SP4(X IN OUT NUMBER)
AS
BEGIN
X: = X*X;
END;
/
PROCEDURE CREATED.
SQL> EXECUTE SP4(5);
ERROR AT LINE 1:
ORA-06550: LINE 1, COLUMN 11:
PLS-00363: EXPRESSION '5' CANNOT BE USED AS AN
ASSIGNMENT TARGET
NOTE: TO OVERCOME THE ABOVE PROBLEM THEN WE FOLLOW
THE FOLLOWING 4 STEPS,
STEP1: DECLARE REFERENCED VARIABLE FOR "OUT" PARAMETERS
IN SP:
SYNTAX:
VAR[IABLE] <REF.VARIABLE NAME> <DT>[SIZE];
STEP2: ASSIGN A VALUE TO REFERENCED VARIABLE:
SYNTAX:
EXECUTE <REF.VARIABLE NAME> := <VALUE>;
SYNTAX:
CREATE OR REPLACE FUNCTION <FUNCTION_NAME>
[(ARUGMENT DATATYPE,
ARGUMENT DATATYPE,)]
RETURN <DATATYPE>
IS
BEGIN
<EXEC-STATEMENTS>;
RETURN (VALUE);
END <FUNCTION_NAME>;
/
HOW TO CALL A STORED FUNCTION:
SELECT <FNAME>(VALUES) FROM DUAL;
NOTE:
ALL FUNCTIONS ARE STORED IN USER_OBJECTS.
ALL FUNCTIONS BODIES ARE STORED IN 'USER_SOURCE' SYSTEM
TABLE.
> TO SEE THE FUNCTION BODY.
EX:
SQL> SELECT TEXT FROM USER_SOURCE WHERE
NAME='EMP_EXPE';
DROPPING FUNCTIONS:
SYNTAX:
SQL> DROP FUNCTION <FUNCTION_NAME>;
EX:
SQL> DROP FUNCTION EMP_EXPE;
PACKAGES:
> IT IS A COLLECTION OF VARIABLES, CURSORS,
PROCEDURES & FUNCTIONS ARE STORED IN ONE LOCATION.
> EASY TO SHARE THE SUBPROGRAMS IN APPLICATION S/W
TOOLS
> THEY IMPROVE PERFORMANCE WHILE ACCESSING
SUBPROGRAMS FROM CLIENT LOCATION
> THEY ARE STORED IN “USER_SOURCE” SYSTEM TABLE
> THEY SUPPORTS FUNCTION OVERLOADING,
ENCAPSULATION & DATABINDING
> IT HAS TWO PARTS
1. PACKAGE SPECIFICATION:
IT HOLDS THE DECLARATION OF VARIABLES, CURSORS
& SUBPROGRAMS.
SYNTAX:
CREATE [OR REPLACE] PACKAGE <PACKAGE NAME>
IS / AS
<DECLARE VARIABLES, CURSORS, SUB BLOCKS>;
END;
/
2. PACKAGE BODY:
IT HOLDS THE BODY OF SUBPROGRAMS.
SYNTAX:
CREATE [OR REPLACE] PACKAGE BODY <PACKAGE NAME>
IS / AS
<IMPLEMENTING SUB BLOCKS>;
END;
/
EX1:
CREATE A PACKAGE TO ENCAPSULATE / BIND MULTIPLE
PORCEDURES?
SQL> CREATE OR REPLACE PACKAGE PK1
IS
PROCEDURE SP1;
PROCEDURE SP2;
END;
/
PACKAGE CREATED.
PACKAGE BODY:
CREATE OR REPLACE PACKAGE BODY MY_PACK
IS
PROCEDURE EMP_EXP (TEMPNO EMP.EMPNO%TYPE)
IS
TDATE EMP.HIREDATE%TYPE; -- PRIVATE VARIABLES
TEXP NUMBER;
BEGIN
SELECT HIREDATE INTO TDATE FROM EMP WHERE
EMPNO=TEMPNO;
TEXP: =ROUND((SYSDATE-TDATE)/365); DBMS_OUTPUT.PUT_LINE
(TEMPNO||' EMPLOYEE EXPERIENCE
IS '||TEXP||'YEARS.');
END EMP_EXP;
FUNCTION EMP_NETSAL (TEMPNO EMP.EMPNO%TYPE)
RETURN VARCHAR2
IS
TSAL EMP.SAL%TYPE;
TCOMM EMP.COMM%TYPE;
BEGIN
SELECT SAL+NVL(COMM,0) INTO RESULT FROM EMP
WHERE EMPNO=TEMPNO;
RETURN (TEMPNO||'EMPLOYEE NET SALARY RS.'||RESULT);
END EMP_NETSAL;
END MY_PACK;
PK3.SF1 (10,20,30)
-----------------
60
PK3.SF1 (10,20)
--------------
200
EX:
CREATE OR REPLACE PACKAGE FO_PACK
IS
FUNCTION ADDVAL (A NUMBER, B NUMBER) RETURN NUMBER;
FUNCTION ADDVAL (A NUMBER, B NUMBER, C NUMBER) RETURN
NUMBER;
FUNCTION ADDVAL (STR1 VARCHAR2, STR2 VARCHAR2) RETURN
VARCHAR2;
FUNCTION ADDVAL (STR1 VARCHAR2, STR2 VARCHAR2, STR3
VARCHAR2) RETURN VARCHAR2;
END FO_PACK;
PACKAGE BODY:
CREATE OR REPLACE PACKAGE BODY FO_PACK
IS
FUNCTION ADDVAL (A NUMBER, B NUMBER) RETURN NUMBER
IS
BEGIN
RETURN(A+B);
END ADDVAL;
NOTE:
> ALL PACKAGES BODIES ARE STORED IN 'USER_SOURCE'.
> TO SEE THE PACKAGE
BODY. EX:
SQL> SELECT TEXT FROM USER_SOURCE WHERE
NAME='FO_PACK';
EX:
SQL> DROP PACKAGE BODY MY_PACK;
DROPPING PACKAGES:
--------------------------------
SYNTAX:
SQL> DROP PACKAGE <PACKAGE NAME>;
EX:
SQL> DROP PACKAGE MY_PACK;
TRIGGERS:
A SET OF PL/SQL STATEMENTS STORED PERMANENTLY IN
DATABASE AND “AUTOMATICALLY” ACTIVATED WHEN EVER AN
EVENT RAISING STATEMENT (DML / DDL) IS PERFORMED.
THEY ARE USED TO IMPOSE USER DEFINED
RESTRICTIONS(OR)BUSINESS RULES ON TABLE / SCHEMA.THEY
ARE ALSO ACTIVATED WHEN TABLES ARE MANIPULATED BY
OTHER USERS OR BY OTHER APPLICATION S/W TOOLS.THEY
PROVIDE HIGH SECURITY ON TABLES.THEY ARE STORED IN
“USER_TRIGGERS” SYSTEM TABLE.
1. DML TRIGGERS
2. DDL TRIGGER / DB TRIGGERS
PURPOSE OF TRIGGERS:
1. TO INVOKING USER DEFINED MESSAGE (OR) ALERTS AT EVENT
RAISE.
2. TO CONTROL DML / DDL OPERATIONS.
3. TO IMPLEMENTING BUSINESS LOGICAL CONDITIONS.
4. TO VALIDATING DATA.
5. FOR AUDITING.
1. DML TRIGGERS:
- THESE TRIGGERS ARE EXECUTED BY SYSTEM
AUTOMATICALLY WHEN USER PERFORM DML (INSERT / UPDATE /
DELETE) OPERATIONS ON A SPECIFIC TABLE.
SYNTAX:
CREATE OR REPLACE TRIGGER <TRIGGER_NAME>
BEFORE/AFTER INSERT OR UPDATE OR DELETE
[ OF <COLUMNS>] ON <TABLE NAME>
[ FOR EACH ROW]
WHEN <CONDITION> (TRUE -> EXECUTES THE TRIGGER,
FALSE - NOT EXECUTE)
DECLARE
<VARIABLE DECLARATION>;]
BEGIN
<EXEC STATEMENTS>;
[ EXCEPTION
<EXEC STATEMENTS>;]
END;
TRIGGER EVENT:
- INDICATES WHEN TO ACTIVATE THE TRIGGER
BEFORE TRIGGER:
1. FIRST TRIGGER BODY IS EXECUTED
2. LATER DML COMMAND EXECUTED
AFTER TRIGGER:
1. FIRST DML COMMAND EXECUTED
2. LATER TRIGGER BODY EXECUTED
TRIGGER LEVELS:
- TRIGGER CAN CREATE AT TWO LEVELS.
A. ROW LEVEL TRIGGER:
- IN THIS LEVEL, TRIGGER BODY(LOGIC) IS EXECUTING FOR
EACH ROW WISE FOR A DML OPERATION.
EX:
CREATE OR REPLACE TRIGGER TR1
AFTER UPDATE ON TEST
FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('HELLO');
END;
/
TRIGGER CREATED.
TESTING:
SQL> UPDATE TEST SET SAL=10000 WHERE SAL=15000;
HELLO
HELLO
2 ROWS UPDATED.
B. STATEMENT TRIGGER:
- IN THIS LEVEL, TRIGGER BODY IS EXECUTING ONLY ONE
TIME FOR A DML OPERATION.
EX:
CREATE OR REPLACE TRIGGER TR1
AFTER UPDATE ON TEST
BEGIN
DBMS_OUTPUT.PUT_LINE('HELLO');
END;
/
TRIGGER CREATED.
TESTING:
SQL> UPDATE TEST SET SAL=12000 WHERE SAL=10000;
HELLO
2 ROWS UPDATED.
BIND VARIABLES:
- BIND VARIABLES ARE JUST LIKE VARIABLES WHICH ARE
USED TO STORE VALUES WHILE INSERTING, UPDATING,
DELETING DATA FROM A TABLE.THESE ARE TWO TYPES,
1. : NEW:
2. : OLD:
- THIS BIND VARIABLE WILL STORE OLD VALUES WHEN WE
DELETE.
SYNTAX:
:OLD. <COLUMN NAME>= <VALUE>;
EX:
: OLD.SAL = 12000;
EX:
CREATE OR REPLACE TRIGGER TRDELETE
AFTER DELETE ON TEST
BEGIN
DBMS_OUTPUT.PUT_LINE ('SOME ONE DELETED DATA FROM YOUR
TABLE');
END;
/
TRIGGER CREATED.
TESTING:
DELETE FROM TEST WHERE EDI=1022;
SOME ONE DELETING DATA FROM YOUR TABLE.
1 ROW DELETED.
EX:
CREATE OR REPLACE TRIGGER TRDML
AFTER INSERT OR UPDATE OR DELETE ON TEST
BEGIN
DBMS_OUTPUT.PUT_LINE ('SOME ONE PERFORMING DML
OPERATIONS ON YOUR TABLE');
END;
/
TRIGGER CREATED.
2. TO CONTROL / RESTRICTED DML OPERATIONS ON A TABLE:
EX:
CREATE OR REPLACE TRIGGER TRIN
AFTER INSERT ON TEST
BEGIN
RAISE_APPLICATION_ERROR (-20487,'SOME ONE INSERTING
DATA INTO YOUR TABLE');
END;
/
TESING:
INSERT INTO TEST VALUES (106,'MILLER',52000)
ERROR AT LINE 1:
ORA-20487: SOME ONE INSERTED DATA INTO UR TABLE
EX:
CREATE OR REPLACE TRIGGER TRUP
AFTER UPDATE ON TEST
BEGIN
RAISE_APPLICATION_ERROR (-20481,'SOME ONE UPDATING
DATA IN YOUR TABLE');
END;
/
TESTING:
UPDATE TEST SET SAL=22000 WHERE EID=1021;
ERROR AT LINE 1:
ORA-20487: SOME ONE UPDATING DATA IN YOUR TABLE
EX:
CREATE OR REPLACE TRIGGER TRDEL
AFTER DELETE ON TEST
BEGIN
RAISE_APPLICATION_ERROR (-20481,'SOME ONE DELETING
DATA FROM YOUR TABLE');
END;
/
TESTING:
DELETE FROM TEST WHERE EDI=1022;
ERROR AT LINE 1:
ORA-20487: SOME ONE DELETING DATA FROM YOUR TABLE.
EX:
CREATE OR REPLACE TRIGGER TRDEL
AFTER INSERT OR UPDATE OR DELETE ON TEST
BEGIN
RAISE_APPLICATION_ERROR (-20481,'SOME ONE PERFORMING
DML OPERATIONS ON YOUR TABLE');
END;
/
TESTING:
INSERT INTO TEST VALUES (106,'MILLER',52000);
UPDATE TEST SET SAL=22000 WHERE EID=1021;
DELETE FROM TEST WHERE EDI=1022;
ERROR AT LINE 1:
ORA-20781: SOME ONE PERFORMING DML OPERATIONS ON YOUR
TABLE.
3. TO IMPLEMENTING BUSINESS LOGICAL CONDITIONS:
EX:
CREATE A TRIGGER TO RESTRICTED DML OPERATIONS ON EVERY
SATURDAY?
EX:
CREATE A TRIGGER TO RESTRICTED DML OPERATIONS ON TEST
TABLE IN BETWEEN 9AM TO 5PM?
CREATE OR REPLACE TRIGGER TRTIME
AFTER INSERT OR UPDATE OR DELETE ON TEST
BEGIN
IF TO_CHAR(SYSDATE,'HH24') BETWEEN 9 AND 16 THEN
RAISE_APPLICATION_ERROR (-20456,'YOU CANNNOT PERFORM
DML OPERATIONS BETWEEN 9AM TO 5PM');
END IF;
END;
/
EX:
TRIGGER NAME: HOLI_TRIG
TABLE NAME: EMP
TRIGGER EVENT: BEFORE INSERT OR UPDATE OR DELETE
SOL:
CREATE OR REPLACE TRIGGER HOLI_TRIG
BEFORE INSERT OR UPDATE OR DELETE
ON EMP
DECLARE
CNT NUMBER;
BEGIN
IF TO_CHAR(SYSDATE,'HH24') NOT BETWEEN 10 AND 16 THEN
RAISE_APPLICATION_ERROR (-20001,'OFFTIMINGS, TRANS.
ARE NOT ALLOWED.');
END IF;
TESTING:
INSERT INTO TEST VALUES (1021,'SMITH',4500);--------NOT
ALLOWED
INSERT INTO TEST VALUES (1021,'SMITH',5500);--------ALLOWED
EX:
CREATE OR REPLACE TRIGGER DEPT_TRIG
BEFORE INSERT ON DEPT
FOR EACH ROW
BEGIN
: NEW.DNAME: =UPPER (: NEW.DNAME);
: NEW.LOC: =UPPER (: NEW.LOC);
END;
TESTING:
SQL> INSERT INTO DEPT VALUES (50,'ECONOMICS','HYD');
EX:
CREATE A TRIGGER TO VALIDATE UPDATE OPERATION ON TEST
TABLE IF NEW SALARY IS LESS THAN TO OLD SALARY?
SQL> CREATE OR REPLACE TRIGGER TRSAL2
BEFORE UPDATE ON TEST
FOR EACH ROW
BEGIN
IF: NEW.SAL <: OLD.SAL THEN
RAISE_APPLICATION_ERROR (-20748,'NEW SAL SHOULD NOT BE
LESS THAN TO OLD SALARY');
END IF;
END;
/
TESTING:
UPDATE TEST SET SAL=6000 WHERE SAL=8000;------NOT
ALLOWED
UPDATE TEST SET SAL=9000 WHERE SAL=8000;--------ALLOWED
EX:
CREATE A TRIGGER TO VALIDATE DELETE OPERATION ON TEST
TABLE IF WE TRY TO DELETE THE EMPLOYEE "SMITH" DETAILS?
SQL> CREATE OR REPLACE TRIGGER TRDATA
BEFORE DELETE ON TEST
FOR EACH ROW
BEGIN
IF: OLD.ENAME = 'SMITH' THEN
RAISE_APPLICATION_ERROR (-20648,'WE CANNOT DELETE
SMITH EMPLOYEE DETAILS');
END IF;
END;
/
TESTING:
DELETE FROM TEST WHERE ENAME='SMITH’; -----NOT ALLOWED
DELETE FROM TEST WHERE ENAME='ALLEN’;------ALLOWED
5. FOR AUDITING:
- WHEN WE MANIPULATE DATA IN A TABLE THOSE
TRANSACTIONAL VALUES ARE STORED IN ANOTHER TABLE IS
CALLED AS AUDITING TABLE.
EX:
SQL> CREATE TABLE EMP1(EID INT, ENAME VARCHAR2(10), SAL
NUMBER (10));
TABLE CREATED.
EX:
CREATE OR REPLACE TRIGGER TRAUDIT_INSERT
AFTER INSERT ON EMP1
FOR EACH ROW
BEGIN
INSERT INTO AUDITEMP1 VALUES (: NEW.EID,'SOME ONE
INSERTED A NEW ROW INTO EMP1 TABLE ON'||' '||
TO_CHAR (SYSDATE,'DD-MON-YYYY HH:MI: SS AM'));
END;
/
TESTING:
INSERT INTO EMP1 VALUES (1021,'SMITH',4500);
E
CREATE OR REPLACE TRIGGER TRAUDIT_UPDATE
AFTER UPDATE ON EMP1
FOR EACH ROW
BEGIN
INSERT INTO AUDITEMP1 VALUES (: OLD.EID,'SOME ONE
UPDATED DATA IN EMP1 TABLE ON'||' '||
TO_CHAR (SYSDATE,'DD-MON-YYYY HH:MI: SS AM'));
END;
/
TESTING:
UPDATE EMP1 SET SAL=6000 WHERE EID=1021;
EX:
CREATE OR REPLACE TRIGGER TRAUDIT_DELETE
AFTER DELETE ON EMP1
FOR EACH ROW
BEGIN
INSERT INTO AUDITEMP1 VALUES (: OLD.EID,'SOME ONE
DELETED DATA FROM EMP1 TABLE ON'||' '||
TO_CHAR (SYSDATE,'DD-MON-YYYY HH:MI: SS AM'));
END;
/
TESTING:
DELETE FROM EMP1 WHERE ENAME='SMITH';
E
CREATE OR REPLACE TRIGGER TRAUDIT_DML
AFTER INSERT OR UPDATE OR DELETE ON EMP1
FOR EACH ROW
BEGIN
INSERT INTO AUDITEMP1 VALUES (: OLD.EID,'SOME ONE
PERFORMING DML OPERATIONS ON EMP1 TABLE ON'||' '||
TO_CHAR (SYSDATE,'DD-MON-YYYY HH:MI: SS AM'));
END;
/
TESTING:
INSERT INTO EMP1 VALUES (1021,'SMITH',4500);
UPDATE EMP1 SET SAL=6000 WHERE EID=1021;
DELETE FROM EMP1 WHERE ENAME='SMITH';
EX:
SQL> CREATE OR REPLACE TRIGGER TRDDL
AFTER CREATE OR ALTER OR RENAME OR DROP ON
MYDB9AM.SCHEMA
BEGIN
RAISE_APPLICATION_ERROR (-20456,'WE CANNOT PERFORM
DDL OPERATIONS ON MYDB9AM SCHEMA');
END;
/
TRIGGER CREATED.
EX:
CREATE A TRIGGER TO RESTRICTED DDL OPERATIONS ON
MYDB9AM SCHEMA IN BETWEEN 9AM TO 5PM?
CREATE OR REPLACE TRIGGER TRDDLTIME
AFTER CREATE OR ALTER OR RENAME OR DROP ON
MYDB9AM.SCHEMA
BEGIN
IF TO_CHAR(SYSDATE,'HH24') BETWEEN 9 AND 16 THEN
RAISE_APPLICATION_ERROR (-20456,'YOU CANNNOT PERFORM
DDL OPERATIONS ON MYDB9AM BETWEEN 9AM TO 5PM');
END IF;
END;
/
DROPPING TRIGGERS:
SQL> DROP TRIGGER <TRIGGERNAME>;
EX:
DROP TRIGGER TRDDLTIME;