15368_lecture 15 to 23

download 15368_lecture 15 to 23

of 201

Transcript of 15368_lecture 15 to 23

  • 8/7/2019 15368_lecture 15 to 23

    1/201

    Data definition language

  • 8/7/2019 15368_lecture 15 to 23

    2/201

    Create table command

    It is used to define a new table

    Each column definition of a table has three

    parts:1. A name

    2. Data type

    3. size

  • 8/7/2019 15368_lecture 15 to 23

    3/201

    syntax

    Create table table_name(column1

    datatype(size),column2

    datatype(size), columnN

    datatype(size));

    Example:

    Create table student(roll_no number(10),

    name varchar(20), city varchar (20));

  • 8/7/2019 15368_lecture 15 to 23

    4/201

    How to display a table

    If we want to display the information about

    the columns defined in a table then we use

    following syntax:

    describe table-name;

    Example:

    describe student

  • 8/7/2019 15368_lecture 15 to 23

    5/201

    output

    Name Null? type

    Roll_no Number(10)

    Name Varchar(20)

    DOB date

    City Varchar(20)

    State Varchar(20)

  • 8/7/2019 15368_lecture 15 to 23

    6/201

    Constraints in create table command

    1. Primary key constraint

    2. Unique constraint

    3. Not-null constraint4. Foreign key constraint

    5. Check constraint

  • 8/7/2019 15368_lecture 15 to 23

    7/201

    Primary key constraint

    Primary key is applied to column so that this

    column can be used to uniquely identify each

    row in a table

    A table have only one primary key

    Primary key has following features:

    1. Prima

    ry key does not allow duplicate values

    2. It does not allow null values

  • 8/7/2019 15368_lecture 15 to 23

    8/201

    syntax

    Column_name datatype(size) Primary Key

    Example:

    create table student(Roll_no number(10) Primary Key,

    name var

    char

    (20) , city var

    char

    (20))OR

    Create table student(Roll_No number(10) , Namevarchar(20) , City varchar(20) , Primary Key(Roll_No));

    OR

    Create table student(Roll_NO number(10) , Namevarchar(20) city varchar(20) , Constraint PK PrimaryKey(roll_no));

  • 8/7/2019 15368_lecture 15 to 23

    9/201

    Unique constraint

    The unique constraint is used for the

    candidate key columns so that they contain

    the unique values for different entities.

    Unique constraint will not allow the duplicate

    values in the column to which they are

    attached

  • 8/7/2019 15368_lecture 15 to 23

    10/201

    Characteristics of unique key

    No allow duplicate values

    Can accept null values

    A table can have more than one unique key

  • 8/7/2019 15368_lecture 15 to 23

    11/201

    syntax

    Column_name datatype(size) Unique

    Example

    create table student( reg_no char(10) PrimaryKey , roll_no number(10) Unique , student_ID

    char(10) Unique , city varchar(20));

  • 8/7/2019 15368_lecture 15 to 23

    12/201

    Not null constraint

    It ensures that the table column will not left

    empty

    Syntax:column name datatype(size) Not Null

  • 8/7/2019 15368_lecture 15 to 23

    13/201

    Foreign key constraint

    The table in which foreign key is defined is

    called foreign table or detail table

    and the table whose prima

    ry key is

    refe

    renced

    by the foreign table is known as Master table

  • 8/7/2019 15368_lecture 15 to 23

    14/201

    characteristics

    It contain only those values that are present inthe primary key of master tabel

    Value in the foreign key can be null or duplicate

    values In foreign key if we insert a value which is not

    present in the primary key the oracle engine willreject the data

    A record in a master table cannot be deleted ifthe corresponding record in the foreign tableexist

  • 8/7/2019 15368_lecture 15 to 23

    15/201

    syntax

    column-name datatype(size)

    References

    Master-Table-name(column-name)

    Example:create table department( department_id char(10)

    Primary Key , department_name varchar(10));

    after creating the master table foreign table is created

    as:Create table course (course_id char(10) Primary Key,

    Dept_id varchar (20) Refrences department(dept_id));

  • 8/7/2019 15368_lecture 15 to 23

    16/201

    Check constraint

    Used to specify the data validation for a column

    Check constraint is a Boolean expression that is

    evaluated to either True or False

    Before inserting a value into the column (to which

    check constraint is attached ) oracle engine

    evaluates the Boolean condition

    If the condition evaluated is true then databaseaccepts the value othervise it do not accept the

    value

  • 8/7/2019 15368_lecture 15 to 23

    17/201

    syntax

    column-name datatype(size) Check (BooleanExpression)

    Example :

    suppose that in employee table the age ofemployee must be between 22 and 30

    syntax:

    create table Employee(emp_id char(10)Primary key , ename varchar (20), age number(10) check (age BETWEEN 22 and 30));

  • 8/7/2019 15368_lecture 15 to 23

    18/201

    Alter table command

    It is used to modify the structure of table

    which is already existing

  • 8/7/2019 15368_lecture 15 to 23

    19/201

    Adding new column to an existing

    table

    syntax:

    Alter table table-name ADD(col-name1

    datatype(size), column-name2datatype(size),.column-nameN

    datatype(size);

  • 8/7/2019 15368_lecture 15 to 23

    20/201

    Modifying an existing table

    Used to increase or decrease the column

    width and to change the datatype

    syntax:Alter table table-name MODIFY (column-name

    New-datatype(New Size));

    Example:Alter table Employee Modify(emp_id

    varchar(20));

  • 8/7/2019 15368_lecture 15 to 23

    21/201

    To add primary key

    Alter table table-name ADD Primary Key

    (column-name);

  • 8/7/2019 15368_lecture 15 to 23

    22/201

    Dropping the constraints

    To remove primary :

    Alter table table-name DROP constraint-name

  • 8/7/2019 15368_lecture 15 to 23

    23/201

    Dropping column from table

    Alter table table-name DROP column

    column-name;

  • 8/7/2019 15368_lecture 15 to 23

    24/201

    Drop table command

    DROP table table-name

  • 8/7/2019 15368_lecture 15 to 23

    25/201

    Rename command

    Use to change the name of existing table

    Syntax:

    Rename table-name TO New-table-name;

  • 8/7/2019 15368_lecture 15 to 23

    26/201

    Data manipulation language

    Used to access or manipulate the data values

    in the tables

  • 8/7/2019 15368_lecture 15 to 23

    27/201

    Insert command

    Used to insert data rows in a table

    We can either insert a row at a time or by

    inser

    ting the datar

    ows fr

    om alr

    eady existingtable

  • 8/7/2019 15368_lecture 15 to 23

    28/201

    syntax

    Insert into table-name (col-name1, col-

    nameN)values(value1,...,valueN);

    The number of values that appear in the

    parenthesis after the keyword values must

    match the number of columns in the list

  • 8/7/2019 15368_lecture 15 to 23

    29/201

    example

    Insert into Emp( emp_id , name , dept_name ,

    age , city , state)

    values(E1 , raj , mech , 26 , pune , MH);

    column name is optional

  • 8/7/2019 15368_lecture 15 to 23

    30/201

    For inserting data rows from another

    table

    Insert into table-name1

    select col-name1,, col-nameN

    From table-name2WHERE condition;

  • 8/7/2019 15368_lecture 15 to 23

    31/201

    UPDATE COMMAND

    Use to modify already existing data values

    It is use to update either

    1. All ther

    ows fr

    om a table2. A selected set ofrows from a table

    SYNTAX:

    Update table-name

    SET

    col-name1 = value1,., col-nameN= valueN

  • 8/7/2019 15368_lecture 15 to 23

    32/201

    example

    Change the city of each employee to

    Chandigarh

    Update EmpSET

    City = Chandigarh;

  • 8/7/2019 15368_lecture 15 to 23

    33/201

    Syntax for updating selected rows

    Update table-name

    SET

    Col-name1 = value1,., col-nameN = valueN

    WHERE condition;Example:

    Update Emp

    SET

    Age = 34

    Where ename =sunil ;

  • 8/7/2019 15368_lecture 15 to 23

    34/201

    DELETE COMMAND

    It is used to delete

    1. All the rows from a table

    2. A selected rows from a table

    Syntax for deleting all the rows

    Delete from table-name;

    for deleting specific rows

    Delete from Table-name

    Where codition;

  • 8/7/2019 15368_lecture 15 to 23

    35/201

    select

    Use to view orretrieve the rows from one or

    more tables

    Syntax:

    Select C1,C2.., Cn

    From R1,R2,..,RnWhere P;

  • 8/7/2019 15368_lecture 15 to 23

    36/201

    Use of select command

    To access all the rows and all the columns

    To access specific row and all the columns

    To access specific columns and all the rows To access specific row and specific column

  • 8/7/2019 15368_lecture 15 to 23

    37/201

    To access all the rows and all the

    columns

    Select * from table_name;

  • 8/7/2019 15368_lecture 15 to 23

    38/201

    To access specific columns

    select column-list

    from table_name;

  • 8/7/2019 15368_lecture 15 to 23

    39/201

    To access specific rows

    select * from table_name

    When condition;

  • 8/7/2019 15368_lecture 15 to 23

    40/201

    To access specific rows and specific

    columns

    select column-listfrom table_name

    where condition

  • 8/7/2019 15368_lecture 15 to 23

    41/201

    Select command with distinct clause

    select DISTINCT column-nameFrom table- name;

  • 8/7/2019 15368_lecture 15 to 23

    42/201

    Select command with order by clause

    select * from table-nameOrder By column-name Sort-order;

  • 8/7/2019 15368_lecture 15 to 23

    43/201

    Select command with arithmetic

    operator

    select column_name arithmetic operationfrom table-name

  • 8/7/2019 15368_lecture 15 to 23

    44/201

    Alias with select command

    Alias is used to rename the column while

    displaying the data . But the actual column

    name in the structure does not change

    SYNTAX:

    select column-name, alias-name

    from table name;

  • 8/7/2019 15368_lecture 15 to 23

    45/201

    Select command with between

    operator

    select * from table-nameWhere column-name BETWEEN LL AND UL;

  • 8/7/2019 15368_lecture 15 to 23

    46/201

    Select command with like operator

    To match the string patterns

    LIKE operator use two wild card character

    1. Percent(%) to match any string of any length2. Underscore(_) to match a single character

  • 8/7/2019 15368_lecture 15 to 23

    47/201

    example

    1. St% matches with any string starting with St

    2. %y matches with any string ends with y

    3. Mo_ _ _matches with any string started with

    Mo and has three letters after it4. _ _ _ _ _a matches with any string ending with

    a and has 5 letters before

    5. _ _ _ _ matches any four characters

    6. _ _% matches any string which is atleast twocharacters

  • 8/7/2019 15368_lecture 15 to 23

    48/201

    Cont..

    select * from table_name

    Where column-name LIKE R%;

  • 8/7/2019 15368_lecture 15 to 23

    49/201

    Select stmt with SET operation

    Union

    Syntax:

    Select-statement1UNION

    Select-statement2;

  • 8/7/2019 15368_lecture 15 to 23

    50/201

    intersect

    Select statement 1

    INTERSECT

    Select- statement 2

  • 8/7/2019 15368_lecture 15 to 23

    51/201

    Select command with dual table

    It is a small work-table

    It consist of only one row and one column

    The column name is Dand the value in thiscolumn is x

  • 8/7/2019 15368_lecture 15 to 23

    52/201

    example

    Query 1:

    Desc dual;

    Query 2:select * from dual;

    output: D

    x

  • 8/7/2019 15368_lecture 15 to 23

    53/201

    Example

    Select 4+4 from dual;

    output: 4+4

    8to view today's date

    select Sysdate from dual;

  • 8/7/2019 15368_lecture 15 to 23

    54/201

    Select command with aggregate

    functions

    Aggregate functions are the Oracle functions

    that takes collection of values as an input and

    produce a single value as an output

    1. Avg

    2. Min

    3. Max

    4. Sum

    5. Count

  • 8/7/2019 15368_lecture 15 to 23

    55/201

    Avg

    It calculates the average value of specified

    column

    Select AVG(column-name)

    from table-name;

  • 8/7/2019 15368_lecture 15 to 23

    56/201

    count

    Counts the number ofrows in a table

    1. count(*) , counts number ofrows in table

    including duplicate and null values

    2. Count(column-name) , counts the number

    ofrows in a table that have a non null value

    for specified column

  • 8/7/2019 15368_lecture 15 to 23

    57/201

    Select command with Group By clause

    This clause creates a data set that contain severalsets ofrecord grouped together based on acondition

    Syntax:select C1,C2,Cn

    Aggregate-function(column-name)

    From table-name

    Where condition

    Group By C1,C2,Cn;

  • 8/7/2019 15368_lecture 15 to 23

    58/201

  • 8/7/2019 15368_lecture 15 to 23

    59/201

    Example

    If we want to see that how many students are

    there in each branch

    Select br

    anch, count(r

    ollno) no. of studentsFrom student

    Group By branch;

  • 8/7/2019 15368_lecture 15 to 23

    60/201

    SELECT COMMAND WITHHAVING

    CLAUSE

    It is used to specify a condition on the Group byclause

    Having clause is equivalent to where cluaseexcept that it acts on the record set but not onthe individual record

    The main difference between where and havingclauses is that , the condition with where clauseis evaluated first and then it forms a group of

    rows which satisfy the conditionwhereas,condition with having class is evaluatedafter the groups are formed by group by clause

  • 8/7/2019 15368_lecture 15 to 23

    61/201

    To show how many students are in CSE

    branch

    Select branch, count(rollno) No. of Students

    From student

    Group By b

    ranch

    Having branch = CSE;

  • 8/7/2019 15368_lecture 15 to 23

    62/201

    Nested queries

    A query is a statement requesting the data

    from database . A query written inside

    another query is called sub-query.

    Nested query can be formed using:

    1. In connective

    2. Non in connective

    3. Exists

    4. Non exists

  • 8/7/2019 15368_lecture 15 to 23

    63/201

    Data control language

    It includes the commands that are related tothe security of database

    Database administrator grants and revokes the

    user privileges A user can be granted all the privileges or

    some specific privilege

    On an object user can perform only thoseoperations for which the privileges aregranted to him

  • 8/7/2019 15368_lecture 15 to 23

    64/201

    Various object privileges

    ALTER:

    DELETE

    INSERT SELECT

    UPDATE

    INDEX With grant option

  • 8/7/2019 15368_lecture 15 to 23

    65/201

    DCL commands

    syntax:Grant privileges

    ON object-name

    TO user-nameWITH GRANT OPTION;

  • 8/7/2019 15368_lecture 15 to 23

    66/201

    example

    To provide insert and select privilege

    SYNTAX: Grant insert, select

    On Employee

    To RAJ;

  • 8/7/2019 15368_lecture 15 to 23

    67/201

    To grant all the privileges

    SYNTAX:

    Grant All

    On Employee

    To SUNIL

  • 8/7/2019 15368_lecture 15 to 23

    68/201

    Revoke

    SYNTAX:

    Revoke privileges

    On object-name From user-name;

  • 8/7/2019 15368_lecture 15 to 23

    69/201

    Join

    When two tables get joined with the help of a

    column that have same data type and size in

    both the tables that relation is known as join

    With the use of Join we can access the data

    from multiple tables using single SQL

    statement

  • 8/7/2019 15368_lecture 15 to 23

    70/201

    SYNTAX

    select table1.column , table2.column

    from table1 , table2

    Wher

    e table1.column = table2.column;The above statement selects the rows of two

    tables , column for table1 and table2 must

    have same data type as well as size

  • 8/7/2019 15368_lecture 15 to 23

    71/201

    Types of join

    1. Cross join

    2. Inner join or equi join

    3. Outer

    join Left outer join

    Right outer join

    4. Self join

  • 8/7/2019 15368_lecture 15 to 23

    72/201

    Cross join

    It is also called as Cartesian product of two

    tables

    Cross join of two tables results in a new table

    which contain each and every possible

    combination ofrows of both the tables

    The resultant table may contain duplicate

    columns

    Thus cross join is usually not preferred

  • 8/7/2019 15368_lecture 15 to 23

    73/201

    syntax

    select table1.column , table2.column

    from table1 , table2;

    Cross join does not include the where clause in

    its syntax

    The above syntax is used when column name inboth the tables are same

  • 8/7/2019 15368_lecture 15 to 23

    74/201

    When the column name is different

    SYNTAX:

    select column1 , column2

    fr

    om table1, table2;

  • 8/7/2019 15368_lecture 15 to 23

    75/201

    Inner join

    It is also called EQUI join

    It is an improvement over cross join

    It include wher

    e clause in the select statement This is called equi join because condition

    under where clause uses the equality operator

    (=) to compare two values of table

  • 8/7/2019 15368_lecture 15 to 23

    76/201

    syntax

    select table1.column, table2.column

    from table1, table2

    wher

    e table1.column = table2.column;

  • 8/7/2019 15368_lecture 15 to 23

    77/201

    Cont..

    Equi join first perform the cross join on two

    tables and then shows only those rows which

    satisfies the condition under where clause

    If the where condition includes any operator

    except = then it is called as non-equality join

  • 8/7/2019 15368_lecture 15 to 23

    78/201

    Outer join

    The outer join is denoted by + operator

    The + operator add the missing rows from first

    table to the resultant table of inner join

    For that row the values for corresponding

    columns of second table may be null

  • 8/7/2019 15368_lecture 15 to 23

    79/201

    Types of outer join

    1. Left outer join

    Which includes all rows from first table

    Example: X = Y (+)2. Right outer join

    Which includes all the rows from second table

    Example: X(+) = Y

  • 8/7/2019 15368_lecture 15 to 23

    80/201

    Self join

    It is used to join the table itself

    It performs the join operation on two copies

    of same table

  • 8/7/2019 15368_lecture 15 to 23

    81/201

    VIEW

    It is an oracle object that is used to implementthe security

    A view is an imaginary table that is created

    from some other base table Through view a user may be allow to access

    specific column instead of accessing all thetables of database

    Purpose of view is to provide security to thedata by restricting the access to the base table

  • 8/7/2019 15368_lecture 15 to 23

    82/201

    Cont..

    Several views can be created from one base

    table

    A user working on a view is able to access only

    those columns of base table that are included

    in that view

    View act like a window to the base table from

    which it is created

  • 8/7/2019 15368_lecture 15 to 23

    83/201

    Types of views

    1. Read only view

    2. Updatable view

  • 8/7/2019 15368_lecture 15 to 23

    84/201

    Read only view

    This view is used only to view the data

    We are not allowed to do any changes in it

  • 8/7/2019 15368_lecture 15 to 23

    85/201

    Updatable view

    In which we can perform insert , delete ,

    update , and other operations

  • 8/7/2019 15368_lecture 15 to 23

    86/201

    Syntax for creating view

    create view view-name

    AS select column list

    From table-name

    Where condition;

  • 8/7/2019 15368_lecture 15 to 23

    87/201

  • 8/7/2019 15368_lecture 15 to 23

    88/201

    HOD

    Dept_id HOD_Name

    1 A

    2 B

    3 C

  • 8/7/2019 15368_lecture 15 to 23

    89/201

    Example of cross join

    Select Name , HOD_name

    From Department , HOD;

  • 8/7/2019 15368_lecture 15 to 23

    90/201

    output

    Name HOD_Name

    CSE A

    IT A

    ECE A

    ME A

    CSE B

    IT B

    ECE B

    ME B

    CSE C

    IT C

    ECE C

    ME C

  • 8/7/2019 15368_lecture 15 to 23

    91/201

    EXAMPLE OF INNER JOIN

    Show the name of departments and their

    respective HODs

    Select Name , HOD_Name

    From department , HOD

    Where department.dept_id = HOD.det_id;

  • 8/7/2019 15368_lecture 15 to 23

    92/201

    output

    Name HOD_Name

    CSE A

    IT B

    ECE C

  • 8/7/2019 15368_lecture 15 to 23

    93/201

  • 8/7/2019 15368_lecture 15 to 23

    94/201

  • 8/7/2019 15368_lecture 15 to 23

    95/201

    Example of self join

    ID NAME HOD

    1 W 2

    2 X

    3 Y 4

    4 Z

  • 8/7/2019 15368_lecture 15 to 23

    96/201

    Show the names ofHODs with their teachers

    Select a.name teacher , c.name HOD

    From teacher a , teacher cWhere a.hod = c.id;

    The above query creates two copies of tableteacher . The alias for first copy is a and alias forsecond copy is c

  • 8/7/2019 15368_lecture 15 to 23

    97/201

    output

    teacher HOD

    M N

    O P

  • 8/7/2019 15368_lecture 15 to 23

    98/201

    PL/SQL

    PL/SQL is a block structured query language

    which combines the features of SQL with

    procedural capabilities

  • 8/7/2019 15368_lecture 15 to 23

    99/201

    Disadvantages of SQL

    1. SQL cannot be used for programming

    because SQL does not provide the

    programming techniques of condition

    checking , looping and branching etc.

    2. SQL statements are passed to oracle engine

    one at a time which increases the traffic on

    the network which results in decrease ofspeed of data processing

  • 8/7/2019 15368_lecture 15 to 23

    100/201

    Cont

    3. On the occurrence of an error , the oracle

    engine displays its own error message . SQL

    does not allow the programmer to handle the

    errors

    To overcome above disadvantages of SQL ,

    PL/SQL came into existance

    /

  • 8/7/2019 15368_lecture 15 to 23

    101/201

    Advantages of PL/SQL

    1. PL/SQL has SQL features as well as

    procedural capabilities

    2. PL/SQL sends entire block of sql statements

    to oracle engine in one go ,thus reduces the

    network traffic and results in icrease of

    processing speed

    3. It allows the programmer to display userfriendly error-message

  • 8/7/2019 15368_lecture 15 to 23

    102/201

    Cont

    PL/SQL programs are portable i.e. , these can

    run on any computer hardware and operating

    system where oracle is installed

    f / d

  • 8/7/2019 15368_lecture 15 to 23

    103/201

    Structure of PL/SQL Code BLOCK

    A PL/SQL code block is divided into four

    sections :

    1. Declare section

    2. Begin section

    3. Exception section

    4. End section

  • 8/7/2019 15368_lecture 15 to 23

    104/201

    structure

    DECLARE

    variable and constant declarations

    BEGIN

    SQL and PL statements

    EXCEPTION

    Err

    or

    handling statementsEND;

    DECLARE i

  • 8/7/2019 15368_lecture 15 to 23

    105/201

    DECLARE section

    Every code block starts with a declare section

    It is used to declare and initialize variables

    This section is optional

    BEGIN

  • 8/7/2019 15368_lecture 15 to 23

    106/201

    BEGIN

    It is an executable section which contain the

    SQL and PL/SQL executable statements

    It is compulsory section

    This section includes all the data

    manipulations, data retrieval , branching and

    looping construct

    E i

  • 8/7/2019 15368_lecture 15 to 23

    107/201

    Exception

    It contains the user defined error handler

    This section is executed only when an error

    occures

    E d ti

  • 8/7/2019 15368_lecture 15 to 23

    108/201

    End section

    This section indicates the end of a code block

    F d t l f PL/SQL

  • 8/7/2019 15368_lecture 15 to 23

    109/201

    Fundamentals of PL/SQL

    Fundamentals of PL/SQL includes:

    1. Character set

    2. Operators

    3. Literals4. Variables and consonants

    5. Data types

    6. Declarations

    7. Assignment8. comments

  • 8/7/2019 15368_lecture 15 to 23

    110/201

    t

  • 8/7/2019 15368_lecture 15 to 23

    111/201

    operators

    Operators can be classified into three groups

    1. Arithmetic operators

    2. Logical operators

    3.C

    omparison ope

    rato

    rs4. Literals:

    numeric literals

    character

    stringboolean

    V i bl d t t

  • 8/7/2019 15368_lecture 15 to 23

    112/201

    Variables and constants

    Variable in PL/SQL is a named variable used to holdsome data values

    Variable must start with a character and can befollowed by maximum of 29 other characters

    Reserved words cannot be used as a variable name

    Constant declaration is similar to variable declarationexcept that keyword constant is added to variablename and a value is assigned immediately

    Ones a constant is de3clared no other assignment tothe constants is possible

  • 8/7/2019 15368_lecture 15 to 23

    113/201

    d l ti

  • 8/7/2019 15368_lecture 15 to 23

    114/201

    declarations

    Before a variable can be used in the begin section, it must be declared in the DECLARE section

    SYNTAX:

    variable-name datatype(size);EXAMPLE:

    Age Number(5);

    A number(10,2);

    Name Varchar2(20);

    DOB Date;

    Declaring constants

  • 8/7/2019 15368_lecture 15 to 23

    115/201

    Declaring constants

    SYNTAX:

    variable-name constant datatype(size) := value;

    EXAMPLE:

    Pi constant number(4,2) := 3.14;

  • 8/7/2019 15368_lecture 15 to 23

    116/201

    Example using assignment operator

  • 8/7/2019 15368_lecture 15 to 23

    117/201

    Example using assignment operator

    A := 10;

    B := c+d;

    USING SELECT INTO CLAUSE

    Select salary into sal from employee where

    empid = 12;

    comments

  • 8/7/2019 15368_lecture 15 to 23

    118/201

    comments

    Single line: begins with double hyphen(--)

    Multiline: begins with a (/*) and ends with

    (*/)

    How to read value during runtime

  • 8/7/2019 15368_lecture 15 to 23

    119/201

    How to read value during runtime

    The symbol & is used to assign the value to

    the variable during runtime

    FOR EXAMPLE consider the num variable , to

    read the value for this variable during runtimefollowing statement can be used:

    Num := #

    Cont

  • 8/7/2019 15368_lecture 15 to 23

    120/201

    Cont..

    When the program will execute the system

    will ask to enter the value and user can enter

    any value

    Enter the value of Num: 10

    the value 10 is substituted at the place of

    &Num

    Num := 10;

    Displaying user message on the screen

  • 8/7/2019 15368_lecture 15 to 23

    121/201

    Displaying user message on the screen

    To display the message , the SERVEROUTPUT

    should be set ON.

    SYNTAX:

    SQL> SET SERVEROUTPUT ON;

    Now we can display any message using

    DBMS_OUTPUT.PUT_LINE (hello);

    Basic PL/SQL programs

  • 8/7/2019 15368_lecture 15 to 23

    122/201

    Basic PL/SQL programs

    Write a PL/SQL code block to display the

    message , hello.

    Declare

    Begin

    dbms_output.put_line(hello);

    END;

    To add two numbers

  • 8/7/2019 15368_lecture 15 to 23

    123/201

    To add two numbers

    Declarea number(2);

    b number(2);

    c number(2);

    Begin

    a:=5;

    b:= 4;

    C:= a+b;

    Dbms_output.put_line(sum=||c);

    END;

  • 8/7/2019 15368_lecture 15 to 23

    124/201

    Conditional control

  • 8/7/2019 15368_lecture 15 to 23

    125/201

    Conditional control

    IF-THEN

    IF-THEN-ELSE

    IF-THEN-ELSEIF

    IF THEN

  • 8/7/2019 15368_lecture 15 to 23

    126/201

    IF THEN

    IF condition then

    sequence of statement;

    END IF;

    IF THEN ELSE

  • 8/7/2019 15368_lecture 15 to 23

    127/201

    IF THEN ELSE

    If condition then

    statements1;

    ELSE

    statements2;

    END IF;

    If-then-elseif

  • 8/7/2019 15368_lecture 15 to 23

    128/201

    If-then-elseif

    IF condition1 THEN

    statements1;

    ELSIF condition2 THEN

    statement2;

    ELSE

    Statement3;

    END IF;

    Iterative control

  • 8/7/2019 15368_lecture 15 to 23

    129/201

    Iterative control

    LOOP

    WHILE-LOOP

    FOR-LOOP

    loop

  • 8/7/2019 15368_lecture 15 to 23

    130/201

    loop

    The keyword LOOP is placed before the first

    statement in the sequence and the keyword

    END LOOP after the last statement in the

    sequence To exit from the loop EXIT-WHEN statement

    can be used

    syntax

  • 8/7/2019 15368_lecture 15 to 23

    131/201

    syntax

    LOOP

    sequence of statements;

    EXIT WHEN condition;

    END LOOP;

    The loop will complete when the condition under

    EXIT-WHEN clause is true

    If the condition is omitted from the above syntax,then the loop will terminate unconditionally

    EXAMPLE

  • 8/7/2019 15368_lecture 15 to 23

    132/201

    EXAMPLE

    Write a program to display number from 1to 10Declare

    i number (2);

    Begin

    i:= 1;LOOP

    dbms_output.put_line(i);

    i:=i+1;

    EXIT WHEN i>=10;

    END LOOP;

    END;

    While loop

  • 8/7/2019 15368_lecture 15 to 23

    133/201

    While loop

    Syntax:

    WHILE condition LOOP

    sequence-of-statements;

    END LOOP;

    Cont

  • 8/7/2019 15368_lecture 15 to 23

    134/201

    Cont

    Before executing the sequence of statements ,the condition is evaluated.

    If it results in TRUE , then the body of loop isexecuted and the control goes to the top of theloop.

    Thus the body of loop is executed each time thecondition is TRUE.

    When the condition becomes FALSE, the bodywill no get executed and the control goes to thestatement immediate below the loop.

    example

  • 8/7/2019 15368_lecture 15 to 23

    135/201

    example

    Write a program to print square of numbers from 1 to 10.Declare

    a number(2);

    Begin

    a:=1;WHILE a

  • 8/7/2019 15368_lecture 15 to 23

    136/201

    For loop

    The FOR-LOOP statement is used to specify a

    range of integers and then executes a

    sequence of statements, once for each integer

    in the range Unlike WHILE-LOOP, the number of iterations

    through a FOR loop is known before the loop

    is entered

  • 8/7/2019 15368_lecture 15 to 23

    137/201

    Cont..

  • 8/7/2019 15368_lecture 15 to 23

    138/201

    Cont..

    The lower and upper bounds are the integervalues separated by double dot(..) and specifya range.

    As long as the value of variable counterliesbetween the specified ranges, the sequence ofstatements keep on executing.

    The FOR loop initialize and increment the

    counter automatically Keyword REVERSE is optional

    Cont..

  • 8/7/2019 15368_lecture 15 to 23

    139/201

    Cont..

    If the reverse option is not used then, thevariable counter is assigned values ranging fromlower bound to upper bound

    EXAMPLE:

    FOR counter IN 1..5

    LOOP

    sequence- of-statements;

    END LOOP;

    Here, counter is assigned values 1,2,3,4,5.

    Cont..

  • 8/7/2019 15368_lecture 15 to 23

    140/201

    Cont..

    If REVERSE option is used then, counter isassigned values ranging from upper bound tolower bound

    EXAMPLE:

    FOR counter IN REVERSE 1..5

    LOOP

    sequence of statements;

    END LOOP;

    Here counter is assigned values 5,4,3,2,1.

    EXAMPLE

  • 8/7/2019 15368_lecture 15 to 23

    141/201

    EXAMPLE

    Write a PL/SQL block to display the table of 2DECLARE

    Total number(4);

    i number(2);

    BEGINFOR i IN 1..10

    LOOP

    total:=2*I;

    dbms_output.put_line(2*||i||=||tatal);

    END LOOP;

    END;

    Sequence control

  • 8/7/2019 15368_lecture 15 to 23

    142/201

    Sequence control

    GOTO statement transfer the flow of control

    to a specified label unconditionally.

    The label is marked using tags .

    Labelname is a user defiened name and it can

    appear either above or below the GOTO

    statement.

    SYNTAX

  • 8/7/2019 15368_lecture 15 to 23

    143/201

    GOTO label-name;

    Example

  • 8/7/2019 15368_lecture 15 to 23

    144/201

    p

    Write a program to find the larger of two numbers using GOTO statement.DECLARE

    num1 number(2);

    num2 number(2);

    BEGIN

    num1:=&num1;

    num2:=&num2;

    IF num1>num2 THEN

    GOTO O1;

    ELSE

    GOTO O2;

    END IF;

    dbms_output.put_line(g reater is num1 = ||num1);

    GOTO O3;

    dbms_output.put_line(g reater is num2 = ||num2);

    dbms_output.put_line(SU CCESSFULLY);

    END;

    DATABASE TRIGGERS

  • 8/7/2019 15368_lecture 15 to 23

    145/201

    It is the stored procedure that is automatically

    executed in response to certain events on a

    particular table or view in a database.

    An event on a table can be INSERT, DELETE, orUPDATE statement on the table

  • 8/7/2019 15368_lecture 15 to 23

    146/201

  • 8/7/2019 15368_lecture 15 to 23

    147/201

    Triggering event or statement

  • 8/7/2019 15368_lecture 15 to 23

    148/201

    gg g

    It is an SQL statement that makes a trigger to fire

    There are typically three triggering events thatcauses trigger to fire:

    1. INSERT event(when a new record is beinginserted into table).

    2. UPDATE event(when a record is being changedin a table).

    3. DELETE event(when a record is being deletedfrom a table) .

    Triggerrestriction

  • 8/7/2019 15368_lecture 15 to 23

    149/201

    gg

    It is a Boolean expression that must be truefor a trigger to fire

    When an event occurs and Triggerrestriction

    is evaluated to true then, only the t

    rigge

    rwillfire

    But if Triggerrestriction evaluated to be false,the Trigger will not fire

    A Triggerrestriction is specified using WHENclause

    TRIGGER ACTION

  • 8/7/2019 15368_lecture 15 to 23

    150/201

    It is a PL/SQL code which is executed when an

    event occurs and triggerrestriction is

    evaluated to TRUE

    Types of triggers

  • 8/7/2019 15368_lecture 15 to 23

    151/201

    yp gg

    1. ROW triggers:

    A ROW trigger is fired for each row affected by a

    triggering statement

    Statement trigger

  • 8/7/2019 15368_lecture 15 to 23

    152/201

    gg

    Statement trigger is fired once for a triggering

    statement, regardless of the no. ofrows

    affected by triggering statement

    Classification on the basis of execution

    time

  • 8/7/2019 15368_lecture 15 to 23

    153/201

    time

    BEFORE trigger

    AFTER trigger

    BEFORE trigger

  • 8/7/2019 15368_lecture 15 to 23

    154/201

    It executes its trigger action before the

    triggering statement

    It can be used when the trigger action must be

    executed before the triggering statementcompletes

    AFTER triggers

  • 8/7/2019 15368_lecture 15 to 23

    155/201

    Executes the trigger action after triggering

    statement is executed

    It can be used when the triggering statement

    must be executed before executing the triggeraction

  • 8/7/2019 15368_lecture 15 to 23

    156/201

    EXAMPLE

  • 8/7/2019 15368_lecture 15 to 23

    157/201

    Write a prog to create a trigger which will tell

    about the operation performed on the

    student table

    program

  • 8/7/2019 15368_lecture 15 to 23

    158/201

    Create or Replace Trigger OprBefore INSERT or UPDATE or DELETE

    ON STUDENT

    BEGIN

    IF INSERTING THEN

    dbms_output.put_line(Operation performed is INSERT);

    ELSE UPDATING THENdbms_output.put_line(Operation performed is update);

    ELSE

    dbms_output.put_line(Operation performed is DELETE);

    END IF;

    END;

    Enabling or Disabling Triggers

  • 8/7/2019 15368_lecture 15 to 23

    159/201

    For disabling the trigger:

    SQL> ALTER TRIGGER TRIGGERNAME Disable;

    Example:

    SQL> Alter Trigger check Disable;

    Cont..

  • 8/7/2019 15368_lecture 15 to 23

    160/201

    For enabling trigger

    Syntax:

    SQL> Alter Trigger TriggerName Enable;

    Disabling all the triggers of table at once:

    Syntax:

    SQL> ALTER Table TableName Disable All

    Triggers;

    Dropping a trigger

  • 8/7/2019 15368_lecture 15 to 23

    161/201

    Drop Trigger TriggerName;

  • 8/7/2019 15368_lecture 15 to 23

    162/201

    Steps needs to work with cursor

  • 8/7/2019 15368_lecture 15 to 23

    163/201

    Declare a cursor

    Open a cursor

    Fetch orread from cursor

    Close a cursor

    Types of cursor

  • 8/7/2019 15368_lecture 15 to 23

    164/201

    Implicit cursor

    Explicit cursor

    Implicit cursor

  • 8/7/2019 15368_lecture 15 to 23

    165/201

    It is a work area that is declared, opened and

    closed internally by the oracle engine

    The user is not involved in managing the

    cursor

    PL/SQL declares a cursor implicitly for all SQL

    data manipulation statements

    Explicit cursor

  • 8/7/2019 15368_lecture 15 to 23

    166/201

    It is a work area that is declared, opened and

    closed externally by the user

    It is also called USER-DEFINED cursor

    It is declared in the DECLARE part of PL/SQLblock

    Attributes of cursor

  • 8/7/2019 15368_lecture 15 to 23

    167/201

    To keep track of current status of cursor,

    PL/SQL uses some attributes which are

    common to both implicit and explicit cursor

    ATTRIBUTES

  • 8/7/2019 15368_lecture 15 to 23

    168/201

    Attribute Meaning

    %ISOPEN Returns TRUE if cursor is open,

    FALSE otherwise.

    %FOUND Returns TRUE ifrecord was

    fetched successfully, FALSE

    otherwise.

    %NOTFOUND Returns TRUE ifrecord was not

    fetched successfully, FALSE

    otherwise

    %ROWCOUNT Returns number ofrecords

    processed from cursor

    Implicit cursor

  • 8/7/2019 15368_lecture 15 to 23

    169/201

    Implicit cursor attributes are used to access

    the information about the status of last

    INSERT, UPDATE, and DELETE or single row

    select statement Implicit cursor uses same set of general

    attributes but proceeded with cursor name

    i.e., SQL.

    Implicit cursor attributes

  • 8/7/2019 15368_lecture 15 to 23

    170/201

    SQL%ISOPEN

    This is always return FALSE because the oracle

    engine closes the implicit cursor automatically

    after executing SQL statement.

    EXAMPLE

  • 8/7/2019 15368_lecture 15 to 23

    171/201

    Write a PL/SQL block to display a message that whether arecord is updated or not using SQL%FOUND andSQL%NOTFOUND.

    BEGIN

    Update student set city = pune where rollno=&rollno;

    IF SQL%FOUND THENdbms_output.put_line(record updated);

    END IF;

    IF SQL%NOTFOUND THEN

    dbms_output.put_line(record not updated);END IF;

    END

    To count number ofrows affected by

    update statement

  • 8/7/2019 15368_lecture 15 to 23

    172/201

    update statement

    DECALREnum number(2);

    BEGIN

    Update student set grade = b wheregrade=c;

    num := SQL%ROWCOUNT;

    dbms_output.put_line(Row affected = num);END;

    Explicit cursor

  • 8/7/2019 15368_lecture 15 to 23

    173/201

    When a query returns multiple rows, user canexplicitly declare a cursor to process the rows

    It is declared in the DECLARE section of

    PL/SQL block All the general attributes of a cursor are

    applicable to this cursor

    Steps in handling explicit cursor

  • 8/7/2019 15368_lecture 15 to 23

    174/201

    Explicit cursor handling needs following steps tobe followed:

    1. Declare the cursor in DECLARE part of PL/SQLblock

    2. Open the cursor3. Using a loop, fetch data from cursor one row at

    a time into memory variables and process thedata stored in the memory variable as required

    4. EXIT f rom loop when processing is complete5. CLOSE the cursor

    Declaring a cursor

  • 8/7/2019 15368_lecture 15 to 23

    175/201

    A cursor must be declared before referencingin other statement

    When cursor is declared , it is given a name

    and is associated with a specific query

    syntax

  • 8/7/2019 15368_lecture 15 to 23

    176/201

    CursorCursorName IS SELECT statement;

    EXAMPLE:

    CursorC IS SELECT rollno from student

    where id = 102;

    Opening a cursor

  • 8/7/2019 15368_lecture 15 to 23

    177/201

    Opening a cursor executes the query andidentifies the result set, which consist of all

    the rows that meet the query search criteria

    SYNTAX:Open CursorName;

    Fetching record from cursor

  • 8/7/2019 15368_lecture 15 to 23

    178/201

    After opening a cursor, FETCH statement isused to load the rows from the result set into

    the memory variable but, one row at a time

    SYNTAX:FETCHCursorName INTO variables;

    EXAMPLE:

    FETCHC INTO rollno, name;

    Closing a cursor

  • 8/7/2019 15368_lecture 15 to 23

    179/201

    It disable the cursor and the result setbecomes undefined

    Once a cursor is closed it can be reopen again

    SYNTAX:

    CLOSE CursorName;

    Write a prog to display the name of

    the student belonging to CSE branch

  • 8/7/2019 15368_lecture 15 to 23

    180/201

    g g

    DECLARECURSOR C IS select name from student where branch = cse;

    BEGIN

    Open C;

    LOOPFetch C into name;

    EXIT When C%NOTFOUND;

    dbms_output.put_line(name);

    END LOOP;

    Close C;END;

    subprograms

  • 8/7/2019 15368_lecture 15 to 23

    181/201

    The named PL/SQL code blocks that can accept

    parameters and can be invoked are called

    SUBPROGRASMS

    types

  • 8/7/2019 15368_lecture 15 to 23

    182/201

    Procedures

    functions

    procedure

  • 8/7/2019 15368_lecture 15 to 23

    183/201

    A procedure or a function is a group of SQLand PL/SQL statements that is used to performa specific task.

    Basically procedure is used to perform anaction where as function is used to compute avalue.

    Another difference is that procedure may

    return no value but function must return avalue

    Stored procedure

  • 8/7/2019 15368_lecture 15 to 23

    184/201

    It is a procedure that has been compiled andstored in any of the oracle engines system

    table

    The basic purpose of subprograms is toachieve:

    1. Modularity

    2. reusability

    modularity

  • 8/7/2019 15368_lecture 15 to 23

    185/201

    It allow the programmer to divide a programinto more than one well defined unit calledMODULES

    Modularity results in:

    1. Extensibility, which enables us to create newmodules without affecting the existingmodules

    2. Maintainability, which makes the modules tobe managed easily.

    Reusability

  • 8/7/2019 15368_lecture 15 to 23

    186/201

    It enables a subprogram to be used in anynumber of applications

    Creating procedures

  • 8/7/2019 15368_lecture 15 to 23

    187/201

    DECLAREglobal variable declaration;

    procedure procedureName

    (argument IN/OUT datatype,)

    IS/AS

    variable and const declaration;

    BEGIN PL/SQL statements;

    EXCEPTION

    exception handling statements;

    END ProcedureName;

    BEGIN

    executable statements;

    procedure calling;

    EXCEPTION

    END

    To multiply two numbers using

    procedure

  • 8/7/2019 15368_lecture 15 to 23

    188/201

    DECLARENum1 Number(2);

    Num2 Number(2);

    Mul Number(4);

    Procedure multiplication(Num1 IN Number, Num2 IN Number, Mul OUTNumber) IS

    BEGIN

    Mul:=Num1*Num2;

    End Multiplication;

    Begin

    Num1:=&Num1

    Num2:=&Num2

    Multiplication(Num1,Num2,Mul);..procedure calling

    dbms_output.put_line(Mul);

    END

    Creating a stored procedure

  • 8/7/2019 15368_lecture 15 to 23

    189/201

    Create Or Replace Procedure ProcedureName(Argument IN/OUT/IN OUT Datatype,..)

    IS/AS

    Variable and constant declaration;

    Begin

    PL/SQL statements;

    Exception

    exception handling statement;End;

    Stored procedure to add two numbers

  • 8/7/2019 15368_lecture 15 to 23

    190/201

    Create Or Replace Procedure Addition(Num1IN Number, Num2 IN Number, Sum OUT

    Number)IS

    BeginSum:=Num1+Num2;

    End;

    Display sum of two numbers by calling

    the addition stored procedure

  • 8/7/2019 15368_lecture 15 to 23

    191/201

    DeclareNum1 Number(2);

    Num2 Number(2);

    Sum Number(2);

    Begin

    Num1:=&Num1;

    Num2:=&Num2;

    Addition(Num1,Num2,Sum);

    dbms_output.put_line(Addition is||Sum);

    End;

    Creating a function

  • 8/7/2019 15368_lecture 15 to 23

    192/201

    DeclareGlobal Variable Declaration;

    Function FunctionName

    (Argument IN Datatype,..)

    Return DataType

    IS/AS

    var

    and const declar

    ation;Begin

    PL/SQL Statements;

    Exception

    End FunctionName;

    Begin

    executable statements;

    Function calling;

    End;

    Deleting stored procedure

  • 8/7/2019 15368_lecture 15 to 23

    193/201

    Drop Procedure ProcedureName;

    packages

  • 8/7/2019 15368_lecture 15 to 23

    194/201

    A package is an oracle object which is used tobundle various objects like variables,

    constants, cursor and subprograms

    A package has two parts:

    1. Package specification

    2. Package body

    Cont..

  • 8/7/2019 15368_lecture 15 to 23

    195/201

    Specification declares the variables, constants,cursors and subprograms

    Body defines cursor and subprograms and

    thus implement the specification

  • 8/7/2019 15368_lecture 15 to 23

    196/201

    Creating a package

  • 8/7/2019 15368_lecture 15 to 23

    197/201

    Package Specification

    Create Or Replace Package PackageName AS

    Function FunctionName(Arg List)Return

    Datatype;

    Procedure ProcedureName(Arg list);

    End PackageName;

    Package body

  • 8/7/2019 15368_lecture 15 to 23

    198/201

    Create O

    rReplace Package Body PackageName ASFunction FunctionName(Arg list)Retrn Datatype

    IS/AS

    var and const declaration;

    Begin

    pl/sql statements;

    Exception

    Exception handling statements;

    End FunctionName;

    Procedure ProcedureName(arg list)IS/AS

    variable and const declaration;

    Begin

    pl/sql statements;

    Exception

    End ProcedureName;

    End PackageName;

    Calling objects of package

  • 8/7/2019 15368_lecture 15 to 23

    199/201

    To call either a function or a procedurecontained in a package , dot(.) notation is used

    as follows:

    Syntax:PackageName.FunctionName(actual arg);

    PackageName.ProcedureName(actual arg);

    Deleting a package

  • 8/7/2019 15368_lecture 15 to 23

    200/201

    Drop Package PackageName;

  • 8/7/2019 15368_lecture 15 to 23

    201/201