Sie sind auf Seite 1von 40

Contents of SQL:

1. Types of Sql Statements



2. Sql Data Types

3. Sql Operators

4. Sql Functions

5. Sql Joins

6. Sub Queries and Co related queries

7. Synonyms

8. Views

9. Sequences

10. Indexes

11. Constraints

12. Materialized Views

13. Global Temporary Table

14. Analytical Functions



























1) Types of Sql Statements:

1. DDL (Data Definition Language)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

Syntax:
Create table <Table_Name> ( Column_name Data_Type,
. . . . . . . . . . . . . . . . . . ,
. . . . . . . . . . . . . . . . . . ,
) Table space <tablespace_name>
Here Table space is Optional.

Example : Create Table Emp (Empno Number(18,2),
Ename Varchar2(50),
Sal Number(10,2),
Deptno Number(10,2))

ALTER The ALTER TABLE statement allows you to rename an existing table.
It can also be used to add, modify, or drop a column from an existing table.

Adding column(s) to a table
To add a column to an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name ADD column_name column-definition;
Example:
ALTER TABLE Emp
ADD Job varchar2(50);
This will add a column called Job to the emp table.
Modifying column(s) in a table

To modify a column in an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name MODIFY column_name column_type;
Examplele:
ALTER TABLE emp MODIFY ename varchar2(100) ;
This will modify the column called ename to be a data type of varchar2(100) and force the
column to not allow null values.
Drop column(s) in a table
To drop a column in an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name DROP COLUMN column_name;
Example:
ALTER TABLE emp DROP COLUMN job;
This will drop the column called job from the table called emp.
Renaming a table To rename the existing table

syntax:
ALTER TABLE table_name RENAME TO new_table_name;
Example:
ALTER TABLE emp RENAME TO employee;
DROP - delete objects from the database
Syntax :
drop table table_name;
drop table table_name cascade constraints;
drop table table_name purge;

Example :

Drop table emp;
TRUNCATE - remove all records from a table, including all spaces allocated for the records are
removed
Syntax :

Truncate Table <Table_Name>

Example :

Truncate Table Emp


DML(Data Manipulation Language):

(DML) statements are used for managing data within schema objects. Some examples:
INSERT inserting data into a table
Example :
Inserting a table with all columns :
Insert into Emp Values(1,john,1000,10)
Inserting a table with selected columns :
Insert into Emp(empno,ename) Values(2,Rajesh)
Inserting a table with select query :
Insert into emp (select * from emp1)
Note : Here emp and emp1 should have same structure Like Number of columns should be
same for both tables.
Inserting a table with selected columns of select query:
insert into emp2(empno,ename) (select empno,ename from emp2)
UPDATE - updates existing data within a table
Single Column Updatation:
Update Table Emp Set Sal = 1500 Where Empno = 10
Multiple columns Updation:
Update Table Emp Set Sal = 1500,ename = suresh Where Empno = 10
DELETE - deletes all records from a table, the space for the records remain
Deleting all the data in a table:
Delete From Emp
Deleting the data in a table with filtering condition(Where Clause):
Delete From emp Where Empno = 10
Delete From Emp Where Empno In (10,20,30)
MERGE - UPSERT operation (insert or update)
Syntax:
Merge Into Target table Trg
Using Source Table Src
On (Src.col = Trg.Col)
When Matched Then
Update Set Trg.col = Src.Col, . . .
When Not Matched Then
Insert (Trg.Col1,Trg.Col2,. . . . ) Values(Src.Col1,Src.Col2, . . . )

DCL(Data Control Language)

GRANT - gives user's access privileges to database
Syntax :
Grant Select On <Object_Name> To user_name Or Schema Name
Example :
Grant Select,Insert,Update On Emp To user_name Or Schema Name
Syntax :
Grant all On <Object_Name> To user_name Or Schema Name
Example :
Grant All On Emp To user_name Or Schema Name
REVOKE - withdraw access privileges given with the GRANT command
Syntax :
Revoke Select On <Object_Name> From user_name Or Schema Name
Example :
Revoke Select,Insert,Update On Emp From user_name Or Schema Name
Syntax :
Revoke all On <Object_Name> From user_name Or Schema Name
Example :
Revoke All On Emp From user_name Or Schema Name
TCL(Transaction Control)

(TCL) statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
COMMIT
Use the COMMIT statement to end your current transaction and make permanent all changes
performed in the transaction. A transaction is a sequence of SQL statements that Oracle
Database treats as a single unit. This statement also erases all savepoints in the transaction
and releases transaction locks.
ROLLBACK
The ROLLBACK statement is the inverse of the COMMIT statement. It undoes some or all
database changes made during the current transaction.
SAVEPOINT :
Identify a point in a transaction to which you can later roll back
The SAVEPOINT statement names and marks the current point in the processing of a
transaction. With the ROLLBACK TO statement, savepoints undo parts of a transaction instead
of the whole transaction. For more information, see
Insert into Emp(empno,ename) values(101,Suresh);
Insert into Emp(empno,ename) values(102,Ramesh);
Savepoint a;

Insert into Emp(empno,ename) values(103,Naresh);
Savepoint b;
Insert into Emp(empno,ename) values(104,Rajesh);
Insert into Emp(empno,ename) values(105,Remesh);

Savepoint c;

Insert into Emp(empno,ename) values(101,);
Savepoint d;

Rollback to C

It will rollback all the transactions after save point C and commit all the transactions before
save point C.

DQL(Data Query Language)

SELECT - retrieve data from the a database
Example :
Retrive data from all columns of table
Select * from Emp
Select a.* from Emp a
Retrive selected columns of table
Select empno,ename From emp
Select a.Empno,a.Ename,a.Sal From Emp a Where a.empno = 10
Retrive all columns with Filtering condition(Where Clause)
Select * From Emp Where Empno = 10
Select a.* From Emp a Where a.Empno = 10

2) Data Types

Data Type Description Max Size
Varchar2(Size)

Variable length
character string
having maximum
length size bytes.
You must specify size
4000 bytes
minimum is 1
NVARCHAR2(size) Variable length
national character set
string having
maximum length size
bytes.
You must specify size
4000 bytes
minimum is 1
VARCHAR VARCHAR is a
synonym for
VARCHAR2 but this
usage may change in
future versions
4000 bytes
minimum is 1
CHAR(size) Fixed length national 2000 bytes
character set data of
length size bytes.
This should be used
for fixed length data.
Default and minimum
size is 1 byte.
NUMBER(p,s) Number having
precision p and scale
s.
The precision p can
range from 1 to 38.
The scale s can range
from -84 to 127.
PLS_INTEGER signed integers
PLS_INTEGER values
require less storage
and provide better
performance than
NUMBER values.
So use PLS_INTEGER
where you can!
PL/SQL only
LONG Character data of
variable length (A
bigger version the
VARCHAR2 datatype)
2 Gigabytes
DATE Valid date range From January 1,
4712 BC to
December 31, 9999
AD.
TIMESTAMP
(fractional_seconds_precision)
the number of digits
in the fractional part
of the SECOND
datetime field.

TIMESTAMP
(fractional_seconds_precision)
WITH {LOCAL} TIMEZONE
As above with time
zone displacement
value

ROWID Hexadecimal string
representing the
unique address of a
row in its table.
(primarily for values
returned by the
ROWID
pseudocolumn.)
10 bytes
UROWID Hex string
representing the
logical address of a
row of an index-
organized table
The maximum size
and default is 4000
bytes
CLOB Character Large
Object
8 TB
NCLOB National Character
Large Object
8 TB
BLOB Binary Large Object 8 TB










3) SQL OPERATORS :

An Operator Manipulates Individual Data Items And Returns A Result.

1) Arithmetic Operators:
Arithmetic Operators Manipulate Numeric Operands.
The Arithmetic Operators Are + , - , / And *

Examples :

Select 10+20 From Dual

Select Sal * Comm From Emp


2) Character Operators:
Character Operators Are Used In Expressions To Manipulate Character Strings.
Character Operator Is ||
Example :
Select Ename|| Is Employee Name From Dual

3) Comparison Operators:
Comparison Operators Are Used In Conditions That Compare One Expression With Another.
The Result Of A Comparison Can Be True, False, Or Unknown.

Comparison Operators Are = , <> , < , <= , > , >= , In , Not In ,Between , Not
Between, Exists,Like , Not Like , Any(Some) And All.

Examples :

Select Ename "Employee" From Emp Where Sal = 1500;

Select Ename From Emp Where Sal <> 5000;

Select Ename "Employee", Job "Title" From Emp Where Sal > 3000;

Select * From Price Where Minprice < 30;

Select * From Price Where Minprice >= 20;

Select Ename From Emp Where Sal <= 1500;

Select * From Emp Where Ename In ('smith', 'ward');

Select * From Dept Where Loc Not In ('new York', 'dallas');

Select Ename, Job From Emp Where Sal Between 3000 And 5000;

Select * From Emp Where Exists (Select Ename From Emp Where Mgr Is
Null);

Select * From Emp Where Ename Like '%E%';

Select * From Emp Where Comm Is Not Null And Sal > 1500;

Select * From Dept Where Loc = Any ('new York','dallas');

Select * From Emp Where Sal >= All (1400, 3000);


4) Logical Operators:
Logical Operators Manipulate The Results Of Conditions.
Logical Operators Are And , Or And Not.

And: Returns True If Both Component Conditions Are True. Returns False If Either Is
False; Otherwise Returns Unknown.
Select * From Emp Where Job='clerk' And Deptno=10

Or: Returns True If Either Component Condition Is True. Returns False If Both Are False.
Otherwise, Returns Unknown.
Select * From Emp Where Job='clerk' Or Deptno=10

Not: Returns True If The Following Condition Is False. Returns False If It Is True. If It Is
Unknown, It Remains Unknown.
Select * From Emp Where Not (Job Is Null)

Select * From Emp Where Not (Sal Between 1000 And 2000)

5) Set Operators:
Set Operators Combine The Results Of Two Queries Into a
Single Result. Set Operators Are Union , Union All, Intersect And Minus

Union : Returns All Distinct Rows Selected By Either Query.

Select * From
(Select Ename From Emp Where Job = 'clerk'
Union
Select Ename From Emp Where Job = 'analyst');

Union All: Returns All Rows Selected By Either Query, Including All Duplicates.

Select * From
(Select Sal From Emp Where Job = 'clerk'
Union All
Select Sal From Emp Where Job = 'analyst');

Intersect: Returns All Distinct Rows Selected By Both Queries

Select * From Orders_List1
Intersect
Select * From Orders_List2

Minus : Returns All Distinct Rows Selected By The First Query But Not The Second.

Select * From (Select Sal From Emp Where Job = 'president'
Minus
Select Sal From Emp Where Job = 'manager');













4) SQL FUNCTIONS :
Number Functions:
Numeric Functions Accept Numeric Input And Return Numeric Values. Most Numeric Functions
That Return Number Values That Are Accurate To 38 Decimal Digits
Abs:
Abs Function Returns The Absolute Value Of A Number.
Syntax:
Abs( Number )
Example :
Select Abs(-23) From Dual
Ceil :
The Ceil Function Returns The Smallest Integer Value That Is Greater Than Or Equal To A
Number.
Ceil( Number )
Select Ceil(32.65) From Dual
Floor:
The Floor Function Returns The Largest Integer Value That Is Equal To Or Less Than A Number.
Floor( Number )
Select Floor(5.9) From Dual
Mod:
The Mod Function Returns The Remainder Of M Divided By N.
Mod( M, N )
The Mod Is Calculated As:
M - N * Floor(M/N)
Mod(15, 4)
Power:
The Power Function Returns M Raised To The Nth Power.
Syntax:
Power( M, N )
M Is The Base.
N Is The Exponent.
If M Is Negative, Then N Must Be An Integer.
Power(3, 2)
Round:
The Round Function Returns A Number Rounded To A Certain Number Of Decimal Places.
Syntax:
Round( Number, [ Decimal Places ])
Number Is The Number To Round.
Decimal Places Is The Number Of Decimal Places Rounded To. This Value Must Be An Integer.
If This Parameter Is Omitted, The Round Function Will Round The Number To 0 Decimal Places.
Round (125.315)
Exp:
The Exp Function Returns E Raised To the Nth Power, Where E = 2.71828183.
Syntax:
Exp (Number)
Number Is the Power to Raise E To.
Exp (3)
Remainder:
The Remainder Function Returns The Remainder Of M Divided By N.
Syntax:
Remainder (M, N)
The Remainder Is Calculated As:
M - (N * X) Where X Is The Integer Nearest M / N

Sign:
The Sign Function Returns A Value Indicating The Sign Of A Number.
Syntax:
Sign( Number )
If Number < 0, Then Sign Returns -1.
If Number = 0, Then Sign Returns 0.
If Number > 0, Then Sign Returns 1.
Sqrt:
The Sqrt Function Returns The Square Root Of N.
Syntax:
Sqrt( N )
N Is A Positive Number.
Sqrt(9)
Character Functions :
Chr:
He Chr Function Is The Opposite Of The Ascii Function. It Returns The Character Based On The
Number Code.
Syntax:
Chr( Number_Code )
Number_Code Is The Number Code Used To Retrieve The Character.
Concat:
The Concat Function Allows You To Concatenate Two Strings Together.
Syntax:
Concat( String1, String2 )
String1 Is The First String To Concatenate.
String2 Is The Second String To Concatenate.
Concat('tech On', ' The Net');
Initcap:
The Initcap Function Sets The First Character In Each Word To Uppercase And The Rest To
Lowercase.
The Syntax :
Initcap( String1 )
String1 Is The String Argument Whose First Character In Each Word Will Be Converted To
Uppercase And All Remaining Characters Converted To Lowercase.
Initcap('tech On The Net');
Lower:
He Lower Function Converts All Letters In The Specified String To Lowercase. If There Are
Characters In The String That Are Not Letters, They Are Unaffected By This Function.
The Syntax:
Lower( String1 )
String1 Is The String To Convert To Lowercase.
Lpad:
The Lpad Function Pads The Left-Side Of A String With A Specific Set Of Characters (When
String1 Is Not Null).
The Syntax:
Lpad( String1, Padded_Length, [ Pad_String ] )
String1 Is The String To Pad Characters To (The Left-Hand Side).
Padded_Length Is The Number Of Characters To Return. If The Padded_Length Is Smaller Than
The Original String, The Lpad Function Will Truncate The String To The Size Of Padded_Length.
Pad_String Is Optional. This Is The String That Will Be Padded To The Left-Hand Side Of
String1. If This Parameter Is Omitted, The Lpad Function Will Pad Spaces To The Left-Side Of
String1.
Lpad('tech', 8, '0');
Rpad:
The Rpad Function Pads The Right-Side Of A String With A Specific Set Of Characters (When
String1 Is Not Null).
The Syntax:
Rpad( String1, Padded_Length, [ Pad_String ] )
String1 Is The String To Pad Characters To (The Right-Hand Side).
Padded_Length Is The Number Of Characters To Return. If The Padded_Length Is Smaller Than
The Original String, The Rpad Function Will Truncate The String To The Size Of Padded_Length.
Pad_String Is Optional. This Is The String That Will Be Padded To The Right-Hand Side Of
String1. If This Parameter Is Omitted, The Rpad Function Will Pad Spaces To The Right-Side Of
String1.
Rpad('tech', 8, '0');
Ltrim:
The Ltrim Function Removes All Specified Characters From The Left-Hand Side Of A String.
The Syntax:
Ltrim( String1, [ Trim_String ] )
String1 Is The String To Trim The Characters From The Left-Hand Side.
Trim_String Is The String That Will Be Removed From The Left-Hand Side Of String1. If This
Parameter Is Omitted, The Ltrim Function Will Remove All Leading Spaces From String1.
Ltrim('123123Tech', '123');
Rtrim:
The Rtrim Function Removes All Specified Characters From The Right-Hand Side Of A String.
The Syntax:
Rtrim( String1, [ Trim_String ] )
String1 Is The String To Trim The Characters From The Right-Hand Side.
Trim_String Is The String That Will Be Removed From The Right-Hand Side Of String1. If This
Parameter Is Omitted, The Rtrim Function Will Remove All Trailing Spaces From String1.
Rtrim('123000', '0');
Translate:
The Translate Function Replaces A Sequence Of Characters In A String With Another Set Of
Characters. However, It Replaces A Single Character At A Time.
The Syntax:
Translate( String1, String_To_Replace, Replacement_String )
String1 Is The String To Replace A Sequence Of Characters With Another Set Of Characters.
String_To_Replace Is The String That Will Be Searched For In String1.
Replacement_String - All Characters In The String_To_Replace Will Be Replaced With The
Corresponding Character In The Replacement_String.
Translate('1Tech23', '123', '456');
Replace:
The Replace Function Replaces A Sequence Of Characters In A String With Another Set Of
Characters.
The Syntax:
Replace( String1, String_To_Replace, [ Replacement_String ] )
String1 Is The String To Replace A Sequence Of Characters With Another Set Of Characters.
String_To_Replace Is The String That Will Be Searched For In String1.
Replacement_String Is Optional. All Occurrences Of String_To_Replace Will Be Replaced With
Replacement_String In String1. If The Replacement_String Parameter Is Omitted, The Replace
Function Simply Removes All Occurrences Of String_To_Replace, And Returns The Resulting
String.
Replace('222Tech', '2', '3');
Substr:
The Substr Functions Allows You To Extract A Substring From A String.
The Syntax:
Substr( String, Start_Position, [ Length ] )
String Is The Source String.
Start_Position Is The Position For Extraction. The First Position In The String Is Always 1.
Length Is Optional. It Is The Number Of Characters To Extract. If This Parameter Is Omitted,
Substr Will Return The Entire String.
Substr('this Is A Test', 6, 2)
Instr:
The Instr Function Returns The Location Of A Substring In A String.
The Syntax:
Instr( String1, String2 [, Start_Position [, Nth_Appearance ] ] )
String1 Is The String To Search.
String2 Is The Substring To Search For In String1.
Start_Position Is The Position In String1 Where The Search Will Start. This Argument Is
Optional. If Omitted, It Defaults To 1. The First Position In The String Is 1. If The
Start_Position Is Negative, The Function Counts Back Start_Position Number Of Characters
From The End Of String1 And Then Searches Towards The Beginning Of String1.
Nth_Appearance Is The Nth Appearance Of String
2. This Is Optional. If Omitted, It Defaults To 1.
Instr('tech On The Net', 'e', 1, 1)
Upper:
The Upper Function Converts All Letters In The Specified String To Uppercase.
The Syntax:
Upper( String1 )
Upper('tech On The Net');
Date Functions:
Sysdate:
The Sysdate Function Returns The Current System Date And Time On Your Local Database.
The Syntax:
Sysdate
Add_Months:
The Add_Months Function Returns A Date Plus N Months.
The Syntax:
Add_Months( Date1, N )
Date1 Is The Starting Date (Before The N Months Have Been Added).
N Is The Number Of Months To Add To Date1.
Add_Months('01-Aug-03', 3)
Months Between:
The Months_Between Function Returns The Number Of Months Between Date1 And Date2.
The Syntax:
Months_Between( Date1, Date2 )
Date1 And Date2 Are The Dates Used To Calculate The Number Of Months.
If A Fractional Month Is Calculated, The Months_Between Function Calculates The Fraction
Based On A 31-Day Month.
Months_Between (To_Date ('2003/07/01', 'yyyy/Mm/Dd'), To_Date ('2003/03/14',
'yyyy/Mm/Dd') )
Next_Day:
The Next_Day Function Returns The First Weekday That Is Greater Than A Date.
The Syntax:
Next_Day( Date, Weekday )
Date Is Used To Find The Next Weekday.
Weekday Is A Day Of The Week (Ie: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday)
Next_Day('01-Aug-03', 'tuesday')
Last_Day:
The Last_Day Function Returns The Last Day Of The Month Based On A Date Value.
The Syntax:
Last_Day( Date )
Date Is The Date Value To Use To Calculate The Last Day Of The Month.
Last_Day(To_Date('2003/03/15', 'yyyy/Mm/Dd'))
Convertion Functions:
To_Char:
The To_Char Function Converts A Number Or Date To A String.
The Syntax:
To_Char( Value, [ Format_Mask ], [ Nls_Language ] )
Value Can Either Be A Number Or Date That Will Be Converted To A String.
Format_Mask Is Optional. This Is The Format That Will Be Used To Convert Value To A String.
Nls_Language Is Optional. This Is The Nls Language Used To Convert Value To A String.
To_Date:
The To_Date Function Converts A String To A Date.
The Syntax:
To_Date( String1, [ Format_Mask ], [ Nls_Language ] )
String1 Is The String That Will Be Converted To A Date.
Format_Mask Is Optional. This Is The Format That Will Be Used To Convert String1 To A Date.
Nls_Language Is Optional. This Is The Nls Language Used To Convert String1 To A Date.
To_Date('2003/07/09', 'yyyy/Mm/Dd')
To_Number:
The To_Number Function Converts A String To A Number.
The Syntax:
To_Number( String1, [ Format_Mask ], [ Nls_Language ] )
String1 Is The String That Will Be Converted To A Number.
Format_Mask Is Optional. This Is The Format That Will Be Used To Convert String1 To A
Number.
Nls_Language Is Optional. This Is The Nls Language Used To Convert String1 To A Number.
To_Number('1210.73', '9999.99')
Decode:
The Decode Function Has The Functionality Of An If-Then-Else Statement.
The Syntax:
Decode( Expression , Search , Result [, Search , Result]... [, Default] )
Expression Is The Value To Compare.
Search Is The Value That Is Compared Against Expression.
Result Is The Value Returned, If Expression Is Equal To Search.
Default Is Optional. If No Matches Are Found, The Decode Will Return Default. If Default Is
Omitted, Then The Decode Statement Will Return Null (If No Matches Are Found).
Case:
You Can Use The Case Statement Within An Sql Statement. It Has The Functionality Of An If-
Then-Else Statement.
The Syntax :
Case [ Expression ]
When Condition_1 Then Result_1
When Condition_2 Then Result_2
...
When Condition_N Then Result_N
Else Result
End
Miscellaneous Functions:
User:
The User Function Returns The User_Id From The Current Oracle Session.
The Syntax:
User
Userenv:
The Userenv Function Can Be Used To Retrieve Information About The Current Oracle Session.
The Syntax:
Userenv( Parameter )
Userenv('entryid')
Nvl:
Nvl function will substitute a value when a null value is encountered.
Syntax:
NVL( string1, replace_with )
string1 is the string to test for a null value.
replace_with is the value returned if string1 is null.
select NVL(commission, 0) from emp;
Nvl2:
Nvl2 function extends the functionality found in the NVL function. It lets you substitutes a
value when a null value is encountered as well as when a non-null value is encountered.
Syntax:
NVL2( string1, value_if_NOT_null, value_if_null )
string1 is the string to test for a null value.
value_if_NOT_null is the value returned if string1 is not null.
value_if_null is the value returned if string1 is null.
Select NVL2(comm, 0 ,10) from emp;

5) Joins
A Join Is A Query That Combines Rows From Two Or More Tables, Views, Or Materialized
Views. Oracle Performs A Join Whenever Multiple Tables Appear In The Query's From Clause.
The Query's Select List Can Select Any Columns From Any Of These Tables. If Any Two Of
These Tables Have A Column Name In Common, You Must Qualify All References To These
Columns Throughout The Query With Table Names To Avoid Ambiguity.
Join Conditions
Most Join Queries Contain Where Clause Conditions That Compare Two Columns, Each From A
Different Table. Such A Condition Is Called A Join Condition. To Execute A Join, Oracle
Combines Pairs Of Rows, Each Containing One Row From Each Table, For Which The Join
Condition Evaluates To True. The Columns In The Join Conditions Need Not Also Appear In The
Select List.


Equijoins
An Equijoin Is A Join With A Join Condition Containing An Equality Operator ( = ). An Equijoin
Combines Rows That Have Equivalent Values For The Specified Columns.
Example:
Select Emp.Empno,Emp.Ename,Emp.Sal,Emp.Deptno,Dept.Dname,Dept.City
From Emp,Dept
Where Emp.Deptno=Dept.Deptno;
The Above Query Can Also Be Written Like, Using Aliases, Given Below.
Select E.Empno, E.Ename, E.Sal, E.Deptno, D.Dname, D.City
From Emp E, Dept D
Where Emp.Deptno=Dept.Deptno;
The Above Query Can Also Be Written Like Given Below Without Using Table Qualifiers.
Select Empno,Ename,Sal,Dname,City From Emp,Dept Where Emp.Deptno=Dept.Deptno;
And If You Want To See All The Columns Of Both Tables Then The Query Can Be Written Like
This.
Select * From Emp,Dept Where Emp.Deptno=Dept.Deptno;
Non Equi Joins
Non Equi Joins Is Used To Return Result From Two Or More Tables Where Exact Join Is Not
Possible.
Example We Have Emp Table And Salgrade Table. The Salgrade Table Contains Grade And
Their Low Salary And High Salary. Suppose You Want To Find The Grade Of Employees Based
On Their Salaries Then You Can Use Non Equi Join.
Select E.Empno, E.Ename, E.Sal, S.Grade From Emp E, Salgrade S
Where E.Sal Between S.Lowsal And S.Hisal
Self Joins
A Self Join Is A Join Of A Table To Itself. This Table Appears Twice In The From Clause And Is
Followed By Table Aliases That Qualify Column Names In The Join Condition. To Perform A Self
Join, Oracle Combines And Returns Rows Of The Table That Satisfy The Join Condition.
Example The Following Query Returns Employee Names And Their Manager Names For Whom
They Are Working.
Select E.Empno, E.Ename, M.Ename Manager From Emp E, Emp M
Where E.Mgrid=M.Empno
Inner Join
An Inner Join (Sometimes Called A "Simple Join") Is A Join Of Two Or More Tables That
Returns Only Those Rows That Satisfy The Join Condition. Inner Join Is Type Of Equi Join.
Example:
Select *
From Emp,Dept
Where Emp.Deptno=Dept.Deptno;
Outer Joins
An Outer Join Extends The Result Of A Simple Join. An Outer Join Returns All Rows That Satisfy
The Join Condition And Also Returns Some Or All Of Those Rows From One Table For Which No
Rows From The Other Satisfy The Join Condition.
To Write A Query That Performs An Outer Join Of Tables A And B And Returns All Rows From A
(A Left Outer Join), Use The Ansi Left [Outer] Join Syntax, Or Apply The Outer Join Operator
(+) To All Columns Of B In The Join Condition. For All Rows In A That Have No Matching Rows
In B, Oracle Returns Null For Any Select List Expressions Containing Columns Of B.
To Write A Query That Performs An Outer Join Of Tables A And B And Returns All Rows From B
(A Right Outer Join), Use The Ansi Right [Outer] Syntax, Or Apply The Outer Join Operator (+)
To All Columns Of A In The Join Condition. For All Rows In B That Have No Matching Rows In A,
Oracle Returns Null For Any Select List Expressions Containing Columns Of A.
To Write A Query That Performs An Outer Join And And Returns All Rows From A And B,
Extended With Nulls If They Do Not Satisfy The Join Condition (A Full Outer Join), Use The Ansi
Full [Outer] Join Syntax.
Example The Following Query Returns All The Employees And Department Names And Even
Those Department Names Where No Employee Is Working.
Select E.Empno,E.Ename,E.Sal,E.Deptno,D.Dname,D.City
From Emp E, Dept D
Where E.Deptno(+)=D.Deptno;
That Is Specify The (+) Sign To The Column Which Is Lacking Values.
We can write above query by using the LEFT OUTER JOJN and RIGHT OUTER JOIN
Select E.Empno,E.Ename,E.Sal,E.Deptno,D.Dname,D.City
From Emp E LEFT OUTER JOIN Dept D
On E.Deptno = D.Deptno;
Select E.Empno,E.Ename,E.Sal,E.Deptno,D.Dname,D.City
From Emp E RIGHT OUTER JOIN Dept D
On E.Deptno = D.Deptno;
A Join Is The Process Of Combining Data From Two Or More Tables. The Dbms Takes All
Combinations Of Rows From The Given Tables.
Cross Join:
Join Without Filter Conditions.
A Cross Join Is The Cartesian Product Or The Result Of All Possible Combinations Of The Rows
From Each Of The Tables Involved In The Join Operation.
This Occurs When, No Specific Join Conditions (Filters) Are Specified. For Eg: There Are 3
Tables A,B And C With 10,20 And 30 Number Of Rows Respectively.
So A Cartesian Production Would Happen In The Below Scenario,
Select A.Col1, B.Col2, C.Col3 From A, B, C
Which Returns 10X20X30=6000 Records Are Result.
Thus The Number Of Rows In A Cartesian Product Of Two Tables Is Equal To The Number Of
Rows In The First Table Times The Number Of Rows In The Second Table.
Never Use This Kind Of Joins Unless Unavoidable As This Takes Huge Amount Of Memory To
Sort And Store
Natural Join: (Ansi Joins)
These Are Ansi Joins Which Are Used For Portability. You Can Use This In Almost All Standard
Databases Like Oracle, Microsoft Sql Server Etc.
Select Dname,Enaem,Mgr From Dept Natural Join Emp
Note : Both Tables Should Have Primary Key-Referential Key Relationship.

6) Sub Queries And Co Related Queries :
Sub query :
A Sub query Is A Query Within A Query. In Oracle, You Can Create Subqueries Within Your Sql
Statements. These Sub queries Can Reside In The Where Clause, The From Clause, Or The
Select Clause.
Where Clause:
Most Often, The Sub query Will Be Found In The Where Clause. These Subqueries Are Also
Called Nested Sub queries.
Example:
Select * From Emp Where Deptno In (Select Deptno From Dept)
Limitations:
Oracle Allows Up To 255 Levels Of Subqueries In The Where Clause.
From Clause:
A Subquery Can Also Be Found In The From Clause. These Are Called Inline Views.
Example:
Display the last three rows of the employee table:
Select *
From (Select a.* , rownum rn FROM emp a) , (Select count(*) c FROM emp)
WHERE rn>(c-3)
In This Example, We've Created A Sub query In The From Clause As Follows:
Select Clause:
Display the cumulative salary of employee:
A Subquery Can Also Be Found In The Select Clause.
Select Empno, Ename, Sal, (Select sum(sal) From emp
Where rowid<=e.rowid) cummsal
From emp e
In This Example, We've Created A Sub query In The Select Clause As Follows:
Oracle Allows An Unlimited Number Of Sub queries In The From Clause.
Correlated Query :
A Correlated Query is executed once for every row processed by the parent statement.
Example :
Display employee details who ever having more than average salary
Select * from emp a
where sal >= (select avg(sal) from emp b where a.deptno b.deptno)
Update employs salaries to maximum salary of each department wise:
Update emp a set sal = (Select max(sal) from emp b where a.deptno = b.deptno)






7) Synonyms:
A Synonym Is An Alternative Name For Objects Such As Tables, Views, Sequences, Stored
Procedures, And Other Database Objects.
Creating Or Replacing A Synonym
The Syntax:
Create [Or Replace] [Public] Synonym [Schema .] Synonym_Name
For [Schema .] Object_Name [@ Dblink];
The Or Replace Phrase Allows You To Recreate The Synonym (If It Already Exists) Without
Having To Issue A Drop Synonym Command.
The Public Phrase Means That The Synonym Is A Public Synonym And Is Accessible To All
Users. Remember Though That The User Must First Have The Appropriate Privileges To The
Object To Use The Synonym.
The Schema Phrase Is The Appropriate Schema. If This Phrase Is Omitted, Oracle Assumes
That You Are Referring To Your Own Schema.
The Object Name Phrase Is The Name Of The Object For Which You Are Creating The
Synonym. It Can Be One Of The Following:
Table, View, Materialized View, Sequence, Stored Procedure, Function, Package, Synonym
Example:
Create Public Synonym Employee
For Scott. Emp;
Select * From emp;
If This Synonym Already Existed And You Wanted To Redefine It, You Could Always Use The Or
Replace Phrase As Follows:
Create Or Replace Public Synonym Employee
For Scott. Emp;
Dropping A Synonym
It Is Also Possible To Drop A Synonym.
The Syntax:
Drop [Public] Synonym [Schema .] Synonym_Name [Force];
The Public Phrase Allows You To Drop A Public Synonym. If You Have Specified Public, Then
You Don't Specify A Schema.
The Force Phrase Will Force Oracle To Drop The Synonym Even If It Has Dependencies. It Is
Probably Not A Good Idea To Use The Force Phrase As It Can Cause Invalidation Of Oracle
Objects.
Example:
Drop Public Synonym Employee;
This Drop Statement Would Drop The Synonym Called emp That We Defined Earlier.

8) View:
View is virtual table, it doesnt contain any data. When you run a view it will run a query on
base table.
Create Single Table Basic View:
Create Or Replace View Emp_View As
Select empno,ename,sal,deptno
From emp;
Create Single Table View With Where Clause:
Create Or Replace View Emp_View1 As
Select empno, ename, sal, deptno
From emp Where deptno = 10;

Create Multi-Table View:
Create Or Replace View Emp_View3 As
Select a.empno,a.ename,a.deptno,a.sal
From Emp a,Dept b
Where a.deptno = b.deptno
Force ... Forces The Creation Of A View Even When The View Will Be Invalid. Noforce Is The
Default
Create Or Replace Force View View_Force As
Select * From Xyz;
Drop View:
Drop View Emp_View;
9)Sequence
A Sequence Is An Object In Oracle That Is Used To Generate A Number Sequence. This Can Be
Useful When You Need To Create A Unique Number To Act As A Primary Key.
The Syntax:
Create Sequence Sequence_Name
Minvalue Value
Maxvalue Value
Start With Value
Increment By Value
Cache Value;
Example:
Create Sequence emp_Seq
Minvalue 1
Maxvalue 9999
Start With 1
Increment By 1
Cache 20;
This Would Create A Sequence Object Called emp_Seq. The First Sequence Number That It
Would Use Is 1 And Each Subsequent Number Would Increment By 1 (Ie: 2,3,4,...}. It Will
Cache Up To 20 Values For Performance.
If You Omit The Maxvalue Option, Your Sequence Will Automatically Default To:
Maxvalue 9999
So You Can Simplify Your Create Sequence Command As Follows:
Create Sequence emp_Seq
Minvalue 1
Start With 1
Increment By 1
Cache 20;
Now That You've Created A Sequence Object To Simulate An Autonumber Field, We'll Cover
How To Retrieve A Value From This Sequence Object. To Retrieve The Next Value In The
Sequence Order, You Need To Use Nextval.
Example:
emp_Seq.Nextval
This Would Retrieve The Next Value From emp_Seq. The Nextval Statement Needs To Be Used
In An Sql Statement. Example:
Insert Into emp(empno,ename)
Values (emp_Seq.Nextval, 'SURESH');
This Insert Statement Would Insert A New Record Into The Emp Table. The empno Field Would
Be Assigned The Next Number From The emp_Seq Sequence. The ename Field Would Be Set
To suresh.
Note : With Respect To A Sequence, The Cache Option Specifies How Many Sequence Values
Will Be Stored In Memory For Faster Access
How Do We Set The Lastvalue Value In An Oracle Sequence?
You Can Change The Lastvalue For An Oracle Sequence, By Executing An Alter Sequence
Command.
Alter Sequence Seq_Name
Increment By 124;
Select Seq_Name.Nextval From Dual;
Alter Sequence Seq_Name
Increment By 1;

10) Index :
An Index Is A Performance-Tuning Method Of Allowing Faster Retrieval Of Records. An Index
Creates An Entry For Each Value That Appears In The Indexed Columns. By Default, Oracle
Creates B-Tree Indexes.
Create An Index
Syntax:
Create [Unique] Index Index_Name
On Table_Name (Column1, Column2, . Column_N)
[ Compute Statistics ];
Unique Indicates That The Combination Of Values In The Indexed Columns Must Be Unique.
Example:
Create Index emp_Idx On emp (empno);
Create A Function-Based Index
In Oracle, You Are Not Restricted To Creating Indexes On Only Columns. You Can Create
Function-Based Indexes.
The Syntax:
Create [Unique] Index Index_Name
On Table_Name (Function1, Function2, . Function_N)

Rename An Index
The Syntax:
Alter Index Index_Name Rename To New_Index_Name;
Example:
Alter Index emp_Idx Rename To emp_Index_Name;
In This Example, We're Renaming The Index Called emp_Idx To emp_Index_Name.
Drop An Index
The Syntax:
Drop Index Index_Name;
Example:
Drop Index emp_Idx;
In This Example, We're Dropping An Index Called emp_Idx.
11) Constraints :
Constraints Enforce Rules On Table Data.When Ever You Run Any Dml Operations On A Table,
The Constraints Must Be Satisfied For The Operation To Succeed.Constraint Can Be Defined At
Column Level Or Table Level.
1.Primary Key
A Primary Key Is A Single Field Or Combination Of Fields That Uniquely Defines A Record. None
Of The Fields That Are Part Of The Primary Key Can Contain A Null Value. A Table Can Have
Only One Primary Key.
Note: Primary Key Can Not Contain More Than 32 Columns.
A Primary Key Can Be Defined In Either A Create Table Statement Or An Alter Table
Statement. Using A Create Table Statement


Syntax :
Create Table Table_Name
(Column1 Datatype Null/Not Null,
Column2 Datatype Null/Not Null,
...
Constraint Constraint_Name Primary Key (Column1, Column2, . Column_N)
);
Example:
Create Table Supplier
( Supplier_Id Numeric(10) Not Null,
Supplier_Name Varchar2(50) Not Null,
Contact_Name Varchar2(50),
Constraint Supplier_Pk Primary Key (Supplier_Id)
);
In This Example, We've Created A Primary Key On The Supplier Table Called Supplier_Pk. It
Consists Of Only One Field - The Supplier_Id Field.
We Could Also Create A Primary Key With More Than One Field As In The Example Below:
Create Table Supplier
( Supplier_Id Numeric(10) Not Null,
Supplier_Name Varchar2(50) Not Null,
Contact_Name Varchar2(50),
Constraint Supplier_Pk Primary Key (Supplier_Id, Supplier_Name)
);
Using An Alter Table Statement
The Syntax:
Alter Table Table_Name
Add Constraint Constraint_Name Primary Key (Column1, Column2, ... Column_N);

Example:
Alter Table Supplier
Add Constraint Supplier_Pk Primary Key (Supplier_Id);
In This Example, We've Created A Primary Key On The Existing Supplier Table Called
Supplier_Pk. It Consists Of The Field Called Supplier_Id.
We Could Also Create A Primary Key With More Than One Field As In The Example Below:
Alter Table Supplier
Add Constraint Supplier_Pk Primary Key (Supplier_Id, Supplier_Name);
Drop A Primary Key
Syntax:
Alter Table Table_Name
Drop Constraint Constraint_Name;
Example:
Alter Table Supplier
Drop Constraint Supplier_Pk;
In This Example, We're Dropping A Primary Key On The Supplier Table Called Supplier_Pk.
Disable A Primary Key
Syntax :
Alter Table Table_Name
Disable Constraint Constraint_Name;
Example:
Alter Table Supplier
Disable Constraint Supplier_Pk;
In This Example, We're Disabling A Primary Key On The Supplier Table Called Supplier_Pk.
Enable A Primary Key
Syntax:
Alter Table Table_Name
Enable Constraint Constraint_Name;

Example:
Alter Table Supplier
Enable Constraint Supplier_Pk;
In This Example, We're Enabling A Primary Key On The Supplier Table Called Supplier_Pk.
2.Unique
A Unique Constraint Is A Single Field Or Combination Of Fields That Uniquely Defines A Record.
Some Of The Fields Can Contain Null Values As Long As The Combination Of Values Is Unique.
Note: Unique Constraint Can Not Contain More Than 32 Columns.
A Unique Constraint Can Be Defined In Either A Create Table Statement Or An Alter Table
Statement.
The Difference Between A Unique Constraint And A Primary Key:
Primary Key Cannot Contain A Null Value. But Unique Constraint Can Contain Null Values.
Using A Create Table Statement
Syntax:
Create Table Table_Name
(Column1 Datatype Null/Not Null,
Column2 Datatype Null/Not Null,
...
Constraint Constraint_Name Unique (Column1, Column2, . Column_N)
);

Example:
Create Table Supplier
( Supplier_Id Numeric(10) Not Null,
Supplier_Name Varchar2(50) Not Null,
Contact_Name Varchar2(50),
Constraint Supplier_Unique Unique (Supplier_Id)
);
In This Example, We've Created A Unique Constraint On The Supplier Table Called
Supplier_Unique. It Consists Of Only One Field - The Supplier_Id Field.

We Could Also Create A Unique Constraint With More Than One Field As In The Example Below:
Create Table Supplier
( Supplier_Id Numeric(10) Not Null,
Supplier_Name Varchar2(50) Not Null,
Contact_Name Varchar2(50),
Constraint Supplier_Unique Unique (Supplier_Id, Supplier_Name)
);

Using An Alter Table Statement
The Syntax:
Alter Table Table_Name
Add Constraint Constraint_Name Unique (Column1, Column2, ... Column_N);

Example:
Alter Table Supplier
Add Constraint Supplier_Unique Unique (Supplier_Id);
In This Example, We've Created A Unique Constraint On The Existing Supplier Table Called
Supplier_Unique. It Consists Of The Field Called Supplier_Id.

We Could Also Create A Unique Constraint With More Than One Field As In The Example Below:
Alter Table Supplier
Add Constraint Supplier_Unique Unique (Supplier_Id, Supplier_Name);

Drop A Unique Constraint
The Syntax:
Alter Table Table_Name
Drop Constraint Constraint_Name;

Example:
Alter Table Supplier
Drop Constraint Supplier_Unique;
In This Example, We're Dropping A Unique Constraint On The Supplier Table Called
Supplier_Unique.
Disable A Unique Constraint
The Syntax:
Alter Table Table_Name
Disable Constraint Constraint_Name;
Example:
Alter Table Supplier
Disable Constraint Supplier_Unique;
In This Example, We're Disabling A Unique Constraint On The Supplier Table Called
Supplier_Unique.
Enable A Unique Constraint
The Syntax:
Alter Table Table_Name
Enable Constraint Constraint_Name;
Example:
Alter Table Supplier
Enable Constraint Supplier_Unique;
In This Example, We're Enabling A Unique Constraint On The Supplier Table Called
Supplier_Unique.
3.Not Null:
A Not null constraint will not allow the null values.
Syntax :
CREATE TABLE table_name
(column1 datatype not null,
column2 datatype not null,
. . . . . . . );
Example:
Create table emp (empno number not null,
Ename Varchar2(100),
Sal Number);
4.Check:
A check constraint allows you to specify a condition on each row in a table. Check constraint
can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.
Note:1) A check constraint can NOT be defined on a VIEW.
2) The check constraint defined on a table must refer to only columns in that table.
It can not refer to columns in other tables.
Using a CREATE TABLE statement
syntax :
CREATE TABLE table_name
(column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE]
);
Example:
Create Table Emp (Empno Number,
Ename Varchar2(100),
Sal Number Constraint ck_1 check(sal > 10000));
5.Foreign Key
A Foreign Key Means That Values In One Table Must Also Appear In Another Table.
The Referenced Table Is Called The Parent Table While The Table With The Foreign Key Is
Called The Child Table. The Foreign Key In The Child Table Will Generally Reference A Primary
Key In The Parent Table.
A Foreign Key Can Be Defined In Either A Create Table Statement Or An Alter Table Statement.
Using A Create Table Statement

The Syntax:
Create Table Table_Name
(Column1 Datatype ,
Column2 Datatype ,
. . . . . . . . . .
Constraint Fk_Column
Foreign Key (Column1, Column2, ... Column_N)
References Parent_Table (Column1, Column2, ... Column_N)
);
Example:
Create Table Supplier
( Supplier_Id Numeric(10) Not Null,
Supplier_Name Varchar2(50) Not Null,
Contact_Name Varchar2(50),
Constraint Supplier_Pk Primary Key (Supplier_Id)
);
Create Table Products
( Product_Id Numeric(10) Not Null,
Supplier_Id Numeric(10) Not Null,
Constraint Fk_Supplier
Foreign Key (Supplier_Id)
References Supplier(Supplier_Id));
In This Example, We've Created A Primary Key On The Supplier Table Called Supplier_Pk. It
Consists Of Only One Field - The Supplier_Id Field. Then We've Created A Foreign Key Called
Fk_Supplier On The Products Table That References The Supplier Table Based On The
Supplier_Id Field.
We Could Also Create A Foreign Key With More Than One Field As In The Example Below:



Create Table Supplier
( Supplier_Id Numeric(10) Not Null,
Supplier_Name Varchar2(50) Not Null,
Contact_Name Varchar2(50),
Constraint Supplier_Pk Primary Key (Supplier_Id, Supplier_Name)
);
Create Table Products
( Product_Id Numeric(10) Not Null,
Supplier_Id Numeric(10) Not Null,
Supplier_Name Varchar2(50) Not Null,
Constraint Fk_Supplier_Comp
Foreign Key (Supplier_Id, Supplier_Name)
References Supplier(Supplier_Id, Supplier_Name)
);
In This Example, Our Foreign Key Called Fk_Foreign_Comp References The Supplier Table
Based On Two Fields - The Supplier_Id And Supplier_Name Fields.
Using An Alter Table Statement
The Syntax:
Alter Table Table_Name
Add Constraint Constraint_Name Foreign Key (Column1, Column2, ... Column_N)
References Parent_Table (Column1, Column2, ... Column_N);
Example:
Alter Table Products Add Constraint Fk_Supplier Foreign Key (Supplier_Id)
References Supplier(Supplier_Id);
In This Example, We've Created A Foreign Key Called Fk_Supplier That References The
Supplier Table Based On The Supplier_Id Field.
We Could Also Create A Foreign Key With More Than One Field As In The Example Below:
Alter Table Products Add Constraint Fk_Supplier
Foreign Key (Supplier_Id, Supplier_Name) References Supplier(Supplier_Id, Supplier_Name);
12) Materialized Views :
It Stores The Result Set Of A Query. Materialized Views Can Query Table Or Views Or Other
Mterialized Views. It Can Be Read Only,Updatable Or Writable.It Has Refresh Option When Any
Changes Made In Base Table.
Refresh Options :
Fast Incrementally Applies Data Changes
It Use Materialized View Logs To Send Rows That Have Changed From Master Table To
Materialized View.
Complete Totally Refreshes The View
It Recreates The Entire Matrilized View.Can Be Done At Any Time; Can Be Time Consuming
Force Does A Fast Refresh In Favor Of A Complete
The Default Refresh Option Is Fast
Refresh Modes :
On Commit Refreshes Occur Whenever A Commit Is Performed On One Of The ViewS
Underlying Detail Table(S)
Available Only With Single Table Aggregate Or Join Based Views
Keeps View Data Transactionally Accurate
Need To Check Alert Log For View Creation Errors
On Demand Refreshes Are Initiated Manually Using One Of The Procedures In The
Dbms_Mview Package
Can Be Used With All Types Of Materialized Views
Manual Refresh Procedures
Dbms_Mview.Refresh(<Mv_Name>, <Refresh_Option>)
Dbms_Mview.Refresh_All_Mviews()
Start With [Next] <Date> - Refreshes Start At A Specified Date/Time And Continue At Regular
Intervals


Create Materialized View Cust_Activity
Build Immediate
Refresh Fast On Commit
As Select U.Rowid Cust_Rowid, L.Rowid Item_Rowid,
U.Cust_Id, U.Custname, U.Email,
L.Categ_Id, L.Site_Id, Sum(Gms), Sum(Net_Rev_Fee)
From Customers U, Items L
Where U.Cust_Id = L.Seller_Id
Group By U.Cust_Id, U.Custname, U.Email, L.Categ_Id, L.Site_Id;
Periodic Refresh :
Create Materialized View V_1
Refresh Fast Next Sysdate+1
As Select * From Emp
Automatic Reffresh :
Create Materialized View V_1
Refresh Fast
As Select * From Emp
Advantages:
1) Useful For Summarizing, Pre-Computing, Replicating And Distributing Data
2) Faster Access For Expensive And Complex Joins
3) Transparent To End-Users
Disadvantages
1) Performance Costs Of Maintaining The Views
2) Storage Costs Of Maintaining The Views




13) Global Temporary Table :
Global Temporary Table Is A Temporary Table. When Ever We Want Transaction Based Data Or
Session Based Data We Can Go For Global Temporary Table. We Have Two Options While
Creating The Global Temporary Table.
1)On Commit Preserve Rows Clause Indicates Data Can Be Preserved For The Whole Session
Until Close The Session
2) On Commit Delete Rows Clause Indicates That The Data Should Be Deleted At The End Of
The Transaction.
Syntax :
Create Global Temporary Table My_Temp_Table (
Column1 Number,
Column2 Number
) On Commit Delete Rows;
Create Global Temporary Table My_Temp_Table (
Column1 Number,
Column2 Number
) On Commit Preserve Rows;

14) Analytical Functions :
1) More Flexible and more efficient to use.
2) Easier to code
3) No need to tune for performance.
1) Rank Functions
Rank Functions are Rank(), Dense_Rank() and Rownumber.

Examples :

Display 2
nd
highest salary from emp table:

Select empno,sal from (select empno,sal rank() over(order by sal desc) r from emp)
Where r = 2
By Using rank() function, leaving the gaps while ranking the records.

Select empno,sal from (select empno,sal Dense_rank() over(order by sal desc) r
from emp)
Where r = 2;
By Using Dense_Rank() function, doesnt leave the gaps while ranking the records.


2) Window Functions
Window Functions are consists of all group functions like
Sum,Avg,Max,Min,First_Value and Last_Value
Examples :
Displaying the cumulative salary of employee
Select sal,Sum(sal) Over(order by sal) from emp
Select first_value(sal) over(partition by deptno order by sal) from emp

3) Lead and Lag Functions :
Lead Function has the ability to give next row.
Lag Function has the ability to give previous row.
Examples :
Select Lead(sal,1) from emp
Select Lag(sal,1) from emp