dbms complete

Upload: ishant-bhalla

Post on 02-Jun-2018

239 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 Dbms Complete

    1/65

    Jatin Bhatia, 10165

    Experiment 1

    Aim: Describe Data Base Management System.

    DBMS (Data Base Management System):Is a system or computer software that is

    designed for the purpose to manage information or databases in such way so that data

    storage and retrieval of information gets easy, so we can easily say that DBMS defines

    what will be the structure for information storage and in addition to it facilitates in data

    manipulation. The common examples of Data Base Management Systems are Microsoft

    Access, DB2, Oracle, SQL Server etc. There are some common goals while using

    DBMS.

    (1) Security.

    (2) Backup and Replication.

    (3) Change and Access Logging.

    (4) Automated Optimization.

    (5) Policy Enforcement.

    (6) Query Ability.

    (7) Meta Data Repository.

    (8) Computation.

    There are three most commonly used database models.

    (1) Hierarchal: A hierarchical database model is adata model in which the data isorganized into atree-like structure. The structure allows representing information using

    parent/child relationships: each parent can have many children, but each child has only

    one parent (also known as a 1-to-many relationship). All attributes of a specific record

    are listed under an entity type.

    (2) Network:The network structure consists of more complex relationships. Unlike the

    hierarchical structure, it can relate to many records and accesses them by following one

    of several paths. In other words, this structure allows for many-to-many relationships.

    (3) Relational:The relational structure is the most commonly used today. It is used by

    mainframe, midrange and microcomputer systems. It uses two-dimensional rows and

    columns to store data. The tables of records can be connected by common key values.

    The model is not easy for the end user to run queries with because it may require a

    complex combination of many tables.

    http://en.wikipedia.org/wiki/Data_modelhttp://en.wikipedia.org/wiki/Tree_data_structurehttp://en.wikipedia.org/wiki/Tree_data_structurehttp://en.wikipedia.org/wiki/Data_model
  • 8/11/2019 Dbms Complete

    2/65

    Jatin Bhatia, 10165

    Advantages of DBMS over File Processing System:

    The DBMS has a number of advantages as compared to traditional computer file

    processing approach.

    1. Controlling Data Redundancy:In non-database systems (traditional computer file processing), each application programhas its own files. In this case, the duplicated copies of the same data are created at many

    places. In DBMS, all the data of an organization is integrated into a single database. Thedata is recorded at only one place in the database and it is not duplicated. For example,

    the dean's faculty file and the faculty payroll file contain several items that are identical.

    When they are converted into database, the data is integrated into a single database sothat multiple copies of the same data are reduced to-single copy.

    In DBMS, the data redundancy can be controlled or reduced but is not removed

    completely. Sometimes, it is necessary to create duplicate copies of the same data itemsin order to relate tables with each other. By controlling the data redundancy, you can save

    storage space. Similarly, it is useful for retrieving data from database using queries.

    2. Data Consistency:By controlling the data redundancy, the data consistency is obtained. If a data item

    appears only once, any update to its value has to be performed only once and the updatedvalue (new value of item) is immediately available to all users.

    If the DBMS has reduced redundancy to a minimum level, the database system enforces

    consistency. It means that when a data item appears more than once in the database and isupdated, the DBMS automatically updates each occurrence of a data item in the database.

    3. Data Sharing:In DBMS, data can be shared by authorized users of the organization. The DBA manages

    the data and gives rights to users to access the data. Many users can be authorized toaccess the same set of information simultaneously. The remote users can also share same

    data. Similarly, the data of same database can be shared between different application

    programs.

    4. Data Integration:In DBMS, data in database is stored in tables. A single database contains multiple tablesand relationships can be created between tables (or associated data entities). This makes

    easy to retrieve and update data.

  • 8/11/2019 Dbms Complete

    3/65

    Jatin Bhatia, 10165

    5. Integrity Constraints:Integrity constraints or consistency rules can be applied to database so that the correctdata can be entered into database. The constraints may be applied to data item within a

    single record or they may be applied to relationships between records.

    Examples:

    The examples of integrity constraints are:

    (i) 'Issue Date' in a library system cannot be later than the corresponding 'Return Date' ofa book.

    (ii) Maximum obtained marks in a subject cannot exceed 100.

    (iii) Registration number of BCS and MCS students must start with 'BCS' and 'MCS'respectively etc.

    There are also some standard constraints that are intrinsic in most of the DBMSs. Theseare;

    Constraint Name Description

    PRIMARY KEY Designates a column or combination of columns as

    Primary Key and therefore, values of columns cannot be

    repeated or left blank.

    FOREIGN KEY Relates one table with another table.

    UNIQUE Specifies that values of a column or combination of

    columns cannot be repeated.

    NOT NULL Specifies that a column cannot contain empty values.CHECK Specifies a condition which each row of a table must

    satisfy.

    6. Data Security:Data security is the protection of the database from unauthorized users. Only the

    authorized persons are allowed to access the database. Some of the users may be allowedto access only a part of database i.e., the data that is related to them or related to their

    department. Mostly, the DBA or head of a department can access all the data in the

    database. Some users may be permitted only to retrieve data, whereas others are allowed

    to retrieve as well as to update data. The database access is controlled by the DBA. Hecreates the accounts of users and gives rights to access the database. Typically, users or

    group of users are given usernames protected by passwords.

    Most of the DBMSs provide the security sub-system, which the DBA uses to createaccounts of users and to specify account restrictions. The user enters his/her account

    number (or username) and password to access the data from database. For example, ifyou have an account of e-mail in the "hotmail.com" (a popular website), then you have to

  • 8/11/2019 Dbms Complete

    4/65

  • 8/11/2019 Dbms Complete

    5/65

    Jatin Bhatia, 10165

    and it can be modified very easily. The created reports are also saved along with database

    and behave like a software component.

    12. Control Over Concurrency:

    In a computer file-based system, if two users are allowed to access data simultaneously, itis possible that they will interfere with each other. For example, if both users attempt to

    perform update operation on the same record, then one may overwrite the values recordedby the other. Most DBMSs have sub-systems to control the concurrency so that

    transactions are always recorded" with accuracy.

    13. Backup and Recovery Procedures:In a computer file-based system, the user creates the backup of data regularly to protect

    the valuable data from damaging due to failures to the computer system or applicationprogram. It is a time consuming method, if volume of data is large. Most of the DBMSs

    provide the 'backup and recovery' sub-systems that automatically create the backup ofdata and restore data if required. For example, if the computer system fails in the middle

    (or end) of an update operation of the program, the recovery sub-system isresponsible formaking sure that the database is restored to the state it was in before the program started

    executing.

    14. Data Independence:The separation of data structure of database from the application program that is used to

    access data from database is called data independence. In DBMS, database and

    application programs are separated from each other. The DBMS sits in between them.You can easily change the structure of database without modifying the application

    program. For example you can modify the size or data type of a data items (fields of a

    database table). On the other hand, in computer file-based system, the structure of dataitems are built into the individual application programs. Thus the data is dependent on the

    data file and vice versa.

    15. Advanced Capabilities:DBMS also provides advance capabilities for online access and reporting of data through

    Internet. Today, most of the database systems are online. The database technology is used

    in conjunction with Internet technology to access data on the web servers.

    Disadvantages of Database Management System (DBMS):

    Although there are many advantages but the DBMS may also have some minor

    disadvantages. These are:

  • 8/11/2019 Dbms Complete

    6/65

    Jatin Bhatia, 10165

    1. Cost of Hardware & Software:A processor with high speed of data processing and memory of large size is required to

    run the DBMS software. It means that you have to upgrade the hardware used for file-

    based system. Similarly, DBMS software is also very costly.

    2. Cost of Data Conversion:When a computer file-based system is replaced with a database system, the data storedinto data file must be converted to database files. It is difficult and time consuming

    method to convert data of data files into database. You have to hire DBA (or databasedesigner) and system designer along with application programmers; Alternatively, you

    have to take the services of some software houses. So a lot of money has to be paid fordeveloping database and related software.

    3. Cost of Staff Training:Most DBMSs are often complex systems so the training for users to use the DBMS isrequired. Training is required at all levels, including programming, application

    development, and database administration. The organization has to pay a lot of amounton the training of staff to run the DBMS.

    4. Appointing Technical Staff:The trained technical persons such as database administrator and application

    programmers etc are required to handle the DBMS. You have to pay handsome salaries to

    these persons. Therefore, the system cost increases.

    5. Database Failures:In most of the organizations, all data is integrated into a single database. If database is

    corrupted due to power failure or it is corrupted on the storage media, then our valuable

    data may be lost or whole system stops.

  • 8/11/2019 Dbms Complete

    7/65

    Jatin Bhatia, 10165

    Experiment 2

    AIM: To create a table in SQL.

    Theory:SQL stands for Structured Query Language. SQL lets you access andmanipulate databases using various commands with a particular syntax.The query and

    update commands form the DML part of SQL:

    SELECT - extracts data from a database

    The most important DDL statements in SQL are:

    CREATE DATABASE - creates a new database

    CREATE TABLE - creates a new table

    ALTER TABLE - modifies a table

    DROP TABLE - deletes a table

    SYNTAX:

    Create table syntax:

    CREATE TABLE table_name

    (

    column_name1 data_type constraint1,column_name2 data_type constraint2,

    column_name3 data_type constraint3,

    ....)

    *constraint field are optional.

    View created table:

    To view the table to be created we use Des command.

    Desc table_name;

    Project for Management of Data Base System

    Library Management System:

  • 8/11/2019 Dbms Complete

    8/65

    Jatin Bhatia, 10165

    We have created a database that manages a library system using SQL language. The tablewith there screenshots are:

    Table 1: StaffAttributes: Employ_ID, Name,Departement, DOB, Book_ID, Membership_Code

  • 8/11/2019 Dbms Complete

    9/65

  • 8/11/2019 Dbms Complete

    10/65

    Jatin Bhatia, 10165

    Table 3: Books Issued

    Attributes:Book_ID, Name_of_Book, Author, Semester, Date_of_issue,Admin_ID,Issuer_ID, Issuer_ID

  • 8/11/2019 Dbms Complete

    11/65

    Jatin Bhatia, 10165

    Table 4:BookBook_ID, Name, Author, Semester

  • 8/11/2019 Dbms Complete

    12/65

    Jatin Bhatia, 10165

    Table 5: Fine

    Issuer_ID, Name, Book_Name, Price, Fine

  • 8/11/2019 Dbms Complete

    13/65

    Jatin Bhatia, 10165

    Experiment 3

    AIM: To alter a created table in SQL.

    Theory:Alter command is used to alter or modify the schema of the required table. Altercommand can be used for various tasks in a table some of them are:

    To add an attribute inside a table. To rename an attribute inside a table.

    To delete a given attribute in a table.

    To alter the data type of the attribute in a table.

    To rename a table.

    To add a constraint (like Primary Key) to a given attribute.

    To delete a constraint (like Not Null) to a given attribute.

    SYNTAX:

    To add an attribute inside a table.

    alter table table_name

    add(columnname 1 datatype1 constraint1(optional),

    columnname 2 datatype2 constraint2(optional),

    -------------------------------

    columnname n datatypen

    );

    To rename an attribute inside a table.

    Alter table table_name

    Rename column old_name to new_name

    ;

    To delete a given attribute in a table

    Alter table table_name

    Drop (attribute_name);

  • 8/11/2019 Dbms Complete

    14/65

    Jatin Bhatia, 10165

    To alter the data type of the attribute in a table.

    Alter table table_name

    Modify ( attribute_name1 new datatype1,

    attribute_name2 new datatype2,

    --------------------------------------

    attribute_namen new datatypen

    );

    To rename a table

    Alter table table_name

    Rename to new table_name

    ;

    To add a constraint (like Primary Key) to a given attribute.

    Alter table table_name

    Add (constraint constraint_label constraint name (attribute_name))

    ;

    To delete a constraint (like Not Null) to a given attribute

    Alter table table_name

    Drop constraint constraint_label

    ;

    Examples of above commands with their screen shots applied on our LibraryManagement Database are shown as follows:

  • 8/11/2019 Dbms Complete

    15/65

    Jatin Bhatia, 10165

    Adding an attribute price of data type number in table book.

  • 8/11/2019 Dbms Complete

    16/65

    Jatin Bhatia, 10165

    To rename column Date_of_birth to DOB.

  • 8/11/2019 Dbms Complete

    17/65

    Jatin Bhatia, 10165

    To drop an attribute price in a table book.

  • 8/11/2019 Dbms Complete

    18/65

    Jatin Bhatia, 10165

    To modify the data type of employee_id, book_id and membership_code to

    varchar, number and number respectively.

  • 8/11/2019 Dbms Complete

    19/65

    Jatin Bhatia, 10165

    To change the table name Staff to Employee.

  • 8/11/2019 Dbms Complete

    20/65

    Jatin Bhatia, 10165

    To add a Primary Key constraint to Book_ID.

  • 8/11/2019 Dbms Complete

    21/65

    Jatin Bhatia, 10165

    To delete a Primary Key constraint on Book_ID.

  • 8/11/2019 Dbms Complete

    22/65

    Jatin Bhatia, 10165

    To rename column name name_of_books to Book_name.

  • 8/11/2019 Dbms Complete

    23/65

  • 8/11/2019 Dbms Complete

    24/65

    Jatin Bhatia, 10165

    Inserting records in table Employee

  • 8/11/2019 Dbms Complete

    25/65

    Jatin Bhatia, 10165

    Inserting records in table Student

  • 8/11/2019 Dbms Complete

    26/65

    Jatin Bhatia, 10165

  • 8/11/2019 Dbms Complete

    27/65

    Jatin Bhatia, 10165

    Inserting records in table Book

  • 8/11/2019 Dbms Complete

    28/65

    Jatin Bhatia, 10165

  • 8/11/2019 Dbms Complete

    29/65

    Jatin Bhatia, 10165

    Inserting records in the table Book_issued

  • 8/11/2019 Dbms Complete

    30/65

    Jatin Bhatia, 10165

    Inserting records in table Fine

  • 8/11/2019 Dbms Complete

    31/65

    Jatin Bhatia, 10165

  • 8/11/2019 Dbms Complete

    32/65

    Jatin Bhatia, 10165

    Experiment 5

    AIM: To delete records in tables created in SQL?

    THEORY: Delete command is also a DML command. It is used to delete records in the

    required table. While deleting a row if we need to apply a condition to it, then we have touse this command with where.

    SYNTAX: There are various formats in which the delete command can be used. Some of

    them are:

    Delete from table_name

    where condition;

    Delete from table_name; //It deletes all rows from table

    Examples of above commands with their screen shots applied on our LibraryManagement Database are shown in the following pages:

    Deletion command applied on table student:(using where condition 4 screen shots)

  • 8/11/2019 Dbms Complete

    33/65

    Jatin Bhatia, 10165

  • 8/11/2019 Dbms Complete

    34/65

    Jatin Bhatia, 10165

    Delete command on table student(deleting complete rows)

  • 8/11/2019 Dbms Complete

    35/65

    Jatin Bhatia, 10165

    Experiment 6

    AIM: To use group by command in table created in SQL?

    THEORY:The GROUP BY statement is used in conjunction with the aggregate

    functions to group the result-set by one or more columns and display it to user. SQLaggregate functions are: Sum, Min, Max, Count, Avg. To give a condition while usingthe group by function we can use the statement havingwith it.

    SYNTAX:

    Select aggregate function (column1)

    From table_name

    Group by column1;

    Select aggregate function (column1)

    From table_name

    Group by column1

    Having condition;

    Examples of above commands with their screen shots applied on our LibraryManagement Database are shown in the following pages:

  • 8/11/2019 Dbms Complete

    36/65

    Jatin Bhatia, 10165

    Screenshot1: Here we can see that the fine attribute is added from the table fine

    grouped according to the price. For example sum of fine on all the books whoseprice is 400 is 180 as shown in the output arranged in ascending order according to

    the price. Here Sum is an aggregate function used.

  • 8/11/2019 Dbms Complete

    37/65

    Jatin Bhatia, 10165

    Screenshot2: Here we have count the number of time the fine issued on a same

    price book( that is grouped by price)For example number of times the book with price 400 is fined is 3 as shown in the

    output and verified by the table displayed in screenshot1.

  • 8/11/2019 Dbms Complete

    38/65

    Jatin Bhatia, 10165

    Screenshot3: Here I have used a having statement with group by to give a

    condition inside my command. Here sum of fine will be grouped by according tothe price as in screenshot1. But the only difference here will be that the command

    will be applicable only for the rows or records that have price>300 as shown in the

    output.

  • 8/11/2019 Dbms Complete

    39/65

    Jatin Bhatia, 10165

    Screenshot4: Here we count number of books for each sem. For example for 4 sem

    there are 4 books as shown in output.

  • 8/11/2019 Dbms Complete

    40/65

    Jatin Bhatia, 10165

    Screenshot5:Here same operation is done as in screenshot 4 but here we used a

    condition by using having command with groupby.

  • 8/11/2019 Dbms Complete

    41/65

    Jatin Bhatia, 10165

    Experiment 7

    AIM: To arrange the data in a table created in SQL?

    THEORY:To arrange a data inside a table created in SQL the command used is order by.

    Order by command arranges the data in table in ascending (by default) or descendingorder according to our preference.

    SYNTAX:

    This syntax arranges the data in ascending order by default applied on the column

    column_name.

    Select * from table_name

    Order by column_name;

    This syntax arranges the data in descending order (desc) applied on the column

    column_name.

    Select * from table_name

    Order by column_name desc;

    Examples of above commands with their screen shots are shown in the following pages:

  • 8/11/2019 Dbms Complete

    42/65

    Jatin Bhatia, 10165

    Screenshot1: Here the table is arranged according to book_id.

  • 8/11/2019 Dbms Complete

    43/65

    Jatin Bhatia, 10165

    Screenshot2: Here table is arranged according to name attribute alphabetically and

    according to sem.

  • 8/11/2019 Dbms Complete

    44/65

    Jatin Bhatia, 10165

    Experiment 8

    AIM: To modify the data in tables created in SQL?

    THEORY:To modify the records inserted in table we have to use the command update.

    We have to set the value of a particular column where the condition identifies theparticular tuple or row.

    SYNTAX:

    To make change in a single column:

    Update table_name

    Set column=value/expression

    Where condtion;

    To make change in multiple column:Update table_name

    Set column1=value/expression , column2=value/expression

    Where condtion;

    When more than one condition is to be implemented:

    Update table_name

    Set column=value/expression

    Where condtion1 AND condition2;

    Examples of above commands with their screen shots applied on our Library

    Management Database are shown in the following pages:

    Screenshot1:Original Table book

  • 8/11/2019 Dbms Complete

    45/65

    Jatin Bhatia, 10165

    Screenshot2: Here multiple values are set.

  • 8/11/2019 Dbms Complete

    46/65

    Jatin Bhatia, 10165

    Screenshot3: Here we have given multiple conditions.

  • 8/11/2019 Dbms Complete

    47/65

    Jatin Bhatia, 10165

    Screenshot4: Here one condition is given.

  • 8/11/2019 Dbms Complete

    48/65

    Jatin Bhatia, 10165

    Experiment 9

    AIM: To apply Join operations in tables created in SQL?

    THEORY:Join operation combines records from two or moretables in a database. It

    creates a set that can be saved as a table or used as it is. A JOIN is a means for combiningfields from two tables by using values common to each. There are different types of join

    operation:-

    Cross Join: It is also known as Cartesian product of two tables. It returns the

    Cartesian product of rows from tables in the join. In other words, it will produce

    rows which combine each row from the first table with each row from the second

    table.

    Inner Join: It is also known as Equi-Join or Simple Join operation. It isa specific

    type of comparator-based join, or theta join, that uses onlyequality comparisons in

    the join-predicate. Using other comparison operators (such as

  • 8/11/2019 Dbms Complete

    49/65

    Jatin Bhatia, 10165

    Left Outer Join

    Select table1.column, table2.column

    From table1, table2

    Where table1.column(+)=table2.column;

    ORSelect from table1 leftouterjoin table2

    On table1.column=table2.column;

    Right Outer Join

    Select table1.column, table2.column

    From table1, table2

    Where table1.column=table2.column(+);

    OR

    Select from table1 rightouterjoin table2On table1.column=table2.column;

    Full Outer Join

    Select from table1 fullouterjoin table2

    On table1.column=table2.column;

    Self Join

    Select column1, column2, cloumn3

    From table1 a, table1 b

    Where a.column1=b.column2;

    Table Alias: In the above syntax we used a for table1 and b for table 2. This method

    reduces the code length and gives the programmer a shortcut in SQL; a and b are

    called the table alias and can be used inside the commands whenever required.

    Examples of above commands with their screen shots are shown in the following pages:

  • 8/11/2019 Dbms Complete

    50/65

    Jatin Bhatia, 10165

    SCREENSHOT1:All the Join operations will be done on the following tables

    (Employee and departement). The table is shown in the screenshot along with the

    tuples.

    SCREENSHOT2: It describes the cross join/Cartesian product operation on the

    two tables with and without condition. In one part a condition is given which

    reduces the number of tuples and in second part 24 rows are selected.

  • 8/11/2019 Dbms Complete

    51/65

    Jatin Bhatia, 10165

    SCREENSHOT3: It describes the inner join operation.

  • 8/11/2019 Dbms Complete

    52/65

    Jatin Bhatia, 10165

    SCREENSHOT4: It describes the left outer join operation on the tables.

    SCREENSHOT5: It describes the right outer join operation.

    SCREENSHOT6: It describes full outer join operation.

  • 8/11/2019 Dbms Complete

    53/65

    Jatin Bhatia, 10165

    Experiment 10AIM: To insert data in a table with the help of subquery?

    THEORY: Subquery or Inner query or Nested query is a query in a query. A subquery is

    usually added in the WHERE Clause of the sql statement. Most of the time, a subquery isused when you know how to search for a value using a SELECT statement, but do not

    know the exact value. Subqueries are an alternate way of returning data from multipletables. During execution of a subquery command in SQL, the innermost query executesfirst.

    Subqueries can be used with the following sql statements along with the comparisonoperators like =, , >=, 2);

    To copy schema as well as data from one table to another.

    Create table as

    (select * from );

    To copy schema and data from one table to another with some conditions.

    Create table as

    (select * from where condition);

    Examples of above commands with their screen shots are shown in the following pages:

  • 8/11/2019 Dbms Complete

    54/65

    Jatin Bhatia, 10165

    Screenshot1: The schema of a table student1 is copied into another table student2.

    Screenshot2: The schema as well as data of table student1 is copied into the table

    student3.

  • 8/11/2019 Dbms Complete

    55/65

    Jatin Bhatia, 10165

    Screenshot3: A new table student4 is created from student1. Student4 contain data

    of all the students that have se as there department.

  • 8/11/2019 Dbms Complete

    56/65

    Jatin Bhatia, 10165

    Experiment 11AIM: To retrieve, delete, and update the date in a table using subquery?

    THEORY: Subquery or Inner query or Nested query is a query in a query. A subquery is

    usually added in the WHERE Clause of the sql statement. A subquery can also be use toretrieve, delete and update the information or data in a table created in SQL.

    The subqueries can be applied on same as well as on different table to get the required

    results.

    There are 2 types of retrieval in SQL: Single Row and Multiple Row.

    When inner query returns a single tuple as its query output then its single row retrieval

    else it is multiple row retrieval.

    SYNTAX:

    To retrieve data from a table.

    Select select_list

    From table

    Where expression_operator

    (select select_list

    from table);

    To delete data from the tableDelete from where

    In(subquery);

    To update data in a table.

    Update

    Set= (subquery1)

    = (subquery2)

    Where condition;

    Examples of above commands with their screen shots are shown in the following pages:

  • 8/11/2019 Dbms Complete

    57/65

    Jatin Bhatia, 10165

    Screenshot1: Here I have retrieved the data from the table student. List of all the

    students are displayed except the student having mechanical department. It is an

    example of multiple row retrieval of data.

  • 8/11/2019 Dbms Complete

    58/65

    Jatin Bhatia, 10165

    Screenshot2: This screenshot describe the single row retrieval of data from table

    student1

    Screenshot3: All the student having branch cse are deleted from the table student1

    using a subquery.

  • 8/11/2019 Dbms Complete

    59/65

    Jatin Bhatia, 10165

    Screenshot4: Here I have updated the table student1 using a subquery. The name of

    the student with roll no 10160 is changed to karma as displayed below.

  • 8/11/2019 Dbms Complete

    60/65

    Jatin Bhatia, 10165

    Experiment 12AIM: Describe PL/SQL (Procedural Language/Structured Query Language)?

    PL/SQL (Procedural Language/Structured Query Language)isOracle Corporation's

    procedural extensionlanguage forSQL and theOracle relational database.PL/SQL'sgeneralsyntax resembles that ofAda orPascal.PL/SQL is one of three key programming

    languages embedded in the Oracle Database, along with SQL itself andJava.

    PL/SQL is Oracle's procedural language extension to SQL, the relational database

    language. PL/SQL fully integrates

    modern software engineering features such as data encapsulation, information hiding,overloading, and exception handling, and so brings state-of-the-art programming to the

    ORACLE Server and a variety of ORACLE tools

    Overview of PL/SQL:With PL/SQL, you can use SQL statements to manipulate ORACLE data and flow-of-

    control statements to process the data. Moreover, you can declare constants and variables,define subprograms (procedures and functions), and trap runtime errors. Thus, PL/SQL

    combines the data manipulating power of SQL with the data processing power ofprocedural languages.

    PL/SQL is a block-structured language. That is, the basic units (procedures, functions,and anonymous blocks) that make up a PL/SQL program are logical blocks, which can

    contain any number of nested sub-blocks. Typically, each logical block corresponds to aproblem or subproblem to be solved. A block (or sub-block) lets you group logically

    related declarations and statements. That way you can place declarations close to wherethey are used. The declarations are local to the block and cease to exist when the block

    completes.

    [DECLARE-- declarations]BEGIN

    -- statements[EXCEPTION-- handlers]

    END;

    PL/SQL TablesPL/SQL provides two composite datatypes: TABLE and RECORD. Objects of type

    TABLE are called PL/SQL tables, which are modeled as (but not the same as) database

    tables. PL/SQL tables use a primary key to give you array-likeaccess to rows.

    http://en.wikipedia.org/wiki/Oracle_Corporationhttp://en.wikipedia.org/wiki/Procedural_programminghttp://en.wikipedia.org/wiki/Programming_languagehttp://en.wikipedia.org/wiki/SQLhttp://en.wikipedia.org/wiki/Oracle_Databasehttp://en.wikipedia.org/wiki/Syntax_%28programming_languages%29http://en.wikipedia.org/wiki/Ada_%28programming_language%29http://en.wikipedia.org/wiki/Pascal_%28programming_language%29http://en.wikipedia.org/wiki/Java_%28programming_language%29http://en.wikipedia.org/wiki/Java_%28programming_language%29http://en.wikipedia.org/wiki/Pascal_%28programming_language%29http://en.wikipedia.org/wiki/Ada_%28programming_language%29http://en.wikipedia.org/wiki/Syntax_%28programming_languages%29http://en.wikipedia.org/wiki/Oracle_Databasehttp://en.wikipedia.org/wiki/SQLhttp://en.wikipedia.org/wiki/Programming_languagehttp://en.wikipedia.org/wiki/Procedural_programminghttp://en.wikipedia.org/wiki/Oracle_Corporation
  • 8/11/2019 Dbms Complete

    61/65

    Jatin Bhatia, 10165

    Like the size of a database table, the size of a PL/SQL table is unconstrained. That is, the

    number of rows in a PL/SQL table can increase dynamically. The PL/SQL table grows asnew rows are added.

    PL/SQL tables can have one column and a primary key, neither of which can be named.

    The column can belong to any scalar type, but the primary key must belong to typeBINARY_INTEGER.

    Interaction With ORACLE:

    SQL SupportBy extending SQL, PL/SQL offers a unique combination of power and ease of use. You

    can manipulate ORACLE data flexibly and safely because PL/SQL supports all SQL data

    manipulation commands (except EXPLAIN PLAN), transaction control commands,functions, pseudocolumns, and operators. However, PL/SQL does not support data

    definition commands such as CREATE, session control commands such as SET ROLES,

    or the system control command ALTER SYSTEM.

    Data Manipulation

    To manipulate ORACLE data, you use the INSERT, UPDATE, DELETE, SELECT, and

    LOCK TABLE commands.

    Transaction Control

    ORACLE is transaction oriented; that is, ORACLE uses transactions to ensure dataintegrity. A transaction is a series of SQL data manipulation statements that does a

    logical unit of work. For example, two UPDATE statements might

    credit one bank account and debit another. At the same instant, ORACLE makespermanent or undoes all database changes made by a transaction. If your program fails in

    the middle of a transaction, ORACLE detects the error and rolls back the transaction.Hence, the database is restored to its former state automatically.

    You use the COMMIT, ROLLBACK, SAVEPOINT, and SET TRANSACTION

    commands to control transactions.COMMIT makes permanent any database changes made during the current transaction.

    Until you commit your changes, other users cannot see them. ROLLBACK ends the

    current transaction and undoes any changes made since the transaction began.SAVEPOINT marks the current point in the processing of a transaction. Used with

    ROLLBACK, undoes part of a transaction. SET TRANSACTION establishes a read-only

    transaction

  • 8/11/2019 Dbms Complete

    62/65

    Jatin Bhatia, 10165

    CONTROL STRUCTURES

    According to the structure theorem, any computer program can be written using the basiccontrol structures which can be combined in any way necessary to deal with a given

    problem.

    The selection structure tests a condition, then executes one sequence of statementsinstead of another, depending on whether the condition is true or false. A condition is any

    variable or expression that returns a Boolean value (TRUE, FALSE, or NULL). Theiteration structure executes a sequence of statements repeatedly as long as a condition

    holds true. The sequence structure simply executes a sequence of statements in the orderin which they occur.

    Conditional Control: IF Statements

    Often, it is necessary to take alternative actions depending on circumstances. The IFstatement lets you execute a sequence of statements conditionally. That is, whether the

    sequence is executed or not depends on the value of a

    condition. There are three forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF.The third form of IF statement uses the keyword ELSIF (NOT ELSEIF) to introduce

    additional conditions, as follows:

    IF condition1 THENsequence_of_statements1;

    ELSIF condition2 THEN

    sequence_of_statements2;ELSE

    sequence_of_statements3;

    15END IF;

    Iterative Control: LOOP and EXIT Statements

    LOOP statements let you execute a sequence of statements multiple times. There are

    three forms of LOOP statements:

    LOOP, WHILE-LOOP, and FOR-LOOP.

    LOOPThe simplest form of LOOP statement is the basic (or infinite) loop, which encloses a

    sequence of statements between

    the keywords LOOP and END LOOP, as follows:LOOP

    sequence_of_statements3;

    ...END LOOP;

  • 8/11/2019 Dbms Complete

    63/65

    Jatin Bhatia, 10165

    With each iteration of the loop, the sequence of statements is executed, then control

    resumes at the top of the loop. If further processing is undesirable or impossible, you canuse the EXIT statement to complete the loop. You can place

    one or more EXIT statements anywhere inside a loop, but nowhere outside a loop. There

    are two forms of EXIT statements: EXIT and EXIT-WHEN.The EXIT statement forces a loop to complete unconditionally. When an EXIT statement

    is encountered, the loop completes immediately and control passes to the next statement.LOOP

    ...IF ... THEN

    ...

    EXIT; -- exit loop immediatelyEND IF;

    END LOOP;

    -- control resumes hereThe EXIT-WHEN statement allows a loop to complete conditionally. When the EXITstatement is encountered, the condition in the WHEN clause is evaluated. If the condition

    evaluates to TRUE, the loop completes and control passes to the next statement after the

    loop.LOOP

    FETCH c1 INTO ...

    EXIT WHEN c1%NOTFOUND; -- exit loop if condition is true...

    END LOOP;

    CLOSE c1;Until the condition evaluates to TRUE, the loop cannot complete. So, statements within

    the loop must change the valueof the condition.

    Like PL/SQL blocks, loops can be labeled. The label, an undeclared identifier enclosed

    by double angle brackets, must

    appear at the beginning of the LOOP statement, as follows:

    LOOP

    sequence_of_statements;...

    16

    END LOOP [label_name];Optionally, the label name can also appear at the end of the LOOP statement.

  • 8/11/2019 Dbms Complete

    64/65

    Jatin Bhatia, 10165

    With either form of EXIT statement, you can complete not only the current loop, but any

    enclosing loop. Simply label the enclosing loop that you want to complete, then use thelabel in an EXIT statement.

    LOOP...

    LOOP...

    EXIT outer WHEN ... -- exit both loopsEND LOOP;

    ...

    END LOOP outer;

    WHILE-LOOP

    The WHILE-LOOP statement associates a condition with a sequence of statements

    enclosed by the keywords LOOP and END LOOP, as follows:WHILE condition LOOPsequence_of_statements;

    ...

    END LOOP;Before each iteration of the loop, the condition is evaluated. If the condition evaluates to

    TRUE, the sequence of statements is executed, then control resumes at the top of the

    loop. If the condition evaluates to FALSE or NULL, the loop is bypassed and controlpasses to the next statement. Since the condition is tested at the top of the loop, the

    sequence might execute zero times.

    FOR-LOOP

    Whereas the number of iteration through a WHILE loop is unknown until the loop

    completes, the number of iterations through a FOR loop is known before the loop isentered. FOR loops iterate over a specified range of integers. The range is part of an

    iteration scheme, which is enclosed by the keywords FOR and LOOPS.

    FOR counter IN [REVERSE] lower_bound..upper_bound LOOP

    sequence_of_statements;...

    END LOOP;

    The lower bound need not be 1. However, the loop counter increment (or decrement)must be 1.

    PL/SQL lets you determine the loop range dynamically at run time, as the following

    example shows:SELECT COUNT(empno) INTO emp_count FROM emp;

    FOR i IN 1..emp_count LOOP...

  • 8/11/2019 Dbms Complete

    65/65

    END LOOP;

    17The loop counter is defined only within the loop. You cannot reference it outside the

    loop. You need not explicitly

    declare the loop counter because it is implicitly declared as a local variable of typeINTEGER.

    The EXIT statement allows a FOR loop to complete prematurely. You can complete notonly the current loop, but any

    enclosing loop.