Sql_contents by Suneel

download Sql_contents by Suneel

of 40

Transcript of Sql_contents by Suneel

  • 8/12/2019 Sql_contents by Suneel

    1/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

  • 8/12/2019 Sql_contents by Suneel

    2/40

    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 ( Column_name Data_Type,

    . . . . . . . . . . . . . . . . . . ,

    . . . . . . . . . . . . . . . . . . ,) Table space

    Here Table space is Optional.

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

    Sal Number(10,2),Deptno Number(10,2))

    ALTERThe 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 thecolumn 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;

  • 8/12/2019 Sql_contents by Suneel

    3/40

    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 areremoved

    Syntax :

    Truncate Table

    Example :

    Truncate Table Emp

    DML(Data Manipulation Language):

    (DML) statements are used for managing data within schema objects. Some examples:

    INSERTinserting 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 besame for both tables.

  • 8/12/2019 Sql_contents by Suneel

    4/40

    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 To user_name Or Schema Name

    Example :

    Grant Select,Insert,Update On Emp To user_name Or Schema Name

  • 8/12/2019 Sql_contents by Suneel

    5/40

    Syntax :

    Grant all On 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 From user_name Or Schema Name

    Example :

    Revoke Select,Insert,Update On Emp From user_name Or Schema Name

    Syntax :

    Revoke all On 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 allowsstatements to be grouped together into logical transactions.

    COMMIT

    Use the COMMIT statement to end your current transaction and make permanent all changesperformed 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 transactionand 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 atransaction. With the ROLLBACK TO statement, savepoints undo parts of a transaction insteadof 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;

  • 8/12/2019 Sql_contents by Suneel

    6/40

    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 beforesave 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 stringhaving maximumlength sizebytes.You must specify size

    4000 bytes

    minimum is 1

    NVARCHAR2(size) Variable lengthnational character setstring havingmaximum length size

    bytes.You must specify size

    4000 bytesminimum is 1

    VARCHAR VARCHAR is a

    synonym for

    VARCHAR2 but thisusage may change infuture versions

    4000 bytes

    minimum is 1

    CHAR(size) Fixed length national 2000bytes

  • 8/12/2019 Sql_contents by Suneel

    7/40

    character set data oflength size bytes.This should be usedfor fixed length data.

    Default and minimumsize is 1 byte.

    NUMBER(p,s) Number havingprecision p and scales.

    The precision p canrange from 1 to 38.The scale s can range

    from -84 to 127.PLS_INTEGER signed integers

    PLS_INTEGER valuesrequire less storage

    and provide betterperformance thanNUMBER values.So use PLS_INTEGER

    where you can!

    PL/SQL only

    LONG Character data ofvariable length (A

    bigger version the

    VARCHAR2 datatype)

    2 Gigabytes

    DATE Valid date range From January 1,

    4712 BC toDecember 31, 9999AD.

    TIMESTAMP(fractional_seconds_precision)

    the number of digitsin the fractional partof the SECONDdatetime field.

    TIMESTAMP(fractional_seconds_precision)WITH {LOCAL} TIMEZONE

    As above with timezone displacementvalue

    ROWID Hexadecimal stringrepresenting theunique address of a

    row in its table.(primarily for valuesreturned by theROWIDpseudocolumn.)

    10 bytes

    UROWID Hex stringrepresenting thelogical address of arow of an index-organized table

    The maximum sizeand default is 4000bytes

    CLOB Character LargeObject

    8 TB

    NCLOB National CharacterLarge Object

    8 TB

    BLOB Binary Large Object 8 TB

    http://www.orafaq.com/wiki/ROWIDhttp://www.orafaq.com/wiki/ROWIDhttp://www.orafaq.com/wiki/ROWID
  • 8/12/2019 Sql_contents by Suneel

    8/40

    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 , NotBetween, 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 Dept Where Loc = Any ('new York','dallas');

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

  • 8/12/2019 Sql_contents by Suneel

    9/40

    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 IsFalse; 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 IsUnknown, 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'UnionSelect 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 AllSelect Sal From Emp Where Job = 'analyst');

    Intersect: Returns All Distinct Rows Selected By Both Queries

    Select * From Orders_List1IntersectSelect * 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');

  • 8/12/2019 Sql_contents by Suneel

    10/40

    4) SQL FUNCTIONS :

    Number Functions:

    Numeric Functions Accept Numeric Input And Return Numeric Values. Most Numeric FunctionsThat 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 ANumber.

    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 )

  • 8/12/2019 Sql_contents by Suneel

    11/40

    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 )

  • 8/12/2019 Sql_contents by Suneel

    12/40

    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 TheNumber 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 ToLowercase.

    The Syntax :

    Initcap( String1 )

    String1 Is The String Argument Whose First Character In Each Word Will Be Converted ToUppercase And All Remaining Characters Converted To Lowercase.

  • 8/12/2019 Sql_contents by Suneel

    13/40

    Initcap('tech On The Net');

    Lower:

    He Lower Function Converts All Letters In The Specified String To Lowercase. If There AreCharacters 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 (WhenString1 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 ThanThe 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 OfString1. If This Parameter Is Omitted, The Lpad Function Will Pad Spaces To The Left-Side OfString1.

    Lpad('tech', 8, '0');

    Rpad:

    The Rpad Function Pads The Right-Side Of A String With A Specific Set Of Characters (WhenString1 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 ThanThe 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 OfString1. If This Parameter Is Omitted, The Rpad Function Will Pad Spaces To The Right-Side OfString1.

    Rpad('tech', 8, '0');

    Ltrim:

    The Ltrim Function Removes All Specified Characters From The Left-Hand Side Of A String.

  • 8/12/2019 Sql_contents by Suneel

    14/40

    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 ThisParameter 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 OfCharacters. 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 TheCorresponding Character In The Replacement_String.

    Translate('1Tech23', '123', '456');

    Replace:

    The Replace Function Replaces A Sequence Of Characters In A String With Another Set OfCharacters.

    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.

  • 8/12/2019 Sql_contents by Suneel

    15/40

  • 8/12/2019 Sql_contents by Suneel

    16/40

    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 FractionBased 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:

  • 8/12/2019 Sql_contents by Suneel

    17/40

    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 ANumber.

    Nls_Language Is Optional. This Is The Nls Language Used To Convert String1 To A Number.

  • 8/12/2019 Sql_contents by Suneel

    18/40

    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 IsOmitted, 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:

  • 8/12/2019 Sql_contents by Suneel

    19/40

    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 theNVL function.It lets you substitutes avalue 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 notnull.

    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 MaterializedViews. 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 OfThese Tables Have A Column Name In Common, You Must Qualify All References To TheseColumns Throughout The Query With Table Names To Avoid Ambiguity.

    Join Conditions

    Most Join Queries Contain Where Clause Conditions That Compare Two Columns, Each From ADifferent Table. Such A Condition Is Called A Join Condition. To Execute A Join, OracleCombines Pairs Of Rows, Each Containing One Row From Each Table, For Which The JoinCondition Evaluates To True. The Columns In The Join Conditions Need Not Also Appear In TheSelect List.

    http://www.techonthenet.com/oracle/functions/nvl.phphttp://www.techonthenet.com/oracle/functions/nvl.phphttp://www.techonthenet.com/oracle/functions/nvl.phphttp://www.techonthenet.com/oracle/functions/nvl.php
  • 8/12/2019 Sql_contents by Suneel

    20/40

    Equijoins

    An Equijoin Is A Join With A Join Condition Containing An Equality Operator ( = ). An EquijoinCombines 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 LikeThis.

    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 NotPossible.

    Example We Have Emp Table And Salgrade Table. The Salgrade Table Contains Grade AndTheir Low Salary And High Salary. Suppose You Want To Find The Grade Of Employees BasedOn 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 IsFollowed By Table Aliases That Qualify Column Names In The Join Condition. To Perform A SelfJoin, 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 WhomThey Are Working.

    Select E.Empno, E.Ename, M.Ename Manager From Emp E, Emp M

    Where E.Mgrid=M.Empno

  • 8/12/2019 Sql_contents by Suneel

    21/40

    Inner Join

    An Inner Join (Sometimes Called A "Simple Join") Is A Join Of Two Or More Tables ThatReturns 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 SatisfyThe Join Condition And Also Returns Some Or All Of Those Rows From One Table For Which NoRows 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 RowsIn 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 AnsiFull [Outer] Join Syntax.

    Example The Following Query Returns All The Employees And Department Names And EvenThose 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;

  • 8/12/2019 Sql_contents by Suneel

    22/40

    A Join Is The Process Of Combining Data From Two Or More Tables. The Dbms Takes AllCombinations 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 RowsFrom Each Of The Tables Involved In The Join Operation.

    This Occurs When, No Specific Join Conditions (Filters) Are Specified. For Eg: There Are 3Tables 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 OfRows 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 ToSort And Store

    Natural Join: (Ansi Joins)

    These Are Ansi Joins Which Are Used For Portability. You Can Use This In Almost All StandardDatabases 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 TheSelect Clause.

    Where Clause:

    Most Often, The Sub query Will Be Found In The Where Clause. These Subqueries Are AlsoCalled 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.

  • 8/12/2019 Sql_contents by Suneel

    23/40

    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 empWhere rowid

  • 8/12/2019 Sql_contents by Suneel

    24/40

    7) Synonyms:

    A Synonym Is An Alternative Name For Objects Such As Tables, Views, Sequences, StoredProcedures, 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) WithoutHaving To Issue A Drop Synonym Command.

    The Public Phrase Means That The Synonym Is A Public Synonym And Is Accessible To AllUsers. 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 AssumesThat You Are Referring To Your Own Schema.

    The Object Name Phrase Is The Name Of The Object For Which You Are Creating TheSynonym. 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 OrReplace 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, ThenYou Don't Specify A Schema.

  • 8/12/2019 Sql_contents by Suneel

    25/40

    The Force Phrase Will Force Oracle To Drop The Synonym Even If It Has Dependencies. It IsProbably Not A Good Idea To Use The Force Phrase As It Can Cause Invalidation Of OracleObjects.

    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 onbase 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 TheDefault

    Create Or Replace Force View View_Force As

    Select * From Xyz;

    Drop View:

    Drop View Emp_View;

  • 8/12/2019 Sql_contents by Suneel

    26/40

    9)Sequence

    A Sequence Is An Object In Oracle That Is Used To Generate A Number Sequence. This Can BeUseful 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 WillCache 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 TheSequence Order, You Need To Use Nextval.

  • 8/12/2019 Sql_contents by Suneel

    27/40

    Example:

    emp_Seq.Nextval

    This Would Retrieve The Next Value From emp_Seq. The Nextval Statement Needs To Be UsedIn 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 WouldBe Assigned The Next Number From The emp_Seq Sequence. The ename Field Would Be SetTo suresh.

    Note : With Respect To A Sequence, The Cache Option Specifies How Many Sequence ValuesWill 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 SequenceCommand.

    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, OracleCreates 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);

  • 8/12/2019 Sql_contents by Suneel

    28/40

    Create A Function-Based Index

    In Oracle, You Are Not Restricted To Creating Indexes On Only Columns. You Can CreateFunction-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. NoneOf The Fields That Are Part Of The Primary Key Can Contain A Null Value. A Table Can HaveOnly 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 TableStatement. Using A Create Table Statement

  • 8/12/2019 Sql_contents by Suneel

    29/40

    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. ItConsists 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);

  • 8/12/2019 Sql_contents by Suneel

    30/40

    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;

  • 8/12/2019 Sql_contents by Suneel

    31/40

    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 TableStatement.

    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 CalledSupplier_Unique. It Consists Of Only One Field - The Supplier_Id Field.

  • 8/12/2019 Sql_contents by Suneel

    32/40

    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 CalledSupplier_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;

  • 8/12/2019 Sql_contents by Suneel

    33/40

    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 CalledSupplier_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,

    . . . . . . . );

  • 8/12/2019 Sql_contents by Suneel

    34/40

    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 constraintcan 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 IsCalled The Child Table. The Foreign Key In The Child Table Will Generally Reference A PrimaryKey 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

  • 8/12/2019 Sql_contents by Suneel

    35/40

    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. ItConsists Of Only One Field - The Supplier_Id Field. Then We've Created A Foreign Key CalledFk_Supplier On The Products Table That References The Supplier Table Based On TheSupplier_Id Field.

    We Could Also Create A Foreign Key With More Than One Field As In The Example Below:

  • 8/12/2019 Sql_contents by Suneel

    36/40

    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 TableBased 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 TheSupplier 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);

  • 8/12/2019 Sql_contents by Suneel

    37/40

    12) Materialized Views :

    It Stores The Result Set Of A Query. Materialized Views Can Query Table Or Views Or OtherMterialized Views. It Can Be Read Only,Updatable Or Writable.It Has Refresh Option When AnyChanges 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 ToMaterialized 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 ViewSUnderlying 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 TheDbms_Mview Package

    Can Be Used With All Types Of Materialized Views

    Manual Refresh Procedures

    Dbms_Mview.Refresh(, )

    Dbms_Mview.Refresh_All_Mviews()

    Start With [Next] - Refreshes Start At A Specified Date/Time And Continue At RegularIntervals

    Create Materialized View Cust_Activity

    Build Immediate

    Refresh Fast On Commit

  • 8/12/2019 Sql_contents by Suneel

    38/40

    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 OrSession Based Data We Can Go For Global Temporary Table. We Have Two Options WhileCreating The Global Temporary Table.

  • 8/12/2019 Sql_contents by Suneel

    39/40

    1)On Commit Preserve Rows Clause Indicates Data Can Be Preserved For The Whole SessionUntil Close The Session

    2) On Commit Delete Rows Clause Indicates That The Data Should Be Deleted At The End OfThe 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 FunctionsRank Functions are Rank(), Dense_Rank() and Rownumber.

    Examples :

    Display 2ndhighest salary from emp table:

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

    Select empno,sal from (select empno,sal Dense_rank() over(order by sal desc) rfrom 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 likeSum,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

  • 8/12/2019 Sql_contents by Suneel

    40/40

    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