An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... ·...

301
1 Lecture 01 An Introduction To RDBMS Lecture 01 Objective This lecture gives an idea of database management system. It helps students to know about the concept of relational database management system and explains why oracle is considered as a strong RDBMS as compared to other databases. Lecture 01 Topics Covered RDBMS – Concept Oracle – A Strong RDBMS Comparison of Oracle with DBMS

Transcript of An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... ·...

Page 1: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 01

An Introduction To RDBMS

Lecture 01

Objective

This lecture gives an idea of database management system. It helps students to know about the concept of relational database management system and explains why oracle is considered as a strong RDBMS as compared to other databases.

Lecture 01

Topics Covered

RDBMS – ConceptOracle – A Strong RDBMSComparison of Oracle with DBMS

Page 2: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 01

What is DataBase?

A logical coherent collection of data.Representation of an aspect of real life that is designed, built and populated with data for specific purpose.Classified according to their organizational approach.Contains aggregation of data records or files.

Lecture 01

What is DBMS?

A collection of programs that enables user to create and maintain a database.A software that provides the users with the processes of defining, constructing and manipulating the database for various applications.

Lecture 01

Advantages of DBMS

Restricted unauthorisedaccess

Provides multiple user interfaces

Enforces integrity constraints

Provides backup and recovery

Page 3: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 01

What is Relational Database?Invented by E. F. Codd at IBM in 1970.A collection of data items organized as a set of formally-described tables.A set of tables containing data fitted into predefined categories.The definition of a relational database results in a table of metadata or formal descriptions of the tables, columns, domains and constraints.Created using SQL

Lecture 01

Why Oracle is Considered As RDBMS?

It is a collection of data treated as a unit.Stores and retrieves related information.Manages a large amount of data in a multiuser environment.Delivers high performance.Prevents unauthorized access.Provides efficient solutions for failure recovery.

Lecture 01

Features of Oracle

Large database and space management controlIndustry accepted standardsDatabase enforced integrityDistributed database systemsPortabilityCompatibilityConnectability

Page 4: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 01

Oracle vs Other Databases

Oracle follows all of the CODD’s rules whereas other databases follow some of them. Oracle works strongly with Client / Server technology.Security wise Oracle is most reliable.

Page 5: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 02

Architecture of Oracle DBMS - I

Lecture 02

Objective This lecture gives an idea of Oracle architecture. It explains about the Database Structure. How they are classified and also explains a bit of different aspects of Logical database structure.

Lecture 02

Topics Covered Architecture of Oracle DBMSLogical Data Structure

Schemas And Schema ObjectData blocks, Extents and SegmentsTablespaces

Page 6: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 02

Oracle ArchitectureDatabase Structures

Logical Physical

Schemas and Schema Objects

Data Blocks, Extents and Segments

Tablespaces

Datafiles

Redo Log Files

Control Files

Data Utilities

Lecture 02

Logical Database StructureSchemas – A Collection of database objects.Schema Objects – Logical structures that directly refer to the database’s data.Oracle Data Blocks – Storage for Oracle database data.Extents - A specific number of contiguous data blocks obtained in a single allocation.Segments - A set of extents allocated for a certain logical structure.Tablespaces - Logical storage units which group related logical structures together.

Lecture 02

Schemas and Schema ObjectsA schema is owned by a database user.Schema objects includes

TablesViewsIndexesClusters

Objects in the same schema can be in different tablespaces.Tables - Basic unit of data storage in an Oracle database.Views - Customized presentations of data in one or more tables .Indexes - Created to increase the performance of data retrieval.

Page 7: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 02

Data Blocks, Extents and Segments

The standard block size is specified by the initialization parameter DB_BLOCK_SIZE.Oracle dynamically allocates space when the existing extents of a segment become full.

Lecture 02

Types of Segments

Data segmentIndex segmentTemporary segmentRollback segment

Lecture 02

The relationship between databases, tablespaces and datafiles

Page 8: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 02

Online and Offline Tablespaces

Online Tablespaces - Users can access the information in the tablespace.Offline Tablespaces - A portion of the database unavailable while allowing normal access to the remainder of the database.

Lecture 02

Detached Processes for Oracle - 1

DBWR - Database WriterLGWR - Log WriterSMON - System MonitorPMON - Process MonitorARCH - Archiver ProcessRECO - Distributed TransactionLCKn - Lock Process

Lecture 02

Detached Processes for Oracle - 2

Dnnn - DispatcherSnnn - ServersLISTENERTCPIP serverCKPxxSnpxxEXTPROCQMNn

Page 9: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 03

Architecture of Oracle DBMS - II

Lecture 03

Objective This lecture explains about different aspects of Physical database structure. It also gives an idea of different data utilities.

Lecture 03

Topics Covered Physical Data Structure

DatafilesRedo Log FilesControl FilesData Utilities

Page 10: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 03

Physical Database StructuresDatafiles – Contains all the database data.Redo Log Files – Records all changes made to data.Control Files – Contains entries that specify the physical structure of the database.Data Utilities - Utilities for moving a subset of an Oracle database from one database to another .

Lecture 03

DatafilesFiles those contain all the database data.Every Oracle database has one or more physical datafiles.A datafile can be associated with only one database.Datafiles can have certain characteristics set to let them automatically extend when the database runs out of space.One or more datafiles form a logical unit of database storage called a tablespace.

Lecture 03

Redo Log FilesEvery Oracle database has a set of two or more redo log files.The set of redo log files is collectively known as the redo log for the database.The primary function of the redo log is to record all changes made to data.Oracle allows a multiplexed redo log.The information in a redo log file is used only to recover the database from a system or media failure that prevents database data from being written to the datafiles.

Page 11: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 03

Control FilesEvery Oracle database has a control file.A control file contains

Database nameNames and locations of datafiles and redo

log filesTime stamp of database creation

A control file is used in database recovery

Lecture 03

Data UtilitiesExport Utility - Transfers data objects between Oracle databases, even if they reside on platforms with different hardware and software configurations.Import Utility - Inserts the data objects extracted from one Oracle database by the Export utility into another Oracle database.SQL*Loader Utility - Loads data from external files into tables in an Oracle database.

Lecture 03

Export UtilityExport extracts the object definitions and table data from an Oracle database and stores them in an Oracle binary-format Export dump file.Export dump files can be used with the Import utility to transfer data between databases that are on machines not connected through a network or as backups in addition to normal backup procedures.It extracts objects such as tables followed by their related objects and then writes them to the Export dump file.

Page 12: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 03

Import Utility

Export dump files can be read only by Import.It reads the object definitions and table data that the Export utility extracted from an Oracle database.It facilitates offline instantiation.

Lecture 03

SQL*Loader Utility

To read load data from ASCII fixed-format or delimited files, the SQL*Loader utility can be used.It accepts input data in a variety of formats.It performs filtering.It loads data into multiple Oracle database tables during the same load session

Page 13: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 04

Data Modeling and Normalization

Lecture 04

Objective

• To study the concept of Data Modeling• Understanding E-R Model• Normalization – A Design Technique• E-R Diagrams

Lecture 04

Topics Covered

• Data Modeling• E-R Model

– Entities– Relationships– Attributes

• Normalization• E-R Diagrams

Page 14: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 04

Data Modeling

• A part of the conceptual design process• Focuses on what data should be stored

in the database• It is preceded by planning and analysis• Completely and accurately represents

the data requirements of the end users• Eliminates redundant data• Independent of any hardware and

software constraints

Lecture 04

Steps In Building the Data Model

• Identification of data objects and relationships

• Drafting the initial ER diagram with entities and relationships

• Refining the E-R diagram• Add key attributes to the diagram

Contd…

Lecture 04

Steps In Building the Data Model

• Adding non-key attributes • Diagramming Generalization Hierarchies• Validating the model through

normalization• Adding business and integrity rules to

the Model

…Contd

Page 15: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 04

Entity - Relationship Model • Originally proposed by Peter in 1976 • A way to unify the network and

relational database views• A way of graphically representing the

logical relationships of entities or objects in order to create a database

• Rendered as points, polygons, circles, or ovals

• Equivalent of grammatical nouns, such as employees, departments, products or networks

Lecture 04

Basic Components of E-R Model• Entities are the

principal data object about which information is to be collected.

• A Relationship represents an association between two or more entities.

• Attributes describe the entity of which they are associated

E – R Model

Entities Relationship

Attributes

Lecture 04

Normalization • A design technique for structuring

relational database tables • First proposed by Edgar F. Codd• Database theory describes a table's

degree of normalization in terms of normal forms

• Each normal form automatically includes the properties of lower normal forms

Page 16: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 04

Various Normal Forms

• 1NF or First Normal Form • 2NF or Second Normal Form• 3NF or Third Normal Form• BCNF or Boyce-Codd normal form• 4NF or Fourth normal form• 5NF or Fifth normal form• DKNF or Domain / key normal form • 6NF or Sixth normal form

Lecture 04

Entity – Relationship Diagram • A specialized graphic that illustrates the

interrelationships between entities in a database

• Uses symbols to represent different types of information

• Any ER diagram has an equivalent relational table and vice-versa

• An invaluable aid to engineers in the design, optimization and debugging of database programs

Lecture 04

Symbols To Construct E-R Diagram • Entities• Relationship• Attribute• Connection

between Entities• Multi-valued

Attributes• Derived

Attributes• Weak entity set

Page 17: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 04

An E-R Diagram Methodology

• Identify Entities • Find Relationships • Draw Rough ERD • Fill in Cardinality • Define Primary

Keys

• Draw Key-Based ERD

• Identify Attributes• Map Attributes• Draw fully

attributed ERD• Check Results

Lecture 04

Simple E-R Diagram

• ER digram shown in the image contains two entities - people and cities

• A single Lives In relationship

• Only one attribute associated with each entity

Person

Lives In

City

Name

Population

Lecture 04

A Case Study • A company has several departments. Each

department has a supervisor and at least one employee. Employees must be assigned to at least one but possibly more departments. At least one employee is assigned to a project but an employee may be on vacation and not assigned to any projects. The important data fields are the names of the departments, projects, supervisors and employees as well as the supervisor and employee number and a unique project number.

Page 18: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 04

Fully Attributed ERD of Company

Page 19: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 05

SGA & Client / Server Architecture

Lecture 05

ObjectivesTo study the Basic Memory Structure associated with Oracle. To understand the concept of SGATo know the various initialization parameters used to control how SGA uses memory.To study the concept of Client / Server Architecture.

Lecture 05

Topics CoveredOracle Memory Structure

SGADatabase buffer cache Redo log buffer Shared pool Large poolData dictionary cache

Client / Server Architecture

Page 20: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 05

Oracle Memory Structures

Oracle uses memory to store informationProgram code Information about a connected session even if it is not currently active Information needed during program execution Information that is shared and communicated among Oracle processesCached data that is also permanently stored on peripheral memory

Lecture 05

Basic Memory Structures

System Global Area ( SGA )Database buffer cache Redo log buffer Shared pool Large pool

Program Global Area ( PGA )Stack areas Data areas

Lecture 05

Oracle Memory Structures

Page 21: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 05

System Global Area ( SGA )

A group of shared memory structures that contain data and control information for one Oracle database instance Sometimes called the shared global areaOracle automatically allocates memory for an SGA when an instance is startedThe SGA is read / write

Lecture 05

Data Structures in SGA

Database buffer cache Redo log buffer Shared pool Large pool ( optional ) Data dictionary cache

Lecture 05

Database Buffer Cache

The portion of the SGA that holds copies of data blocks read from datafilesAll user processes concurrently connected to the instance share access to the database buffer cache

Page 22: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 05

Redo Log BufferA circular buffer in the SGA that holds information about changes made to the database.Redo entries contain the information necessary to reconstruct, or redo, changes made to the database by INSERT, UPDATE, DELETE, CREATE, ALTER or DROP operations.Redo entries are copied by Oracle server processes.

Lecture 05

Shared PoolPortion of the SGA that contains library cache, dictionary cache, buffers for parallel execution messages and control structures.The total size of the shared pool is determined by the initialization parameter SHARED_POOL_SIZE.

Lecture 05

Large PoolTo provide large memory allocations for:

Session memory for the shared server and the Oracle XA interfaceI/O server processes Oracle backup and restore operations Parallel execution message buffers, if the initialization parameter PARALLEL_AUTOMATIC_TUNING is set to true

Page 23: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 05

Dictionary CacheA collection of database tables and views containing reference information about the database, its structures and its usersOracle accesses the data dictionary frequently during SQL statement parsingAlso known as the row cache

Lecture 05Client / Server Architecture

The database are separated into two parts: a front-end or client portion, and a back-end or server portion.The client runs the database application that accesses database information and interacts with a user through the keyboard, screen and pointing device.The server runs the Oracle software and handles the functions required for concurrent, shared data access to an Oracle database

Lecture 05

Client / Server Architecture

In figure A, the client and server are located on different computers.In figure B, a single computer has more than one processor and different processors separate the execution of the client application from Oracle

Page 24: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 06

Oracle Objects_I

Lecture 06

Objectives

To study…What are Oracle objects?What is the use of Oracle Objects? Various types of database objects

Lecture 06

Topics Covered

Schema ObjectsTablesViewsMaterialized views

Page 25: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 06

Schema ObjectsA schema is a collection of logical structures of data or schema objects.Each user owns a single schema.Schema objects can be created and manipulated with SQL .Schema objects do not have a one-to-one correspondence to physical files on disk that store their information.Oracle stores a schema object logically within a tablespace of the database.

Lecture 06

Schema Objects, Tablespaces & Datafiles

Lecture 06

TablesTables are the basic unit of data storage in an Oracle database. Data is stored in rows and columns.Rules can be specified for each column of a table.Oracle automatically allocates a data segment in a tablespace to hold the table's future data.The allocation and use of space for a table's data segment can be controlled.

Page 26: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 06

Types of Tables

Partitioned TablesNested TablesTemporary TablesExternal Tables

Lecture 06

Views

A view is a tailored presentation of the data.It takes the output of a query and treats it as a table.Views can be used in most places where a table can be used.It depends on the referenced objects.Oracle automatically handles the dependencies for views.

Lecture 06

Mechanics of Views

When a view is referenced in a SQL statement Oracle

Merges the statement that references the view with the query that defines the viewParses the merged statement in a shared SQL areaExecutes the statement

Page 27: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 06

Types of Views

Updatable Join ViewsObject ViewsInline Views

Lecture 06

Materialized ViewsSchema objects that can be used to summarize, compute, replicate and distribute data.Suitable in various computing environments such as data warehousing, decision support and distributed or mobile computing.Can be accessed directly using a SELECT statement.Can be partitioned.

Lecture 06

Constraints Defined on Views

Primary key constraintUnique constraintReferential Integrity constraint

Page 28: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 07

Oracle Objects_II

Lecture 07

Objectives

To study…What are Oracle objects?What is the use of Oracle Objects? Various types of database objects

Lecture 07

Topics Covered

SequencesSynonymsIndexesIndex – organized tablesClustersHash clusters

Page 29: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 07

SequencesProvides a sequential series of numbers.Especially useful in multiuser environments for generating unique sequential numbers without the overhead of disk I/O or transaction locking.Reduces serialization where the statements of two transactions must generate sequential numbers at the same time.Sequence numbers are generated independently of tables.

Lecture 07

SynonymsIt is an alias for any table, view, materialized view, sequence, procedure, function or package.It requires no storage other than its definition in the data dictionary.Both public and private synonyms can be created.They can simplify SQL statements for users in a distributed database system.

Lecture 07

Uses of SynonymsMask the name and owner of an object Provide location transparency for remote objects of a distributed database Simplify SQL statements for database users Enable restricted access similar to specialized views when exercising fine-grained access control

Page 30: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 07

IndexesOptional structures associated with tables and clustersCan be created on one or more columns of a table to speed SQL statement execution on that tableMore than one index using the same columns can be created

Lecture 07

Index-Organized TablesAn index-organized table has a storage organization that is a variant of a primary B-tree.Applications manipulate the index-organized table just like an ordinary table, using SQL statements.It provides faster access to table rows by the primary key or any key that is a valid prefix of the primary key.

Lecture 07

Structure of a Regular Table and an Index-Organized Table

Page 31: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 07

Index-Organized Table Applications

Online Transaction Processing InternetE-CommerceData Warehousing Time-series applications

Lecture 07

ClustersOptional method of storing table dataA group of tables that share the same data blocks and are often used togetherStores related rows of different tables together in the same data blocksEach cluster key value is stored only once each in the cluster and the cluster indexLess storage is required to store related table and index data in a cluster than in nonclustered table format

Lecture 07

Hash Clusters

It groups table data in a manner similar to regular index clusters.It is an alternative to a nonclustered table with an index or an index cluster.A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value.The key of a hash cluster can be a single column or composite key.

Page 32: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 08

Securities in Oracle

Lecture 08

Objectives

• This lecture helps to understand about the concept of security mechanism. It also explains the types of Database securities and various Oracle security facilities.

Lecture 08Topics Covered• Concept of Security Mechanism• Types of Database Securities

System SecurityData Security

• Oracle Security FacilitiesDatabase Users and SchemasPrivilegesRolesStorage Settings and QuotasProfiles and Resource LimitsSelective Auditing of User ActionsFine-Grained Auditing

Page 33: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 08

Why security mechanisms?

• To prevent unauthorized database access

• To prevent unauthorized access to schema objects

• To audit user actions

Lecture 08

Types of Database Securities

• System Security – Includes the mechanisms that control

the access and use of the database at the system level

• Data Security – Includes the mechanisms that control

the access and use of the database at the schema object level

Lecture 08

System Security

• System Security includesValid username/password combinations The amount of disk space available to a user's schema objects The resource limits for a user

Page 34: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 08

Data Security

• Data Security includesWhich users have access to a specific schema object and the specific types of actions allowed for each user on the schema objectThe actions, if any, that are audited for each schema objectData encryption to prevent unauthorized users from bypassing Oracle and accessing data

Lecture 08

Oracle Security Facilities

• Database Users and Schemas• Privileges• Roles• Storage Settings and Quotas• Profiles and Resource Limits• Selective Auditing of User Actions• Fine-Grained Auditing

Lecture 08

Relationships of Security Facilities

Page 35: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 08

Database Users and Schemas

• Each Oracle database has a list of usernames.

• To access a database, a user must use a database application and attempt a connection with a valid username of the database.

• Each username has an associated password to prevent unauthorized use.

Lecture 08

Privileges

• A privilege is a right to run a particular type of SQL statement .

• Types of PrivilegesSystem PrivilegesSchema Object PrivilegesGranted Privileges

Lecture 08

Roles

• Oracle provides for easy and controlled privilege management through roles.

• Roles are named groups of related privileges that you grant to users or other roles.

Page 36: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 08

Storage Settings and Quotas

• Oracle provides a way to direct and limit the use of disk space allocated to the database for each user.

Default TablespaceTemporary TablespaceTablespace Quotas

Lecture 08

Profiles and Resource Limits

• Each user is assigned a profile that specifies limitations on several system resources available to the user .

• Different profiles can be created and assigned individually to each user of the database.

• The resource limit feature prevents excessive consumption of global database system resources.

Lecture 08

Selective Auditing of User Actions • Statement Auditing

The auditing of specific SQL statements without regard to specifically named schema objects

• Privilege AuditingThe auditing of powerful system privileges without regard to specifically named schema objects

• Schema Object AuditingThe auditing of access to specific schema objects without regard to user

Page 37: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 08

Fine-Grained Auditing • Allows the monitoring of data access

based on content• Based on simple user-defined SQL

predicates on table objects as conditions for selective auditing

• Can be implemented in user applications using the DBMS_FGA package or by using database triggers

Page 38: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 09

What is SQL?

Lecture 09

Objective

The aim of this lecture is to introduce students with Standard Query Language used to query data from Oracle RDBMS. After completing this lecture student will understand the concept of SQL and it’s use. They will also get a brief idea of Language Elements of SQL.

Lecture 09

Topics Covered

An Introduction to SQLHistorySQL StandardizationProcedural ExtensionsAdditional ExtensionsSQL FeaturesTasks for which SQL provides StatementsLanguage Elements

Page 39: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 09

What is SQL?

Commonly expanded as Structured Query LanguageA computer language designed for the retrieval and management of data in relational database management systems, database schema creation and modification and database object access control managementStandardized by both ANSI and ISO

Lecture 09

History of SQL

During 1970s, a team at IBM developed System R RDBMS based on E. F. Codd’smodel.Subsequently another team at IBM created SEQUEL – Structured English Query Language to manage data stored in System R.The acronym SEQUEL was later changed to SQL.

Lecture 09

SQL Standardization

Oracle Corporation strives to comply with industry-accepted standards and participates actively in SQL standards committeesAdopted as a standard by the ANSI in 1986ANSI SQL standard was subsequently adopted as an ISO standard in 1987

Page 40: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 09

Procedural extensions

Structured Query Language Open Source

Procedural Language/PostgreSQL

PL/pgSQLPostgres

ProprietaryProcedural Language/SQL

PL/SQLOracle

Open Source/Proprietary

MySQLMySQLMySQL

ProprietaryTransact-SQLT-SQLMicrosoft/Sybase

ProprietarySQL Procedural Language

SQL PLIBM

Stored Module Standard

SQL/PersistentSQL/PSM ANSI

Development Method

Full NameCommon Name

Source

Lecture 09

Additional extensions

SQL/CLI extensionIt defines common interfacing components that can be used to execute SQL statements from applications written in other programming languages

SQL/MED extensionIt provides extensions to SQL that define foreign-data wrappers and datalink types to allow SQL to manage external data

Contd…

1/3

Lecture 09

Additional extensions SQL/OLB extension

It defines the syntax and symantics of SQLJ that is SQL embedded in Java

SQL/Schemata extensionIt defines the Information Schema and Definition Schema, providing a common set of tools to make SQL databases and objects self-describing

SQL/JRT extensionIt specifies the ability to invoke static Java methods as routines from within SQL applications

Contd…

…Contd 2/3

Page 41: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 09

Additional extensions SQL/XML extension

It specifies SQL-based extensions for using conjunction with SQL

SQL/PSM extensionIt standardizes procedural extensions for SQL including flow of control, condition handling, statement condition signals and resignals, cursors and local variables, and assignment of expressions to variables and parameters

…Contd 3/3

Lecture 09

Features of SQL

Processes sets of data as groups rather than as individual unitsProvides automatic navigation to the dataUses statements that are complex and powerful individually

Lecture 09

Tasks for which SQL provides statements

Querying dataInserting, updating and deleting rows in a tableCreating, replacing, altering and dropping objectsControlling access to the database and its objectsGuaranteeing database consistency and integrity

Page 42: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 09

Language ElementsStatements

Have a persistent effect on schemas and data and also controls transactions, program flow, connections, sessions or diagnostics

QueriesRetrieve data based on specific criteria

ExpressionsCan produce either scalar values or tables consisting of columns and rows of data

Contd…

1/2

Lecture 09

Language Elements

PredicatesSpecify conditions that can be evaluated to SQL three-valued

ClausesConstituent components of statements and queries

…Contd 2/2

Page 43: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 10

Types of SQL statements

Lecture 10

Objectives

In this lecture students will study the various types of SQL statements like DDL. DML, DCL statements etc..It also describes the SQL statements that allows to create, alter and destroy database objects.On completing this lecture students will also understand the SQL statements used in data manipulation and control.

Lecture 10

Topics CoveredAn Introduction to Types of SQL statementsSQL DDL StatementsSQL DML StatementsSQL DCL StatementsMiscellaneous SQL Statements

Transaction Control StatementsSession Control StatementsSystem Control StatementEmbedded SQL Statements

Page 44: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 10

SQL statements

Can operate on objects that are created by SQL Can operate on externally described physical files and single-format logical filesDo not refer to the IDDU dictionary definition for program-described files

Lecture 10

Basic Types of SQL statements

Data definition language ( DDL ) statements

Defines the database structure or schema

Data manipulation language ( DML ) statements

Manages data within schema objects

Data control language ( DCL ) statementsAdministers permissions on the databases and database objects

Lecture 10

DDL statementsDDL is a computer language for defining data structuresUsed to modify the structure of tables and other objects in databasePart of SQL that permits database tables to be created or deletedAlso used to define indexes and specify links between tablesImposes constraints between database tables

Page 45: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 10

Examples of DDL statements

CREATE TABLE - creates a new database tableALTER TABLE - alters a database tableDROP TABLE - deletes a database tableCREATE INDEX - creates an indexDROP INDEX - deletes an index

Lecture 10

DML statementsA family of computer languages used by computer programs or database users to insert, delete and update data in a databaseQuery and update commands together form the Data Manipulation Language part of SQLUsed to retrieve and manipulate data in a Relational database

Lecture 10

Examples of DML statements

SELECT - extracts data from a database tableUPDATE - updates data in a database tableDELETE - deletes data from a database tableINSERT INTO - inserts new data into a database table

Page 46: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 10

DCL statementsA computer language and a subset of SQL that is used to control access to data in a databaseControls the security and permissions of the objects or parts of the database(s)DCL are mostly transaction relatedUsed to configure and control database objects

Lecture 10

Examples of DCL statements

GRANT - Allows specified users to perform specified tasksREVOKE - Cancels previously granted or denied permissions

Lecture 10

Transaction Control Statements

Manages changes made by DML statementsExamples:

COMMIT ROLLBACK SAVEPOINT SET TRANSACTION

Page 47: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 10

Session Control Statements

Dynamically manage the properties of a user sessionDo not implicitly commit the current transactionPL/SQL does not support session control statementsExamples:

ALTER SESSION SET ROLE

Lecture 10

System Control Statement

Dynamically manages the properties of an Oracle instanceDoes not implicitly commit the current transactionNot supported in PL/SQLExample:

ALTER SYSTEM

Lecture 10

Embedded SQL Statements

Place DDL, DML and transaction control statements within a procedural language programSupported by the Oracle precompilers

Page 48: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 11

SQL SELECT Statement

Lecture 11

Objective☯On completion of this lecture the

students will understand the concepts of various clauses used in SELECT statement.

Lecture 11

Topics Covered☯What is a SELECT Statement?☯Rules of formulating SELECT

statement☯Different clauses and their

functionality☯Processing of clauses

Page 49: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 11

What is a SELECT statement?☯Used to query data in the tables☯The result is always a table☯ Forms the core of SQL☯Consists of a table expression

followed by several specifications☯Has an additional clause that cannot

be specified within a table expression☯Requires user to tell it which columns

and from what table user wants to obtain data

Lecture 11Rules for formulating SELECT statements

☯ Each select block consists of at least the SELECT clause

☯ The clauses such as WHERE, GROUP BY and ORDER BY are optional

☯ If a WHERE, GROUP BY, HAVING or ORDER BY clause is used, SELECT and FROM clauses are required

☯ The order of the clauses within a select block is fixed

☯ A HAVING clause can be used within a select block only if there is a GROUP BY clause

Lecture 11Modifying Clauses and their Functions

FunctionsModifying Clauses

Sorts the results of prior clauses to produce final output

ORDER BY

Filters out groups that don’t satisfy the search condition

HAVING

Separates rows into groups based on the values in the grouping columns

GROUP BY

Filters out rows that don’t satisfy the search condition

WHERE

Specifies from which tables data should be taken

FROM

Page 50: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 11Processing the Clausesstart

FROM

WHERE

GROUP BY

HAVING ORDER BY

SELECT end result

Lecture 11

Basic Syntax of SELECT☯SELECT column1,

column2,.....columnx FROM table_name ;

☯Ex. To select the MemberId and FirstName columns from all records in the MemberDetails table, the SQL statement is

SELECT MemberId, FirstName FROM MemberDetails ;

Page 51: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 12

FROM & WHERE Clauses

Lecture 12

Objective☯This lecture explains how the SELECT

statement works with the help of other clauses such as FROM and WHERE and helps students to write the SELECT Query with those clauses.

Lecture 12

Topics Covered☯ FROM clause☯WHERE clause☯SELECT with DISTINCT☯Order while using Multiple Clauses

Page 52: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 12

The FROM Clause☯The processing of a table expression

begins at the FROM clause☯Each table from which we use

columns in the other clauses should be specified here

☯ In the FROM clause we specify the tables from which the result of a table expression will be retrieved

☯The FROM clause is used for specifying which tables are to be queried

Lecture 12

Examples of FROM Clause

☯How to show the entire contents of the CITIES table of EXTRA database?

SELECT * FROM EXTRA.CITIES

☯ JIM wants to retrieve the entire contents of the PENALTIES table, which has been created by BOB. (Assume that JIM has the authority to query this table.)

SELECT * FROM BOB.PENALTIES

Contd…

Lecture 12

Examples of FROM Clause

Mega State

Big City Tiny Terrace

3

Golden State

Windy Village

Winding Road

2

New StateOrange Town

Main Street

1

StateCityStreetLocationId

Queries to obtain this result?

SELECT * FROM Location; or

SELECT LocationId, Street, City, State FROM Location;

…Contd

Page 53: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 12

Returning Only Distinct Rows

☯ If you want to know all the unique values in a record, how would you go about retrieving them?

By using the DISTINCT keyword.The DISTINCT keyword is added to the SELECT statement’s column listing directly after the SELECT keyword.The DISTINCT keyword works on all columns in combination but all the columns listed in the SELECT statement must be unique

Lecture 12

Example of Distinct

☯ If someone asks which cities members come from, we could try a query similar to

SELECT City FROM MemberDetails ;

Windy Village

Big City

Orange Town

Orange Town

New Town

Orange Town

Townsville

City

Result will be

Contd…

Lecture 12

Example of Distinct

☯ As you can see, Orange Town is listed three times because there are three members from that city. But if you simply want a list of the unique places that members live in

SELECT DISTINCT City FROM MemberDetails ;

Windy Village

Townsville

Orange Town

New Town

Big City

City

Result should be

…Contd

Contd…

Page 54: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 12

Example of Distinct☯ If we change the

previous query to include MemberIdwhich is unique for every single row and rerun the query you end up with all the rows

SELECT DISTINCT City, MemberIdFROM MemberDetails ;

Result will be

…Contd

9Windy Village

1Townsville

7Orange Town

6Orange Town

5Orange Town

4New Town

8Big City

MemberIdCity

Lecture 12

WHERE Clause

☯Allows to set one or more conditions that must be satisfied by each record before it can form part of the results

☯A condition is used to select rows from the intermediate result of the FROM clause

☯Acts as a kind of filter

Lecture 12Filtering Results with the WHERE Clause

☯ if we were asked for a list of members who live in Big City, we would need to specify that the column City must be equal to Big City

SELECT FirstName + ' '+ LastName AS [Full Name] FROM MemberDetails WHERE City = ‘Big City’ ;

Jack Johnson

John Jackson

Full Name

Result will be

Page 55: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 12

Order while using Multiple Clauses

☯ If more than one of the clauses are used, they must appear in the following order:

SELECT column_listFROM table_list[WHERE search_condition] [GROUP BY grouping_column] [HAVING search_condition] [ORDER BY ordering_condition] ;

Page 56: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 13

Operators Used in SQL

Lecture 13

ObjectivesOn completing this lecture students will be able to understand how to use,

The various conditions using comparison operatorsThe comparison operators with SubqueriesThe comparison operators with Correlated SubqueriesConditions coupled with AND, OR and NOTThe IN operatorThe BETWEEN operator

Lecture 13

Topics Covered

Conditions Using Comparison OperatorsConditions Coupled with AND, OR and NOTThe IN OperatorThe BETWEEN Operator

Page 57: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 13

IntroductionIn the WHERE clause, a condition is used to select rows from the intermediate result of the FROM clauseA row is included in the (intermediate) result of the WHERE clause only if the condition is trueIf the condition is false or unknown, the row is kept out of the resultThe conditions consist of one or more expressions

Lecture 13

Conditions Using Comparison Operators

The best-known condition is the one in which the values of two expressions are comparedThe condition is formed by an expression, a comparison operator or relation operator and another expressionThe value on the left of the operator is compared with the expression on the rightThe condition is true, false, or unknown, depending on the operator

Lecture 13

Comparison operators supported by SQL

Not equal to<>

Greater than equal to

>=

Less than equal to<=

Greater than>

Less than<

Equal to=

MeaningComparison Operator

Page 58: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 13

Simple Use of OperatorsHow to get the numbers of the players resident in Stratford

SELECT PLAYERNO FROM PLAYERS WHERE TOWN = 'Stratford‘ ;

Query to obtain the player numbers for players who have league number 7060

SELECT PLAYERNO FROM PLAYERS WHERE LEAGUENO = '7060‘ ;

Lecture 13

Comparison Operators with Subqueries

To find the number, the name and initials of each player who is older than the player with league number 8467

SELECT PLAYERNO, NAME, INITIALS FROM PLAYERS WHERE BIRTH_DATE < ( SELECT BIRTH_DATE FROM PLAYERS WHERE LEAGUENO = '8467' ) ;

Lecture 13

Another CaseFind the number, the town and the sex of each player living in the same town as player 7 and having the same sex as player 2

SELECT PLAYERNO, TOWN, SEX FROM PLAYERS WHERE ( TOWN, SEX ) = ( ( SELECT TOWN FROM PLAYERS WHERE PLAYERNO = 7 ), ( SELECT SEX FROM PLAYERS WHERE PLAYERNO = 2 ) ) ;

Page 59: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 13

Comparison Operators with Correlated SubqueriesHow to get the numbers of the matches played by players living in Inglewood

SELECT MATCHNO FROM MATCHES WHERE 'Inglewood' = ( SELECT TOWN FROM PLAYERS WHERE PLAYERS.PLAYERNO =

MATCHES.PLAYERNO ) ;

Lecture 13

Truth Table for the Logical Operators

UnknownUnknownUnknownUnknownUnknownUnknownUnknownFalseFalseUnknownUnknownTrueUnknownTrueUnknownTrueUnknownFalseUnknownFalseTrueFalseFalseFalseFalseTrueTrueFalseTrueFalseFalseTrueUnknownUnknownTrueFalseTrueFalseFalseTrueFalseTrueTrueTrueTrue

NOT C1C1 OR C2C1 AND C2

C2C1

Lecture 13

Simple Case

Get the numbers, the names, and the towns of all players who live in Plymouth or Eltham

SELECT PLAYERNO, NAME, TOWN FROM PLAYERS WHERE TOWN = 'Plymouth' OR TOWN = 'Eltham' ;

Page 60: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 13

Using NOT Operator

Get the numbers, names, and towns of players who do not live in Stratford

SELECT PLAYERNO, NAME, TOWN FROM PLAYERS WHERE TOWN <> 'Stratford' ;

Similar toSELECT PLAYERNO, NAME, TOWN FROM PLAYERS WHERE NOT ( TOWN = 'Stratford' ) ;

Using <> operator

Using NOT operator

Lecture 13

IN Operator Find the number, name, and town of each player who lives in Inglewood, Plymouth, Midhurst or Douglas

SELECT PLAYERNO, NAME, TOWN FROM PLAYERS WHERE TOWN = 'Inglewood' OR TOWN = 'Plymouth' OR TOWN = 'Midhurst' OR TOWN = 'Douglas' ;

Similar toSELECT PLAYERNO, NAME, TOWN

FROM PLAYERS WHERE TOWN IN ( 'Inglewood', 'Plymouth',

'Midhurst', 'Douglas' ) ;

Without Using IN operator

Using IN operator

Lecture 13

BETWEEN Operator Find the number and date of birth of each player born between 1962 and 1964

SELECT PLAYERNO, BIRTH_DATE FROM PLAYERS WHERE BIRTH_DATE >= '1962-01-01' AND BIRTH_DATE <= '1964-12-31' ;

Similar toSELECT PLAYERNO, BIRTH_DATE FROM PLAYERS WHERE BIRTH_DATE BETWEEN '1962-01-01' AND '1964-12-

31' ;

Using AND operator

Using BETWEEN operator

Page 61: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 14

SELECT – Group By & Having Clauses

Lecture 14

Objective

The Objective of this lecture is to explainThe Group By clauseHow to group on one columnHow to group on two or more columnsHow to group on expressionsGeneral Rules of Group By clauseThe Having clauseGeneral Rules of Having clause

Lecture 14

Topics Covered

What is Group By clause?Cases of Group By clauseGrouping on one columnGrouping on two or more columnsGrouping on expressionsGeneral rules for the Group By clauseIntroduction to Having clauseGeneral rules for the Having clause

Page 62: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 14

What is Group By Clause?

Groups rows on the basis of similarities between themUsed to aggregate dataThe simplest form is the one in which only one column is groupedCan contain two or more columnsWhen rows are grouped, NULL values are also considered to be equalThe GROUP BY clause is frequently used to formulate questions based on the word per

Lecture 14

Cases of Group By Clauses

If all the rows in the PLAYERS table are grouped on the basis of the place of residence, the result would be one group of players per townFrom there we could query how many players there are in each group

Lecture 14

Grouping on One Column

Query to get all the different town names from the PLAYERS table will be

SELECT TOWN FROM PLAYERS GROUP BY TOWN ;

How to find the number of players for each town?

SELECT TOWN, COUNT ( * ) FROM PLAYERS GROUP BY TOWN ;

Contd…

Page 63: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 14

Grouping on One Column

For each team, get the team number, the number of matches that has been played for that team and the total number of sets won

SELECT TEAMNO, COUNT(*), SUM(WON)FROM MATCHES GROUP BY TEAMNO ;

…Contd

Lecture 14

Grouping on Two or More ColumnsFor the MATCHES table, how to get all the different combinations of team numbers and player numbers?

SELECT TEAMNO, PLAYERNO FROM MATCHES GROUP BY TEAMNO, PLAYERNO ;

In this case the result is grouped not on one column but on two and all rows with the same team number and the same player number form a group

SELECT TEAMNO, PLAYERNO FROM MATCHES GROUP BY PLAYERNO, TEAMNO ;

Lecture 14

Grouping on Expressions

Group the players on the basis of their player numbers. Group 1 should contain the players with number 1 up to and including 24. Group 2 should contain the players with numbers 25 up to and including 49 and so on. For each group, get the number of players and the highest player number

SELECT TRUNCATE(PLAYERNO/25,0), COUNT(*), MAX(PLAYERNO) FROM PLAYERS GROUP BY TRUNCATE(PLAYERNO/25,0) ;

Page 64: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 14

General Rules for the GROUP BY Clause

If a select block does have a GROUP BY clause, any column specification specified in the SELECT clause must exclusively occur as a parameter of an aggregated function or in the list of columns given in the GROUP BY clause or in bothAn expression that occurs in the GROUP BY clause can appear in the SELECT clause

Contd…

Lecture 14

General Rules for the GROUP BY Clause

An expression that is used to form groups can also occur in the SELECT clause within a compound expressionIf an expression occurs twice or more in a GROUP BY clause, double expressions are simply removedDISTINCT ( if used outside an aggregation function ) that is superfluous when the SELECT clause includes all the columns specified in the GROUP BY clause

…Contd

Lecture 14

The Having Clause

Selects rows after a GROUP BY clause has been executedCan be used only in combination with a GROUP BY clauseEnables you to select groups with rows based upon their particular group propertiesThe condition in the HAVING clause looks a lot like a normal condition in the WHERE clause

Page 65: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 14

Examples of the HAVING Clause

For each player who has incurred more than 150 worth of penalties in total, find the player number and the total amount of penalties

SELECT PLAYERNO, SUM ( AMOUNT ) FROM PENALTIES GROUP BY PLAYERNO HAVING SUM ( AMOUNT ) > 150 ;

Contd…

Lecture 14

Examples of the HAVING Clause

For each player who is a captain and who has incurred more than 80 worth of penalties in total, find the player number and the total amount of penalties

SELECT PLAYERNO, SUM ( AMOUNT ) FROM PENALTIES WHERE PLAYERNO IN ( SELECT PLAYERNO FROM TEAMS ) GROUP BY PLAYERNO HAVING SUM ( AMOUNT ) > 80 ;

…Contd

Lecture 14

General Rules for the HAVING Clause

Each column specification specified in the HAVING clause must occur within an aggregation function or in the list of columns named in the GROUP BY clauseThe result of an aggregation function always consists of one value for each groupThe result of a column specification, where it has not been grouped consists of a set of values

Page 66: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 15

SELECT With ORDER BY and LIKE

Lecture 15

Objective

This lecture gives an idea about the ORDER BY clause and also explains its implementation. On completion of this lecture students will also be able to understand the use of LIKE operator in SELECT statement.

Lecture 15

Topics Covered

An introduction to ORDER BY clauseSorting on Column NamesSorting on ExpressionsSorting with Sequence Numbers and Column HeadingsSorting in Ascending and Descending OrderThe LIKE Operator

Page 67: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 15

ORDER BY Clause

If the SELECT statement has no ORDER BY clause, the sequence is unpredictableThe addition of an ORDER BY clause at the end of a SELECT statement is the only guarantee that the rows in the end result will be sorted in a certain way

Lecture 15

Sorting on Column NamesSorting on one column is the simplest methodThe sorting consists of one column specificationAllowed to sort on each column specified in the SELECT clause

Lecture 15

ExamplesTo find the payment number and the player number of each penalty incurred and sort the result by player number

SELECT PAYMENTNO, PLAYERNO FROM PENALTIES ORDER BY PLAYERNO ;

To find all player numbers and penalty amounts and sort the result on both columns

SELECT PLAYERNO, AMOUNT FROM PENALTIES ORDER BY PLAYERNO, AMOUNT ;

Page 68: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 15

Sorting on ExpressionsGet for all players the last name, the initials, and the player number, and sort the result on the first letter of the last name

SELECT NAME, INITIALS, PLAYERNO FROM PLAYERS ORDER BY SUBSTR ( NAME, 1, 1 ) ;

Get the player number and the amount of all penalties and sort the result on the average penalty amount of each player

SELECT PLAYERNO, AMOUNT FROM PENALTIES AS P1 ORDER BY ( SELECT AVG ( AMOUNT )

FROM PENALTIES AS P2 WHERE P1.PLAYERNO =

P2.PLAYERNO ) ;

Lecture 15

Sorting with Sequence Numbers and Column Headings

In the ORDER BY clause, we can replace a sorting consisting of column names or expressions with sequence numbersA sequence number assigns a number to the expression in the SELECT clause on which sorting is performedIt is not essential to use sequence numbers

Lecture 15

ExamplesFor each player who has incurred at least one penalty, get the total penalty amount; sort the result on this total

SELECT PLAYERNO, SUM ( AMOUNT ) FROM PENALTIES GROUP BY PLAYERNO ORDER BY 2 ;

For each player, get the player number, the last name, and the sum of his penalties; sort the result on this sum

SELECT PLAYERNO, NAME, ( SELECT SUM ( AMOUNT ) FROM PENALTIES AS PEN WHERE PEN.PLAYERNO = P.PLAYERNO ) FROM PLAYERS AS P ORDER BY 3 ;

Page 69: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 15

Sorting in Ascending and Descending Order

By default, SQL sorts the result in ascending orderThe same result can be achieved by explicitly specifying ASC after the sortingIf DESC is specified, the rows in the result are presented in descending order

Lecture 15

Example

For each penalty, get the player number and the penalty amount; sort the result in descending order on player number and in ascending order on penalty amount

SELECT PLAYERNO, AMOUNT FROM PENALTIES ORDER BY PLAYERNO DESC,

AMOUNT ASC ;

Lecture 15

The LIKE OperatorTo find the name and number of each player whose name begins with an uppercase B

SELECT NAME, PLAYERNO FROM PLAYERS WHERE NAME LIKE 'B%' ;

How to get the name and number of each player whose name ends with a lowercase r

SELECT NAME, PLAYERNO FROM PLAYERS WHERE NAME LIKE '%r' ;

Page 70: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 16

CREATE TABLE

Lecture 16

Objective

This lecture explains about the creation of tables. On completion of this lecture student will be able to create not only the new tables but also the temporary tables. It also explains the process of copying tables and naming tables and columns.

Lecture 16

Topics Covered

Creating New TablesCreating Temporary TablesCopying TablesNaming Tables and ColumnsColumn OptionsDerived Columns

Page 71: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 16

Creating New Tables

The CREATE TABLE statement is used to construct new tablesRows of data can be stored in the tableThe table schema of a table consists of one or more table elementsA column definition contains a column name, a data type, possibly a null specification and possibly a column integrity constraintA new table is built in the current database.

Lecture 16

Basic Syntax of Create Table

CREATE TABLE <table name> ( <column name> <type> [<default

value>] [<column constraints>], … <column name> <type> [<default

value>] [<column constraints>], <table constraint>, … <table constraint> ) ;

Lecture 16

Simple Example

CREATE TABLE vendors ( vendorid CHAR ( 5 ), companyname VARCHAR ( 30 ), repfname VARCHAR ( 20 ), replname VARCHAR ( 20 ), referredby CHAR ( 5 ) ) ;

Creates a table named vendorsThe new table contains five columns and each column has a data type.The new table does not contain any data

Page 72: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 16

Creating Temporary TablesThe temporary table is created with the CREATE TABLE statement by adding the word TEMPORARY to itThe temporary table is essentially owned by one SQL user for a limited time spanEvery SELECT, UPDATE, INSERT and DELETE statement can be executed on temporary tablesSQL removes temporary tables automatically when the application ends

Lecture 16

Cases to create Temporary TableCreate the temporary table SUMPENALTIES and store in it the sum of all penalties

CREATE TEMPORARY TABLE SUMPENALTIES ( TOTAL DECIMAL ( 10, 2 ) ) ;

Create a permanent table and a temporary table with similar names

CREATE TABLE TESTTABLE ( C1 INTEGER ) INSERT INTO TESTTABLE VALUES ( 1 ) CREATE TEMPORARY TABLE TESTTABLE ( C1 INTEGER, C2 INTEGER ) INSERT INTO TESTTABLE VALUES ( 2, 3 ) SELECT * FROM TESTTABLE ;

Lecture 16

Copying Tables

It is possible to create a new table that is based on an existing tableThe specifications and the contents of the existing tables are used to create the new table The table that is created has the same table schema as the original tableIf we want to change certain properties of a column during copying, we have to add a table schema to the CREATE TABLE statement

Page 73: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 16

How to Copy Tables?

Create a copy of the TEAMS table called TEAMS_COPY1

CREATE TABLE TEAMS_COPY1 LIKE TEAMS ;

Create a copy of the TEAMS table called TEAM_COPY2, and copy the contents as well

CREATE TABLE TEAMS_COPY2 AS ( SELECT * FROM TEAMS ) ;

Contd…

Lecture 16

How to Copy Tables?

Create a copy of the TEAMS table and assign the columns TEAMNO and PLAYERNO different names respectively TNO and PNO

CREATE TABLE TEAMS_COPY3 AS ( SELECT TEAMNO AS TNO, PLAYERNO AS PNO FROM TEAMS ) ;

…Contd

Lecture 16

Naming Tables and Columns

Keep the table and column names short but not crypticUse the plural form for table namesDo not use information-bearing namesBe consistentAvoid names that are too longGive columns with comparable populations the same name

Page 74: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 16

Case of Column Options

Create the PENALTIES table in which the default value of the AMOUNT column is equal to 50 and the default value for the PAYMENT_DATE is 1 January 1990

CREATE TABLE PENALTIES ( PAYMENT_DATE DATE NOT NULL

DEFAULT '1990-01-01', AMOUNT DECIMAL ( 7, 2 ) NOT NULL

DEFAULT 50.00 ) ;

Lecture 16

Case of Derived Columns

Create a new version of the MATCHES table that contains an extra column called BALANCE, which holds the difference between the columns WON and LOST

CREATE TABLE MATCHES ( MATCHNO INTEGER NOT NULL PRIMARY

KEY, TEAMNO INTEGER NOT NULL, PLAYERNO INTEGER NOT NULL, WON SMALLINT NOT NULL, LOST SMALLINT NOT NULL, BALANCE AS ABS ( WON - LOST ) ) ;

Page 75: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 17

Datatypes

Lecture 17

Objectives

• When we create a table or cluster, we must specify a datatype for each of its columns. When we create a procedure or stored function, we must specify a datatype for each of its arguments. This lecture helps to understand about the various datatypes used in oracle – sql.

Lecture 17Topics Covered• Datatypes – An Introduction• Oracle Built-in Datatypes

Character DatatypesNUMBER DatatypesLong and Raw DatatypesDatetime and Interval DatatypesLarge Object ( LOB ) DatatypesROWID Datatypes

Page 76: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 17

Datatypes – An Introduction

• Each value manipulated by Oracle has a datatype

• A value's datatype associates a fixed set of properties with the value

• Each value subsequently placed in a column assumes the column's datatype

• The Oracle precompilers recognize other datatypes in embedded SQL programs

Lecture 17

Oracle Built-in Datatypes

Lecture 17

Character Datatypes

• Stores alphanumeric data which are words and free-form text

• Less restrictive than other datatypes

• Stored in strings with byte values corresponding to one of the character sets

Page 77: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 17

Types of Character Datatypes

Lecture 17

Number Datatypes

• Stores zero, positive and negative fixed and floating-point numbers

• If an arithmetic expression whose value has a magnitude greater than or equal to 1.0 x 10126 is specified then an error will be returned

Lecture 17

Precision & Scale

-84 to 127

Number of digits to the right of the decimal point

Scale

1 to 38Total number of digitsPrecision

Page 78: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 17

Long and Raw Datatypes• Stores data that is not to

be interpreted by Oracle• Intended for binary data

or byte strings• Import and Export utilities

do not perform character conversion when transmitting RAW or LONG RAW data

Lecture 17

Datetime & Interval Datatypes

• Values of datetime datatypes are sometimes called datetimes

• Values of interval datatypes are sometimes called intervals

• Both datetimes and intervals are made up of fields

• Stores date and time information

Lecture 17

Datetime Datatypes & Fields

Page 79: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 17

LOB Datatypes• Stores large and

unstructured data such as text, image, video and spatial data up to 4 gigabytes in size

• Can be attributes of a user-defined datatype

• More than one LOB column in a table can be defined

Lecture 17

ROWID Datatype• ROWID stores address of

each row• UROWID stores the

addresses of index-organized and foreign tables

• Oracle creates logical rowidsbased on a table's primary key

• The ROWID pseudocolumnof an index-organized table has a datatype of UROWID

Page 80: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 18

Updating Tables

Lecture 18

Objective

SQL offers various statements for updating the contents of tables statements for inserting new rows, for changing column values and for deleting rows. This lecture describes the extensive features of these statements.

Lecture 18

Topics Covered

Inserting New RowsUpdating Values in RowsDeleting Rows from a Table

Page 81: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 18

Inserting New Rows

The INSERT statement is used to add rows to an existing tableEach INSERT statement corresponds to a new row in a tableAfter the term INSERT INTO, the table name is specifiedThe values that the new row consists of come after VALUES

Lecture 18

Some Guidelines for INSERTEach alphanumeric value must be enclosed in single quotation marksThe column values are separated by commasA date consists of three components: year, month, and day which are separated by hyphensDo not have to specify column names if a value is specified for all columns of the table concerned

Lecture 18

Syntax of INSERT statement

INSERT INTO < table name > [ ( < attribute >, ..., < attribute > ) ] VALUES ( < expression >, ..., <

expression > ) ;INSERT creates a new row in < table name >The new row contains the values determined by the expressions in the VALUES list

Page 82: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 18

Examples of INSERT statement

INSERT INTO ingredients VALUES ( 'EDSDR', 'Ed''s Vanishing

Dressing', 'ounce', 0.1, NULL, DEFAULT, 'EDDRS' ) ;This creates a single, new row in the ingredients tableThe items in the VALUES list are matched one-by-one, in order of the attributes in the ingredients table

Contd…

Lecture 18

Examples of INSERT statementIf the TEAMS table contains three columns and three values have been specified, the INSERT statement will beINSERT INTO TEAMS

VALUES ( 3, 100, 'third' ) ;INSERT INTO TEAMS ( TEAMNO, PLAYERNO, DIVISION )

VALUES ( 3, 100, 'third' ) ;INSERT INTO TEAMS ( PLAYERNO, DIVISION, TEAMNO )

VALUES ( 3, 100, 'third' ) ;

OR

OR

…Contd

Lecture 18

Updating Values in Rows

We can change the values in existing rows using UPDATEA table reference is used to indicate which table needs to be updatedThe WHERE clause of an UPDATE statement specifies which rows must be changedThe SET clause assigns new values to one or more columns

Page 83: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 18

Syntax of UPDATE statement

UPDATE < table-name > [ [ AS ] < alias > ] SET < column > = < expression >, ..., <

attribute > = < expression > [ WHERE < condition > ] ;

UPDATE changes all rows in <table name> where <condition> evaluates to trueFor each row the SET clause dictates which attributes change and how to compute the new value

Lecture 18

Examples of UPDATE statement

How to set the inventory to 0 for all ingredients in the milk food group?UPDATE ingredients

SET inventory = 0 WHERE foodgroup = 'Milk' ;

How to update the league number for player 95 of PLAYERS table to 2000?UPDATE PLAYERS

SET LEAGUENO = '2000' WHERE PLAYERNO = 95 ;

Lecture 18

Deleting Rows from a Table

We can remove rows from a table using DELETEIf there is no WHERE clause, DELETE removes all rowsDELETE can only remove rows from a single tableDELETE may use correlated subqueries

Page 84: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 18

Syntax of DELETE statement

DELETE FROM < table name > [ [ AS ] < alias > ] [ WHERE < condition > ] ;

DELETE removes all rows from <table name> where <condition> evaluates to true

Lecture 18

Examples of DELETE statement

How to delete all penalties incurred by player 44 from PENALTIES table?DELETE

FROM PENALTIES WHERE PLAYERNO = 44 ;

DELETE FROM PENALTIES AS PEN WHERE PEN.PLAYERNO = 44 ;

OR

Contd…

Lecture 18

Examples of DELETE statementDelete all players of PLAYERS table for whom the year in which they joined the club is greater than the average year that all players from Stratford joined the clubDELETE

FROM PLAYERS WHERE JOINED > ( SELECT AVG ( JOINED ) FROM PLAYERS WHERE TOWN = 'Stratford' ) ;

…Contd

Page 85: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 19

Drop, Rename & Alter

Lecture 19

ObjectiveThe UPDATE, INSERT and DELETE statements update the contents of a table. With SQL, we can also change the structure of a table, even when that table contains millions of rows. We can add columns, change the data type of an existing column, add integrity constraints and can even delete entire tables. This chapter describes all the features to drop tables, to rename them and to change them.

Lecture 19

Topics CoveredDeleting Entire TablesRenaming TablesChanging the Table StructureChanging ColumnsChanging Integrity Constraints

Page 86: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 19

Deleting Entire Tables

The DROP TABLE statement is used to delete a tableSQL removes the descriptions of the table from all relevant catalog tables, along with

all integrity constraints indexesprivileges that are linked to that table

Lecture 19

Basic Syntax & Example

DROP TABLE < tablename > ;Delete the PLAYERS table

DROP TABLE PLAYERS ;After this statement has been processed, the table no longer existsAll linked database objects have been removed as well

Lecture 19

Renaming TablesThe RENAME TABLE statement gives an existing table a new nameBasic Syntax of Rename Statement

RENAME TABLE < table name > TO < table name > ;

Page 87: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 19

ExampleChange the name of the PLAYERS table to TENNIS_PLAYERS

RENAME TABLE PLAYERS TO TENNIS_PLAYERS ;

All other database objects that refer to this table will be changed on execution of this statement

Lecture 19

Changing the Table Structure

SQL supports the ALTER TABLE statement for changing many aspects of the table structureBasic Syntax of ALTER TABLE statement is

ALTER TABLE < table name > < action > ;

Lecture 19

Some Types of Actions with ALTER

Adds a new column to < table name >ADD [ COLUMN ] < column definition >

Change or drop the specified default value from < column name >

ALTER [ COLUMN ] < column name >[ SET DEFAULT < value expression > | DROP

DEFAULT ]

Contd…

Page 88: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 19

Some Types of Actions with ALTER

Delete < column name > from < table name >

DROP [ COLUMN ] < column name > [ CASCADE | RESTRICT ]

Add a new constraint to < table name >ADD < table constraint >

Delete <constraint name> from < table name >

DROP CONSTRAINT < constraint name > [ CASCADE | RESTRICT ]

…Contd

Lecture 19

Changing ColumnsAdd a new column called TYPE to the TEAMS table. This column will show whether it is a ladies' or a men's team

ALTER TABLE TEAMS ADD TYPE CHAR ( 1 ) ;

In the TEAMS table, change the column name BIRTH_DATE to DATE_OF_BIRTH

ALTER TABLE PLAYERS CHANGE BIRTH_DATE DATE_OF_BIRTH DATE ;

Lecture 19

Changing Integrity Constraints

To remove integrity constraints, you can use the DROP version of the ALTER TABLE statementDelete the primary key from the PLAYERS table

ALTER TABLE PLAYERS DROP PRIMARY KEY ;

Delete the check integrity constraint called C1 that is defined on the B column of the T2 table

ALTER TABLE T2 DROP CONSTRAINT C1 ;

Page 89: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 20

Transactions

Lecture 20

ObjectivesDatabases are all about sharing data, so it is common for multiple users to be accessing and even changing the same data at the same time. The simultaneous execution of operations is called concurrency. Sometimes concurrency can get us into trouble if our changes require multiple SQL statements. To deal with such problem, databases allow the grouping of a sequence of SQL statements into an indivisible unit of work called a transaction.

Lecture 20

Topics CoveredWhat is Transaction?Rules to start or end TransactionsStarting TransactionsEnding Transactions with COMMIT and ROLLBACKSavepointACID concept

Page 90: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 20

What is Transactions?A sequence of SQL statements that are treated as a single unit.Used to prevent inconsistency of the data stored in the database.Can be defined as a set of SQL statements that are entered by one user and that are ended by specifying whether all changes are to be made permanent or rolled back.

Lecture 20

Rules to Start or End Transactions

A database transaction can be started asImplicit transactionsExplicit transactions

An Oracle transaction is terminated ifCOMMIT / ROLLBACK statement is issuedDDL statement is executedCurrent Oracle session is logged offHardware or machine failure occurs

Lecture 20

Starting TransactionsSQL starts a transaction automatically when a new statement is executed if there is no currently active transactionImplicit Transactions –

The first SQL statement of an application or the first SQL statement after a COMMIT or ROLLBACK starts a new transaction

Explicit Transactions –In this the transaction is started with the START TRANSACTION statementA START TRANSACTION statement automatically leads to a COMMIT of the changes that are not permanent yet

Page 91: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 20

ExampleINSERT ...

DELETE ... ROLLBACK WORK UPDATE ... ROLLBACK WORK INSERT ... DELETE ... COMMIT WORK UPDATE ... end of program

START TRANSACTION INSERT ... DELETE ... ROLLBACK WORK

START TRANSACTION UPDATE ... ROLLBACK WORK

START TRANSACTION INSERT ... DELETE ... COMMIT WORK

START TRANSACTION UPDATE ... end of program

Using Explicit Transaction

Lecture 20

COMMIT StatementUsed to end the current transaction and make permanent all changes performed in the transactionErases all savepoints in the transaction and releases the transaction's locksCommits an in-doubt distributed transaction manuallyTerminates a read-only transaction begun by a SET TRANSACTION statement

Lecture 20

Syntax of COMMIT

To insert a row into the regions table and commit this changeINSERT INTO regions

VALUES ( 5, 'Antarctica' ) ; COMMIT WORK ;

Page 92: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 20

ROLLBACK StatementUsed to undo work done in the current transactionUsed to manually undo the work done by an in-doubt distributed transactionTo roll back your current transaction, no privileges are necessaryIf savepoint clause is omitted, then the ROLLBACK statement rolls back the entire transaction

Lecture 20

Syntax of ROLLBACK

The following statement rolls back your current transaction to savepoint emp_salROLLBACK TO

SAVEPOINT emp_sal ;

Lecture 20

SAVEPOINT Statement Used to identify a point in a transaction to which can be rolled back laterSavepoint names must be distinct within a given transactionIf we create a second savepoint with the same identifier as an earlier savepoint, then the earlier savepoint is erasedAfter a savepoint has been created, we can either continue processing, commit work, roll back the entire transaction or roll back to the savepoint

Page 93: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 20

Creating Savepoints

To update emp1's and emp2's salary in a table employees, check that the total department salary does not exceed 314,000 and then reenter emp2's salary, enter

UPDATE employees SET salary = 7000 WHERE last_name =

'emp1' ; SAVEPOINT emp_sal ; UPDATE employees SET salary = 12000 WHERE last_name =

'emp2' ; SAVEPOINT emp2_sal ; SELECT SUM ( salary ) FROM employees ; ROLLBACK TO SAVEPOINT emp1_sal ; UPDATE employees SET salary = 11000 WHERE last_name =

'emp2' ; COMMIT ;

Lecture 20

ACID Concept The DBMS provides the following ACID properties for a transaction:

AtomicityConsistencyIsolationDurability

Page 94: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 21

SQL*Plus - An Introduction

Lecture 21

ObjectivesThis lecture gives an idea of an interactive and batch query tool that provides access to the Oracle RDBMS. The SQL*Plus tool is used to generate reports interactively as well as dynamically using the HTML output facility.

Lecture 21

Topics CoveredWhat is SQL*Plus?Uses of SQL*PlusSQL*Plus Command-line User InterfaceConfiguring SQL*PlusEntering SQL*Plus CommandsRunning SQL*Plus Commands

Page 95: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 21

What is SQL*Plus?An interactive and batch query tool that is installed with every Oracle Server or Client installationHas a command-line user interface and more recently a web-based user interface called iSQL*PlusHas its own commands and environmentProvides access to the Oracle RDBMS

Lecture 21

Uses of SQL*PlusTo generate reports interactivelyTo generate reports as batch processesTo generate reports dynamically

By using the HTML output facility of SQL*Plus in combination with server side CGI scriptsBy using the dynamic reporting capability of iSQL*Plus to run a script from a web page

To output the results to Text fileScreenHTML file for browsing on the Internet

Lecture 21

SQL*Plus Command-line User Interface

It is standard on all operating systemsIt is used

To enter, edit, run store, retrieve and save SQL commands and PL/SQL blocksTo format, calculate, store and print query resultsTo list column definitions for any tableTo send messages to and accept responses from an end userTo perform database administration

Page 96: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 21

SQL*Plus running in an X terminal

Lecture 21

Configuring SQL*Plus

SQL*Plus environment is set up throughSite ProfileUser Profile

Login file can be modified The current SQL*Plus system variables in a host operating system file can be set

Lecture 21

Entering SQL*Plus CommandsIn command-line SQL*Plus, the commands are typed at the SQL*Plus promptKinds of commands entered in the command-line are

SQL commands, for working with information in the databasePL/SQL blocks, also for working with information in the databaseSQL*Plus commands, for formatting query results, setting options, and editing and storing SQL commands and PL/SQL blocks

Page 97: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 21

Running SQL*Plus CommandsSQL*Plus treats SQL*Plus commands differently than SQL commands or PL/SQL blocksTo speed up command entry, we can abbreviate many SQL*Plus commands to one or a few letters

Lecture 21

An Example

The command to change the format used to display the column SALARY of a sample view is

COLUMN SALARY FORMAT $99,999 HEADING 'MONTHLY SALARY'

When we run this, the COLUMN command will format the column SALARY with a dollar sign ($) and a comma (,) and will give it a new heading

Page 98: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 22

Formatting SQL*Plus Reports

Lecture 22

ObjectiveOn completing this chapter student will be able to

Format the query results to produce a finished reportFormat ColumnsClarify Report with Spacing and Summary LinesDefine Page and Report Titles and DimensionsStore and Print Query Results

Lecture 22

Topics Covered

Formatting ColumnsClarifying Report with Spacing and Summary LinesDefining Page and Report Titles and DimensionsStoring and Printing Query Results

Page 99: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 22

Formatting ColumnsThrough the SQL*Plus COLUMN command we can

Change Column HeadingsFormat NUMBER ColumnsFormat DatatypesCopy Column Display AttributesList and Reset Column Display AttributesSuppress and Restore Column Display AttributesPrint a Line of Characters after Wrapped Column Values

Lecture 22

Changing Column HeadingsA more useful column heading can be defined with the HEADING clause of the COLUMN command

COLUMN column_name HEADING column_headingTo change a column heading to two or more words, enclose the new heading in single or double quotation marks when we enter the COLUMN commandTo display a column heading on more than one line, use a vertical bar ( | ) where we want to begin a new line

Lecture 22

Formatting NUMBER ColumnsSQL*Plus normally displays numbers with as many digits as are required for accuracyThe COLUMN command identifies the column we want to format and the model we want to use

COLUMN column_name FORMAT modelTo display SALARY with a dollar sign, a comma, and the numeral zero instead of a blank for any zero values, enter the following command

COLUMN SALARY FORMAT $99,990

Page 100: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 22

Copying Column Display AttributesTo give more than one column the same display attributes we must use the LIKE clause of the COLUMN commandTo give the column COMMISSION_PCT the same display attributes you gave to SALARY, but to specify a different heading, enter the following command

COLUMN COMMISSION_PCT LIKE SALARY HEADING BONUS

Lecture 22

Listing and Resetting Column Display Attributes

To list the current display attributes for a given column, use the COLUMN command followed by the column name only

COLUMN column_nameTo reset all column display attributes to their default values, enter:

CLEAR COLUMNS

Lecture 22

Suppressing and Restoring Column Display Attributes

To suppress a column's display attributes, enter a COLUMN command in the following form:

COLUMN column_name OFFTo restore the attributes you defined through COLUMN

COLUMN column_name ON

Page 101: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 22

Printing a Line of Characters after Wrapped Column Values

To print a line of dashes after each wrapped column value, enter the commands:

SET RECSEP WRAPPED SET RECSEPCHAR "-"

We can restrict the width of the column JOB_TITLE and tell SQL*Plus to wrap whole words to additional lines when necessary

COLUMN JOB_TITLE FORMAT A20 WORD_WRAPPED

Lecture 22

Clarifying ReportTo clarify a report

Suppress Duplicate Values in Break ColumnsInsert Space when a Break Column's Value ChangesInsert Space after Every RowUse Multiple Spacing TechniquesList and Remove Break DefinitionsCompute Summary Lines when a Break Column's Value ChangesCompute Summary Lines at the End of the ReportComputing Multiple Summary Values and LinesList and Remove COMPUTE Definitions

Lecture 22

Suppressing Duplicate Values in Break Columns

The BREAK command suppresses duplicate values by default in the column or expression

BREAK ON break_columnWhenever we specify a column or expression in a BREAK command, use an ORDER BY clause specifying the same column or expression

Page 102: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 22

Inserting Space when a Break Column's Value Changes

We can insert blank lines or begin a new page each time the value changes in the break columnTo insert n blank lines

BREAK ON break_column SKIP nTo skip a page

BREAK ON break_column SKIP PAGE

Lecture 22

Inserting Space after Every Row

To skip n lines after every rowBREAK ON ROW SKIP n

To skip a page after every rowBREAK ON ROW SKIP PAGE

Lecture 22

Defining Page and Report Titles and Dimensions

Setting the Top and Bottom Titles and Headers and FootersDisplaying System-Maintained Values in TitlesListing, Suppressing and Restoring Page Title DefinitionsDisplaying Column Values in TitlesDisplaying the Current Date in TitlesSetting Page Dimensions

Page 103: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 22

Storing and Printing Query Results

Creating a Flat FileSending Results to a File

SPOOL file_nameSending Results to a Printer

SPOOL OUT

Page 104: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 23

Group Functions

Lecture 23

Objective

Functions provide a rich toolset for manipulating and massaging data in SQL queries. The focus of this lecture will be on how data can be aggregated to allow users to interact with data at some higher level of granularity than what is stored in the database.

Lecture 23

Topics Covered

What are functions?SQL FunctionsAggregate Functions• AVG• CORR• COUNT• MAX• MIN• RANK• SUM

Page 105: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 23

What are Functions?

Blocks of code that perform an action and referenced by an identifier and can be passed argumentsFunctions in Oracle are similar to object methods in languages like Java or functions or procedures in languages like Visual Basic and CCan be created as standalone objects or included in a package with other objects

Lecture 23

SQL Functions

Built into OracleAvailable for use in various appropriate SQL statementsOracle provides a rich set of functions with the database

Lecture 23

Rules for SQL Functions

If a SQL function is called with an argument of a datatype other than the datatype expected by the SQL function, then Oracle implicitly converts the argument to the expected datatype before performing the SQL functionIf a SQL function is called with a null argument, then the SQL function automatically returns nullWhen SQL functions are applied to LOB columns, Oracle creates temporary LOBs during SQL and PL/SQL processing

Page 106: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 23

Aggregate Functions

Perform a specific operation over all rows in a groupReturn a single result row based on groups of rows rather than on single rowsCan appear in select lists and in ORDER BY and HAVING clausesCommonly used with the GROUP BY clause in a SELECT statement, where Oracle divides the rows of a queried table or view into groupsCan be nestedAll aggregate functions except COUNT( * ) and GROUPING ignore nulls

Lecture 23

AVG Function

AVG returns average value of exprThe following example calculates the average salary of all employees in the employees table:SELECT AVG ( salary ) "Average"

FROM employees ;

Lecture 23

CORR Function

CORR returns the coefficient of correlation of a set of number pairsThe following example calculates the coefficient of correlation between the list prices and minimum prices of products by weight classSELECT weight_class, CORR ( list_price, min_price )

FROM product_informationGROUP BY weight_class ;

Page 107: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 23

COUNT Function

COUNT returns the number of rows in the queryIf the asterisk (*) is specified, then this function returns all rows including duplicates and nullsCOUNT never returns null

Lecture 23

MAX Function

MAX returns maximum value of exprThe following example determines the highest salary in the employees table:SELECT MAX ( salary ) "Maximum"

FROM employees ;

Lecture 23

MIN Function

MIN returns minimum value of exprThe following statement returns the earliest hire date in the employees table:SELECT MIN ( hire_date ) "Earliest"

FROM employees ;

Page 108: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 23

RANK Function

The following example calculates the rank of a hypothetical employee in the sample table employees with a salary of $15,500 and a commission of 5%:SELECT RANK ( 15500, .05 ) WITHIN GROUP

( ORDER BY salary, commission_pct ) "Rank" FROM employees ;

Lecture 23

SUM Function

SUM returns the sum of values of exprThe following example calculates the sum of all salaries in the sample employees table:SELECT SUM ( salary ) "Total"

FROM employees ;

Lecture 23

Summery of SQL Aggregate Functions

IllegalNoAnyNumber of rowsCOUNT ( * )

YesYesAnyNumber of non-null values

COUNT

YesYesNumericSum of expression values

SUM

NoYesAnySmallest expression value

MIN

NoYesAnyLargest expression value

MAX

YesYesNumericAverage expression value

AVG

DISTINCT Meaningful

NULLsIgnored?

Data Type

ReturnsFunction

Page 109: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 24

Aggregating Results with Different Clauses

Lecture 24

Objective

We have already seen in the last lecture that given a set of data, SQL provides us with a single aggregate value over that data. SQL provides several basic aggregation functions. In this lecture we are going to learn how to use different clauses such as WHERE, GROUP BY, HAVING along with these functions.

Lecture 24

Topics Covered

Removing Rows before AggregationRemoving Repeating DataMixing Attributes, Aggregates and LiteralsGroup AggregationRemoving Rows before GroupingSorting GroupsRemoving GroupsAggregates over Expressions

Page 110: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 24

Removing Rows before Aggregation

We can limit the rows used by the aggregate function with a WHERE conditionThe WHERE condition is always applied before any aggregate function is computedSELECT SUM ( price ) AS sales

FROM orders WHERE storeid = 'FIRST' ;

It finds the total sales price at FIRST store in orders table

Lecture 24

Removing Repeating DataAn aggregate function includes all rows even repeats with the noted exceptions of NULLDISTINCT qualifier can be added to remove duplicates prior to computing the aggregate functionIt is legal to use DISTINCT with MIN and MAX, however, it will not alter the resultsCOUNT ( DISTINCT * ) is illegalALL qualifier can be explicitly requested instead of DISTINCT for the inclusion of repeats

Lecture 24

DISTINCT Example

How to find the number of ingredients with a non-NULL food group and the number of distinct non-NULL food groups?SELECT COUNT ( foodgroup )

AS "FGIngreds", COUNT ( DISTINCT foodgroup ) AS "NoFGs" FROM ingredients ;

Page 111: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 24

Mixing Attributes, Aggregates and Literals

Attributes and aggregate functions cannot be mixed usually in the attribute list of a SELECTstatementLiterals and aggregate functions can be mixedHow to mix literals with aggregates?SELECT 'Results: ' AS " ",

COUNT ( * ) AS noingredients, COUNT ( inventory ) AS countedingredients, SUM ( DISTINCT inventory ) AS totalingredientsFROM ingredients ;

Lecture 24

Group AggregationSQL provides a simple mechanism for applying aggregates to all groups in one querySQL uses the GROUP BY clause to specify the attribute(s) that determine the groupingGroups can be defined by multiple attributeswhen we use a GROUP BY clause, we restrict the attributes that can appear in the SELECT clause

Contd…

Lecture 24

Group AggregationIf a GROUP BY clause is present, the SELECT clause may only contain attributes appearing in the GROUP BY clause, aggregate functions or literalsGROUP BY does not require the use of aggregation functions in the attribute listWithout aggregation functions, GROUP BYacts like DISTINCT, forming the set of unique groups over the given attributes

…Contd

Page 112: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 24

GROUP BY Example

Suppose we want the name of the ingredient, not the ingredient ID. However, it is possible that different ingredients have the same name. We can still get the groups we want by using BOTH the ingredient ID and the name in the GROUP BY clauseSELECT name, AVG ( unitprice )

FROM ingredients WHERE unit = 'piece' GROUP BY ingredientid, name ;

Lecture 24

Removing Rows before GroupingWe can eliminate rows from groups using the WHERE clauseRows not satisfying the WHERE predicate are removed before the groups are formedTo find the number of nonbeverages sold at each storeSELECT storeid, COUNT ( * )

FROM orders WHERE menuitemidNOT IN ( 'SODA','WATER' ) GROUP BY storeid ;

Lecture 24

Sorting Groups

We can order our groups using ORDER BYThe aggregate we use in our sort criteria need not be an aggregate from the SELECT listAny attributes in the ORDER BY clause must either be contained within an aggregation function or appear in the GROUP BY clauseSELECT storeid, SUM ( price )

FROM orders GROUP BY storeidORDER BY COUNT ( * ) ;

Page 113: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 24

Removing Groups

The HAVING clause is used to specify a condition for groups in the final resultGroups for which the HAVING condition does not evaluate to true are eliminatedThe condition in the HAVING clause may be over any group attribute or group data aggregationSELECT referredby, COUNT ( * )

FROM vendors WHERE referredby IS NOT NULL GROUP BY referredbyHAVING COUNT ( * ) > 1 ;

Contd…

Lecture 24

Removing Groups

The condition in the HAVING clause may be over any group attribute or group data aggregationHAVING clause is not restricted to aggregation functions in the SELECT list or even aggregation functions over attributes in the GROUP BYThe HAVING clause can use AND, OR and NOT just like the WHERE clause

…Contd

Lecture 24

Aggregates over Expressions

Aggregate functions accept expression parametersSELECT SUM ( unitprice*inventory )

AS invalueFROM ingredients WHERE vendorid = 'VGRUS' ;

We can even use aggregate functions within expressions

Page 114: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 25

Lecture 25

In databases, the data is spread across many tables. Joins enable to combine the data extracted from various tables to form a single result set. SQL supports a number of types of joins. This lecture explains the various types of joins and how they are used in SQL statements.

Lecture 25

Introduction to JoinsEqui JoinNon-equi JoinCross JoinNatural JoinCondition JoinColumn-name JoinOuter JoinUnion Join

Page 115: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 25

Joins are powerful relational operators that combine data from multiple tables into a single result tableAny multitable query is a type of joinThe source tables are joined in the sense that the result table includes information taken from all the source tablesThe simplest join is a two-table SELECTthat has no WHERE clause qualifiers

Lecture 25

SELECT column_nameFROM table1, table2 WHERE logical expression ;

Whenever a join involves more than two tables, the database joins the first two tables based on the join conditions and then joins their resulting tables with the next tableThe maximum number of join conditions needed to join n tables is n - 1

Lecture 25

A basic join with a WHERE clause containing a condition specifying that the value in one column in the first table must be equal to the value of a corresponding column in the second tableCombines rows that have equivalent values for the specified columnsSELECT empname, empno, dept, location

FROM employee, department WHERE employee.deptno = dept. deptno ;

Page 116: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 25

SELECT E.*, C.Salary, C.Bonus, Y.TotalSalesFROM EMPLOYEE E, COMPENSATION

C, YTD_SALES Y WHERE E.EmpID = C.EmployAND C.Employ = Y.EmpNo ;

The statement performs an equi-join on three tables, pulling data from corresponding rows of each one to produce a result table that shows the employees' details, the amount of sales they are responsible for, and their compensation

Lecture 25

It specifies the relationships between columns belonging to different tables by using relational operators other than =Used when there is no direct relationship between the tablesSELECT emp.empname, emp.sal, emp.job, salgrade.grade

FROM emp, salgradeWHERE emp.salBETWEEN SALGRADE.LOSAL AND salgrade.hisal ;

Lecture 25

Can be written using CROSS

It is the keyword for the basic join without a WHERE clauseIt rarely gives the required resultIt can be useful as the first step in a chain of data manipulation operations that ultimately produce the desired resultSELECT *

FROM EMPLOYEE, COMPENSATION ;SELECT *

FROM EMPLOYEE CROSS JOIN COMPENSATION ;

Page 117: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 25

Can be written using NATURAL

It is a special case of an equi-joinRemoves the need to add WHERE clause in the join conditionsIn this all columns in one table that have the same names, types and lengths as corresponding columns in the second table are compared for equalitySELECT E.*, C.Salary, C.Bonus

FROM EMPLOYEE E, COMPENSATION C WHERE E.EmpID = C.EmpID ;

SELECT E.*, C.Salary, C.BonusFROM EMPLOYEE E NATURAL JOIN COMPENSATION C ;

Lecture 25

It is like an equi-join, except the condition being tested does not have to be equalThe condition is contained in an ONclause rather than a WHERE clauseIf the condition is satisfied, the corresponding row becomes part of the result table

Lecture 25

The column-name join is like a natural joinWith this, we can select which same-name columns to compare

Page 118: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 25

An extension of equi and non-equi joinsReturns all rows returned by equi and non-equi join and rows from one table that do not match any row from the other tableON operator is provided for implementationTo write a query that performs an outer join of tables A and B and returns all rows from A, use the LEFT [ OUTER ] JOIN syntax in the FROM clause

Contd…

Lecture 25

To write a query that performs an outer join of tables A and B and returns all rows from B, use the RIGHT [ OUTER ] JOIN syntax in the FROM clauseTo write a query that performs an outer join and returns all rows from A and B, extended with nulls if they do not satisfy the join condition, use the FULL [ OUTER ] JOINsyntax in the FROM clause

…Contd

Lecture 25

The statement to find the employee name, employee id, department name and location of the employees from Employee and Department tables isSELECT empname, empid, dept, location

FROM Employee, DepartmentWHERE Employee.deptno ( + ) =

Department.deptno ;

Page 119: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 25

Makes no attempt to match a row from the left source table with any rows in the right source tableCreates a new virtual table that contains the union of all the columns in both source tablesThe table resulting from a union join contains all the columns of both source tables and the number of rows that it contains is the sum of the number of rows in the two source tables

Page 120: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 26

Lecture 26

SQL provides a powerful tool in the form of nested queries also called as subqueries, that can be used in all four SQL data statements. This chapter will define and illustrate the use of subqueries in SQL statements.

Lecture 26

What is nested query?Return typeGuidelines while using subqueriesCreating a subqueryMultilevel subqueryExecution of statement in multilevel subquerySubqueries with Empty Results

Page 121: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 26

A SELECT statement that is nested within another SQL statementExecuted prior to execution of their containing SQL statementAlways enclosed within parenthesesComputes results that are used by an outer query

Lecture 26

A nested query returns a table that may consist of:

A single row with a single columnMultiple rows with a single columnMultiple rows and columns

When the containing statement has finished executing, the tables returned by any nested queries are discarded

Lecture 26

Only the columns of the outermost query can appear in the result tableAll SQL comparison operators work with nested queriesNested queries are restricted in what they can returnMost often found in the WHERE clause of a SELECT, UPDATE or DELETEstatement

Page 122: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 26

A query to find the vendorid of Veggies_R_Us will be:

SELECT vendoridFROM vendors WHERE companyname = 'Veggies_R_Us' ;

A query to find the names of ingredients provided by VGRUS will be:

SELECT name FROM ingredients WHERE vendorid = 'VGRUS' ;

Contd…

Lecture 26

We combine the two queries by replacing the literal string in second query with first query

SELECT name FROM ingredients WHERE vendorid =

( SELECT vendoridFROM vendors WHERE companyname = 'Veggies_R_Us' ) ;

…contd

Lecture 26

SELECT name, price FROM items WHERE itemid IN

( SELECT itemidFROM madewithWHERE ingredientid IN

( SELECT ingredientidFROM ingredients WHERE vendorid =

( SELECT vendoridFROM vendors WHERE companyname =

'Veggies_R_Us' ) ) ) ;

Subquery 3

Subquery 2

Subquery 1

Page 123: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 26

SQL first executes the innermost subquery, Subquery 1This returns a table containing one column, vendorid, with one rowSubquery 2 executes next and returns a table containing one column, ingredientid, with a row for each ingredient supplied by the vendor ID returned from Subquery 1

Contd…

Lecture 26

Next Subquery 3 executes and returns a table containing one column, itemid, with a row for each ingredient returned by Subquery 2Finally, the outer query executes and returns a table containing two columns, name and price, with a row for each item returned by Subquery 3

…contd

Lecture 26

If the subquery result is empty, SQL returns NULL

SELECT companynameFROM vendors WHERE referredby =

( SELECT vendoridFROM vendors WHERE companyname = 'No Such

Company' ) ;

Contd…

Page 124: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 26

The subquery results are empty so the subquery returns NULL. Evaluating the outer query, referredby = NULL returns unknown for each row in vendorsConsequently, the outer query returns an empty result table

…contd

Page 125: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 27

Lecture 27

Some subqueries are completely self-contained called noncorrelatedsubqueries while others reference columns from the containing statement called correlated subqueries. The next section will explore these two subquerytypes.

Lecture 27

Non-correlated SubqueriesSingle-Row, Single-Column SubqueriesMultiple-Row, Single-Column SubqueriesMultiple-Column SubqueriesThe WITH Clause

Correlated SubqueriesData Manipulation Using Correlated Subqueries

Page 126: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 27

May be executed alone and does not reference anything from the containing statementMost subqueries that are encountered will be of this type unless update or delete statements are usedAllows each row from the containing SQL statement to be compared to a set of values

Lecture 27

Single-row, single-column subqueriesMultiple-row, single-column subqueriesMultiple-column subqueries

Lecture 27

Returns a single row with a single columnTreated like a scalar by the containing statementMay appear on either side of a conditionThe usual comparison operators ( =, <, >, !=, <=, >= ) are employed

Page 127: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 27

The query that illustrates the utility of single-row, single-column subqueries by finding all employees who are earning above average salarySELECT lname

FROM employee WHERE salary >

( SELECTAVG ( salary ) FROM employee ) ;

Lecture 27

When a subquery returns more than one row, it is not possible to use only comparison operatorsIf the subquery returns more than one row, then we will not be able to use it on one side of an equality conditionFor working with multi-row subqueries, IN, ANY and ALL operators are used

Lecture 27

The query to retrieve the name of the highest paid person in department 30SELECT fname, lname

FROM employee WHERE dept_id = 30

AND salary >= ALL( SELECT salary FROM employee WHERE dept_id = 30 ) ;

Page 128: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 27

SELECT account_id, product_cd, cust_idFROM account WHERE open_branch_id =

( SELECT branch_idFROM branch WHERE name = 'Woburn Branch' ) AND open_emp_id IN( SELECT emp_idFROM employee WHERE title = 'Teller'

OR title = 'Head Teller' ) ;Contd…

Lecture 27

The query uses two subqueries to identify the ID of the Woburn branch and the IDs of all bank tellers, and the containing query then uses this information to retrieve all checking accounts opened by a head teller at the Woburn branch.

…contd

Lecture 27

To eliminate the inefficiency of executing the same subquery multiple times, Oracle introduced the WITH clauseThe WITH clause creates a temporary data setThe WITH clause acts in many ways like another type of subquery called the inline view

Page 129: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 27

Suppose we want to show all employees making more than the average salary, and we want to show how much above the average each employee makes

WITH avg_sal AS ( SELECT AVG ( salary ) valFROM employee )

SELECT e.emp_id, e.lname, e.fname, ( SELECT ROUND ( e.salary - val ) FROM avg_sal ) above_avgFROM employee e WHERE e.salary > ( SELECT val

FROM avg_sal ) ;

Lecture 27

References one or more columns from its containing SQL statementExecuted once for each candidate row in the intermediate result set of the containing queryUsed to test whether relationships exist without regard to cardinalityDependent on its containing statement from which it references one or more columns

Lecture 27

SELECT c.cust_id, c.cust_type_cd, c.cityFROM customer c WHERE 2 = ( SELECT COUNT ( * )

FROM account a WHERE a.cust_id =

c.cust_id ) ;The query uses a correlated subquery to count the number of accounts for each customer and the containing query then retrieves those customers having exactly two accounts

Page 130: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 27

An example of a correlated subqueryused to modify the last_activity_datecolumn in the account table:UPDATE account a

SET a.last_activity_date = ( SELECT MAX ( t.txn_date )

FROM transaction t WHERE t.account_id =

a.account_id) ;

Page 131: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 28

Operators Used in Nested queries

Lecture 28

Objective

If a subquery returns more than one row then we will not be able to use it on one side of an equality condition. However, there are some additional operators that may be used to build conditions with these types of subqueries.

Lecture 28

Topics Covered

IN OperatorALL OperatorANY operatorEXISTS Operator

Page 132: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 28

IN OpeartorWhen we cannot equate a single value to a set of values we can check to see if a single value can be found within a set of valuesThe expression on the left-hand side of the condition is the column nameThe right-hand side of the condition is a set of stringsThe IN operator checks to see if either of the strings can be found in the name column

Lecture 28

Example of IN Operator

SELECT emp_id, fname, lname, title FROM employee WHERE emp_id IN

( SELECT superior_emp_idFROM employee ) ;

The query uses the in operator with a subquery on the right-hand side of the filter condition to see which employees supervise other employees

Lecture 28

ALL OperatorThe ALL operator allows to make comparisons between a single value and every value in a setWe need to use one of the comparison operators ( =, <>, <, >, etc. ) in conjunction with the ALL operatorWhen using NOT IN or <> ALL to compare a value to a set of values, we must be careful to ensure that the set of values does not contain a null value

Page 133: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 28

Examples of ALL Operator

The next query finds all employees whose employee IDs are not equal to any of the supervisor employee IDsSELECT emp_id, fname, lname, title

FROM employee WHERE emp_id <> ALL

( SELECT superior_emp_idFROM employee WHERE superior_emp_id IS

NOT NULL ) ;

Contd…

Lecture 28

Examples of ALL operatorsThis example uses ALL to find accounts having an available balance smaller than all of Frank Tucker's accounts:SELECT account_id, cust_id, product_cd, avail_balance

FROM account WHERE avail_balance < ALL

( SELECT a.avail_balanceFROM account a INNER JOIN individual i ON a.cust_id = i.cust_idWHERE i.fname = 'Frank' AND

i.lname = 'Tucker' ) ;

…Contd

Lecture 28

ANY Operator

The ANY operator allows a value to be compared to the members of a set of valuesA condition using the ANY operator evaluates to true as soon as a single comparison is favorable

Page 134: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 28

Example of ANY OperatorSELECT account_id, cust_id, product_cd, avail_balance

FROM account WHERE avail_balance > ANY ( SELECT a.avail_balanceFROM account a INNER JOIN individual i ON a.cust_id = i.cust_idWHERE i.fname = 'Frank' AND

i.lname = 'Tucker' ) ;The above query finds all accounts having an available balance greater than ANY of Frank Tucker's accounts

Lecture 28

EXISTS operator

The most common operator used to build conditions that utilize correlated subqueries is the EXISTS operatorThe EXISTS operator is used when we want to identify that a relationship exists without regard for the quantityUsing the EXISTS operator, the subquery can return zero, one or many rows

Contd…

Lecture 28

EXISTS Operator

The condition with EXISTS operator simply checks whether any rows were returned by the subqueryNOT EXISTS can be used to check for subqueries that return no rows

…Contd

Page 135: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 28

Example

The query to find all the accounts for which a transaction was posted on a particular day without regard for how many transactions were posted is:SELECT a.account_id, a.product_cd, a.cust_id, a.avail_balance

FROM account a WHERE EXISTS ( SELECT 1

FROM transaction t WHERE t.account_id =

a.account_id AND t.txn_date = '2005-01-22' ) ;

Lecture 28

Example of NOT EXISTS

SELECT a.account_id, a.product_cd, a.cust_idFROM account a WHERE NOT EXISTS ( SELECT 1

FROM business b WHERE b.cust_id = a.cust_id ) ;

This query finds all customers whose customer ID does not appear in the business table

Page 136: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 29

Lecture 29

• In some situations we need to combine the results from two or more SELECT statements. SQL enables us to handle these requirements by using set operations. In this session we will study the set operators used to combine results of different tables.

Lecture 29

• An Introduction• Union• Union All• Intersect• Intersect All• Minus

Page 137: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 29

• As the data in a relational database is distributed across multiple tables, a query usually draws data from more than one table

• SQL has operators that combine data from multiple sources into a single result table

• SQL provides set operators that combines the results of individual table expressions

• Each operator combines data from multiple tables in a different way

Lecture 29

• SQL statements containing set operators are referred to as compound queries

• Each SELECT statement in a compound query is referred to as a component query

• Two SELECTs can be combined into a compound query by a set operation only if

The result sets of both the queries must have the same number of columnsThe data type of each column in the second result set must match the data type of its corresponding column in the first result set

Lecture 29

Displays all rows unique to the first query

MINUS

Displays all distinct rows selected by both queries

INTERSECT

Displays all rows selected by either query along with duplicates

UNION ALL

Displays all rows selected by either query

UNION

DescriptionOperators

Page 138: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 29

• The UNION operator is the SQL implementation of relational algebra’s union operator

• The UNION operator enables to draw information from two or more tables that have the same structure

• The union of two tables returns all the rows that appear in either table and eliminates duplicates

• The UNION DISTINCT operator functions identically to the UNION operator without the DISTINCT keyword

Lecture 29

• The SELECT clauses of all relevant table expressions must have the same number of expressions

• The expressions that will be placed under one another must have comparable data types

• An ORDER BY clause can be specified only after the last table expression

• An additional DISTINCT is superfluous but allowed

Lecture 29

• SELECT cust_nbr, name FROM customer WHERE region_id = 5 UNION SELECT c.cust_nbr, c.nameFROM customer c WHERE c.cust_nbr IN ( SELECT o.cust_nbrFROM cust_order o, employee e WHERE o.sales_emp_id = e.emp_id AND

e.lname = 'MARTIN' ) ;Contd…

Page 139: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 29

• The result set contains only distinct rows• To eliminate duplicate rows, the UNION

operation needs to sort and filter the result set• The result set is sorted on the combination of

all the columns in the SELECT list• Introduce a performance overhead to the

UNION operation

…contd

Lecture 29

• The UNION ALL operator merges the result sets of two component queries

• It returns rows retrieved by either of the component queries, without eliminating duplicates

• With UNION ALL, the number of rows in the final table will always equal the sum of the number of rows in the original tables

• There is no need for the server to check for overlapping data

Lecture 29

• SELECT cust_id, lname name FROM individual UNION ALL SELECT cust_id, name FROM business ;

• It demonstrates how the UNION ALL operator can be used to generate a full set of customer data from the two customer subtype tables

Page 140: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 29

• The ANSI SQL specification includes the INTERSECT operator for performing intersections

• INTERSECT returns only the rows retrieved by both component queries

• INTERSECT removes any duplicate rows found in the overlapping region whereas INTERSECT ALL does not

Lecture 29

• SELECT * FROM NATIONAL ;

8TurleyBob12DrysdaleDon13KoufaxSandy9NewcombeDon11MaglieSalCompleteGamesLastNameFirstName

Contd…

Lecture 29

• SELECT * FROM AMERICAN ;

8TurleyBob14ReynoldsAllie

10LarsonDon12FordWhiteyCompleteGamesLastNameFirstName

…contd

Contd…

Page 141: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 29

• SELECT * FROM NATIONAL INTERSECT SELECT * FROM AMERICAN ;

8TurleyBobCompleteGamesLastNameFirstName

…contd

Lecture 29

• Returns all rows from the first SELECT that are not also returned by the second SELECT

• The corresponding ANSI/ISO SQL keyword is EXCEPT

• Returns the first table minus any overlap with the second table

• If two table expressions are combined with the MINUS operator, the end result consists of only the rows that appear in the result of the first table expression but do not appear in the result of the second

Lecture 29

• SELECT cust_nbr, name FROM customer WHERE region_id = 5 MINUS SELECT c.cust_nbr, c.nameFROM customer c WHERE c.cust_nbr IN

( SELECT o.cust_nbrFROM cust_order o, employee e WHERE o.sales_emp_id = e.emp_idAND e.lname = 'MARTIN' ) ;

Page 142: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 30

PSEUDOCOLUMNS

Lecture 30

OBJECTIVE

In this lecture we are goingto study about the pseudo columns in Oracle.

Lecture 30

TOPICS COVERED

INTRODUCTIONCURRVAL and NEXTVALLEVELROWIDROWNUMXMLDATA

Page 143: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 30

What is PSEUDO COLUMN ?

A pseudo column behaves like a table column, but is not actually stored in the table.

We can select from pseudo columns, but you cannot insert, update, or delete their values.

Lecture 30

CURRVAL & NEXTVAL

CURRVAL : returns the current value of the sequence.

NEXTVAL : increments the sequence and returns the next value.

Lecture 30

Syntax of CurrVal & NextVal

We must qualify CURRVAL and NEXTVAL with the name of the sequence :

Sequence.CURRVALSequence.NEXTVAL

Example :SELECT employees_seq.nextval

FROM DUAL

Page 144: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 30

Usage with another schema

To refer current or next value of the sequence in the schema of another user we must have that privilege and qualify the sequence as :

schema.sequence.CURRVALschema.sequence.NEXTVAL

Lecture 30

Usage with Remote Database

To refer to the value of a sequence on a remote database, we must qualify the sequence with a complete or partial name of a database link:

schema.sequence.CURRVAL@dblink schema.sequence.NEXTVAL@dblink

Lecture 30

LEVEL

For each row returned by a hierarchical query, the LEVEL pseudo column returns 1 for a root row, 2 for a child of a root, and so on. A root row is the highest row within an inverted tree.A child row is any nonroot row.A parent row is any row that has children.A leaf row is any row without children.

Page 145: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 30

Example of LEVEL

Figure shows nodes of an inverted tree with their LEVEL values :

Lecture 30

ROWID

For each row in the database, the ROWID pseudo column returns a row's address. Usually, a rowid value uniquely identifies a row in the database.However, rows in different tables that are stored together in the same cluster can have the same rowid. Values of the ROWID pseudo column have the data type ROWID or UROWID.

Lecture 30

Use of ROWID

They are the fastest way to access a single row. They can show you how a table's rows are stored. They are unique identifiers for rows in a table.

EXAMPLE :

SELECT ROWID, last_name FROM employees WHERE department_id = 20;

Page 146: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 30

ROWNUM

For each row returned by a query, the ROWNUM pseudo column returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.You can use ROWNUM to limit the number of rows returned by a query, as in this example:

SELECT * FROM employees WHERE ROWNUM < 10;

Lecture 30

ROWNUM with Order By clause

If an ORDER BY clause follows ROWNUM in the same query, then the rows will be reordered by the ORDER BY clause.

SELECT * FROM employees WHERE ROWNUM < 11 ORDER BY last_name;

Lecture 30

XMLDATA

Oracle stores XMLType data either in LOB or object-relational columns, based on XMLSchema information and how we specify the storage clause. The XMLDATA pseudo column lets us access the underlying LOB or object relational column to specify additional storage clause parameters, constraints, indexes, and so forth.

Page 147: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 31

Lecture 31

In this chapter, we will learn to build and save views for reuseto use views to tie related data back togetherto use views to narrow or limit the data that users are allowed to se

Lecture 31

Introducing ViewsCreating ViewsTypes of ViewsUpdating ViewsDropping Views

Page 148: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 31

A virtual table defined by a queryProvide users with a specific view of the data in the databaseProvides a mechanism to create alternate ways of working with the data in a databaseDefined once and can be used in many queriesMay tie related tables together and pull selected fields out that specific users need

Lecture 31

Structure data in a way that users or classes of users find natural or intuitiveRestrict access to the data such that a user can see and modify exactly what they needSimplify the DBA’s job by building base data structuresSummarize data for reports

Lecture 31

Provides securityProvides the basis for other views or queriesProvides personalization of dataRename fieldsOften used interchangeably with queries

Page 149: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 31

If a query is based on a view, the view name must be looked up and the SQL statement retrieved and then executedIf views are build up based on views, the results may not allow to update the dataViews may allow users to add or delete records that are not part of the view

Lecture 31

CREATE VIEW <view name>[(<column list>)] AS <SELECT statement>

Creates a view named <view name>The column names / types and data for the view are determined by the result table derived by executing <SELECT statement>The number of columns in <column list> must match the number of columns in the <SELECT statement>

Lecture 31

CREATE VIEW vrsAS SELECT ingredientid, name,

inventory, inventory * unitprice AS value

FROM ingredients i, vendors v WHERE i.vendorid = v.vendorid

AND companyname = 'Veggies_R_Us' ;

Contd…

Page 150: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 31

Creates a view named vrsvrs view contains four columns with the names and types of the results from the SELECT statementvrs view shows the ingredients (ingredient ID, inventory, and inventory value) supplied to us by Veggies_R_Us

…contd

Lecture 31

Table Join Viewsjoin related tables back together in order to pull specific fields out of the related tables and display a view across more than one table

Row Viewsselect a subset of all the rows in the larger dataset

Field Viewsselect all of the records but only some of the fields Contd…

Lecture 31

Filtered Windowed Viewsdisplay selected columns from selected rows

Summary Viewsperforms various operations on entire sets of rows, returning a single row representing some operation on the set

…contd

Page 151: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 31

We can even perform INSERT, UPDATE and DELETE on a viewAll DBMSs do not allow updating through viewsUpdates through views can have unexpected consequences, depending on the behavior of the DBMS

Lecture 31

For a view to be updatable, the query defining a view must:

Not contain DISTINCTNot reference the same column twice in the SELECT clauseNot have a GROUP BY or HAVING clauseNot contain UNION, MINUS or INTERSECTContain attributes from only one tableHave exactly one row in a base table that corresponds to each row in the view

…contd

Lecture 31

The DROP VIEW statement deletes a viewEvery other view that references the dropped view is also dropped automaticallyWhen a base table is dropped, all views that have been defined directly or indirectly on that table are also dropped

…contd

Page 152: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 31

DROP VIEW < table specification > [CASCADE | RESTRICT]Using the CASCADE keyword can result in entire chains of views being dropped because views depend on views being droppedThe RESTRICT keyword, tells the DBMS that the drop should fail if any other views depend on the view being dropped

…contd

Page 153: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 32

SEQUENCES

Lecture 32

Objective

In this lecture we will learn how to create, maintain and use sequences.

Lecture 32

Topics Covered

IntroductionCreating SequenceConfirming SequenceUsing SequenceModifying SequenceRemoving Sequence

Page 154: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 32

What is a Sequence ?A sequence :

Automatically generates unique numbersIs a sharable objectIs typically used to create a primary key valueReplaces application codeSpeeds up the efficiency of accessing sequence values when cached in memory.

Lecture 32

The CREATE SEQUENCE Statement Syntax

CREATE SEQUENCE sequence [ INCREMENT BY n ] [ START WITH n ] [ { MAXVALUE n | NOMAXVALUE } ] [ { MINVALUE n | NOMINVALUE } ] [ { CYCLE | NOCYCLE } ] [ { CACHE n | NOCACHE } ] ;

Contd…

Lecture 32

Creating a SequenceCreate a sequence name EMPNO_SEQ to be used for the primary key of the DEPARTMENTS table.Do not use the CYCLE option.

CREATE SEQUENCE empno_seqINCREMENT BY 10START WITH 120MAXVALUE 9999NOCACHENOCYCLE;

Sequence created.

Page 155: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 32

Confirming Sequences

Verify your sequence values in the USER_SEQUENCES data dictionary table.

SELECT sequence_name, min_value, max_value, increment_by, last_number

FROM user_sequences;

The LAST_NUMBER column displays the next available sequence number if NOCACHE is specified.

Lecture 32

Using a Sequence

Caching sequence values in memory gives faster access to those values.Gaps in sequence values can occur when:

A rollback occursThe system crashesA sequence is used in another table.

If the sequence was created with NOCACHE, view the next available value, by querying the USER_SEQUENCES table.

Lecture 32

Modifying a SequenceChange the increment value, maximum value, minimum value, cycle option, or cache option.

ALTER SEQUENCE dept_deptid_seqINCREMENT BY 20MAXVALUE 999999NOCACHENOCYCLE;

Sequence altered.

Page 156: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 32

Guidelines for Modifying a Sequence

We must be the owner or have the ALTER privilege for the sequence.Only future sequence numbers are affected.The sequence must be dropped and re-created to restart the sequence at a different number.Some validation is performed.

Lecture 32

Removing a SequenceRemove a sequence from the data dictionary by using the DROPSEQUENCE statement.Once removed, the sequence can no longer be referenced.

DROP SEQUENCE dept_deptid_seq;Sequence dropped.

Page 157: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 33

Lecture 33

After completing this session we should be able to understand– the concept of integrity constraints– the various types of integrity constraints– the limitations of different integrity constraints– the use of integrity constraints

Lecture 33

What are Integrity Constraints?Types of Integrity Constraints– NOT NULL Constraints– Unique Constraints– Primary key Constraints– Foreign key Constraints– Check Constraints

Scope of Integrity ConstraintsRestrictions of particular Integrity Constraints

Page 158: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 33

Allow to automatically enforce the integrity of dataAllow to filter the data that is placed in a databaseRules that define which data values are valid during INSERT, UPDATE and DELETE operationsConstraints are defined when you create or alter a table

Lecture 33

NOT NULL constraintUnique constraint Primary key constraintForeign key constraintCheck constraint

Lecture 33

Column-level constraints– Declared as part of a column definition and apply

only to that columnTable-level constraints– Declared independently from any column

definitions– Required when we wish to define a constraint

that applies to more than one column

Page 159: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 33

CONSTRAINT [ constraint_name ] constraint_type [ ( column [ ,... ] ) ]

[ predicate ] [ constraint_deferment ] [ deferment_timing ]

Lecture 33

Prohibits a column from containing nullsThe only constraints we can specify inline on XMLType and VARRAY columnsEvery row in the table must contain a value for the columnCannot be specified in a view constraintCannot be specified for an attribute of an object

Lecture 33

The following statement alters the locations_demo table to define and enable a NOT NULL constraint on the country_idcolumn:ALTER TABLE locations_demo

MODIFY ( country_idCONSTRAINT country_nn NOT NULL ) ;

The constraint country_nn ensures that no location in the table has a null country_id

Page 160: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 33

Designates a column as a unique keyWhile defining a unique constraint inline, we need only the UNIQUE keywordWhen a unique constraint is defined out of line, we must also specify one or more columnsTwo rows in the table cannot have the same value for the unique keyWhen we specify a unique constraint on one or more columns, Oracle implicitly creates an index on the unique key

Lecture 33

A table or view can have only one unique keyA composite unique key cannot have more than 32 columnsWe cannot designate the same column or combination of columns as both a primary key and a unique keyWe cannot specify a unique key when creating a subtable or a subview in an inheritance hierarchy

Lecture 33

CREATE TABLE promotions_var1 ( promo_id NUMBER ( 6 ) CONSTRAINT promo_id_u UNIQUE, promo_name VARCHAR2 ( 20 ), promo_category VARCHAR2 ( 15 ), promo_cost NUMBER ( 10,2 ), promo_begin_date DATE, promo_end_date DATE ) ;

Page 161: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 34

Lecture 34

After completing this session we should be able to understand– the primary key constraint– the foreign key constraint– the check constraint

Lecture 34

Primary key ConstraintsForeign key ConstraintsCheck Constraints

Page 162: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 34

Designates a column as the primary key of a table or viewCombines a NOT NULL and unique constraint in one declarationNo primary key value can appear in more than one row in the tableNo column that is part of the primary key can contain a null

Lecture 34

A table or view can have only one primary keyThe size of the primary key cannot exceed approximately one database blockA composite primary key cannot have more than 32 columnsThe same column or combination of columns cannot be designated as both a primary key and a unique key

Lecture 34

CREATE TABLE locations_demo( location_id NUMBER ( 4 ) CONSTRAINT loc_id_pk PRIMARY KEY, street_address VARCHAR2 ( 40 ), postal_code VARCHAR2 ( 12 ), city VARCHAR2 ( 30 ), state_province VARCHAR2 ( 25 ), country_id CHAR ( 2 ) ) ;

Page 163: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 34

Designates a column as the foreign keyEstablishes a relationship between that foreign key and a specified primary or unique keyThe foreign key and the referenced key can be in the same table or viewA foreign key constraint can be defined on a single key column either inline or out of lineThe same column or combination of columns can be designated as both a foreign key and a primary or unique key

Lecture 34

The referenced unique or primary key constraint on the parent table or view must already be definedA composite foreign key cannot have more than 32 columnsThe child and parent tables must be on the same databaseWe cannot define a foreign key constraint in a CREATE TABLE statement that contains an AS subquery clause

Lecture 34

CREATE TABLE dept_20 ( employee_id NUMBER ( 4 ), last_name VARCHAR2 ( 10 ), job_id VARCHAR2 ( 9 ), manager_id NUMBER ( 4 ), hire_date DATE, salary NUMBER ( 7, 2 ), commission_pct NUMBER ( 7, 2 ), department_id CONSTRAINT fk_deptnoREFERENCES departments ( department_id ) ) ;

Page 164: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 34

Lets us specify a condition that each row in the table must satisfyEach row in the table must make the condition either TRUE or unknownWhen Oracle evaluates a check constraint condition for a particular row, any column names in the condition refer to the column values in that rowThe syntax for inline and out-of-line specification of check constraints is the same

Lecture 34

A check constraint cannot be specified for a viewThe condition of a check constraint can refer to any column in the tableThe condition of a check constraint cannot refer to columns of other tablesConditions of check constraints cannot contain – subqueries and scalar subquery expressions– Nested table columns or attributes– The pseudocolumns CURRVAL, NEXTVAL, LEVEL or

ROWNUM, etc.

Lecture 34

CREATE TABLE divisions ( div_no NUMBER CONSTRAINT check_divnoCHECK ( div_no BETWEEN 10 AND 99 ) DISABLE, div_name VARCHAR2 ( 9 ) CONSTRAINT check_divnameCHECK ( div_name = UPPER ( div_name ) ) DISABLE, office VARCHAR2 ( 10 ) CONSTRAINT check_officeCHECK ( office IN ( 'DALLAS', 'BOSTON',

'PARIS','TOKYO' ) ) DISABLE ) ;

Page 165: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 35

INTEGRITY CONSTRAINTS - III

Lecture 35

Objective

• In this lecture we will learn – naming the constraints– enabling and disabling constraints– adding and dropping of constraints.

Lecture 35

Topics CoveredDefining ConstraintsAdding a Constraint Dropping a ConstraintDisabling ConstraintsEnabling ConstraintsNaming ConstraintsCascading ConstraintsViewing Constraints

Page 166: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 35

Defining Constraints

Syntax for defining constraints is :CREATE TABLE [ schema . ] table

( column datatype [ DEFAULT expr ] [ column_constraint ] , . . .[ table_constraint ] [ , . . . ] ) ;

Constraints are usually created at the same time as the table.

Lecture 35

Defining Constraints• Constraints can be defined at one of the two

levels :

• Column Constraint Levelcolumn [ CONSTRAINT constraint_name ]

constraint_type,

• Table Constraint Levelcolumn , . . .

[ CONSTRAINT constraint_name ] constraint_type ( column , . . . ) ,

Lecture 35

Adding ConstraintsALTER TABLE statement is used to add a constraint using ADD clause.We can add or drop a constraint but cannot modify its structure.NOT NULL constraint can be added using the MODIFY clause

ALTER TABLE tableADD [ CONSTRAINT constraint ] type ( column ) ;

Page 167: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 35

Dropping ConstraintsALTER TABLE statement with DROP clause is used to drop a constraint.When we drop an integrity constraint, that constraint is no longer enforced by the Oracle server ad is no longer available in the data dictionary.To drop a constraint, we can identify the constraint name from USER_CONSTRAINTS and USER_CONS_COLUMNS data dictionary view.

Lecture 35

Dropping ConstraintsSyntax : ALTER TABLE tableDROP PRIMARY KEY | UNIQUE ( column ) |

CONSTRAINT constraint[ CASCADE ] ;

The CASCADE option of the DROP clause causes any dependent constraints also to be dropped.Example :

ALTER TABLE employeesDROP CONSTRAINT emp_mgr_fk;

Table altered.

Lecture 35

Disabling ConstraintsFor deactivating an integrity constraint execute the DISABLE clause of ALTER TABLE statement.We need to apply CASCADE option to disable dependent integrity constraints.

ALTER TABLE tableDISABLE CONSTRAINT constraint [ CASCADE ] ;

We can use DISABLE clause in both CREATE TABLEand ALTER TABLE statement.Disabling a unique or primary key constraint removes the unique index.

Page 168: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 35

Enabling ConstraintsWe can activate an integrity constraint currently disabled in table definition by using ENABLE clause.A UNIQUE or PRIMARY KEY index is automatically created if we enable a unique or primary key constraint.

ALTER TABLE tableENABLE CONSTRAINT constraint ;

If we enable a constraint, that constraint applies to all the data in the table. All the data in the table must fit the constraint.

Lecture 35

Example of Enabling and Disabling constraints

Disabling ConstraintALTER TABLE employeesDISABLE CONSTRAINT emp_id_pkCASCADE ;

Table altered.Enabling Constraint

ALTER TABLE employeesENABLE CONSTRAINT emp_id_pk ;Table altered.

Lecture 35

Naming Constraints• Oracle enables us to specify names for the

constraints while defining them at column level.

• We need to specify constraint name when we define constraints.

• Oracle automatically generates names for constraints, if we do not specify them.

• Automatically generated names are in the form, SYS_C######.

• These names do not include table name or type of constraint.

Page 169: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 35

Example of Naming ConstraintsCREATE TABLE supplier(s_id NUMBER ( 5 ) CONSTRAINT supl_pk PRIMARY KEY ,s_lname VARCHAR2 ( 15 ) , s_fname VARCHAR2 (15 ) ,s_city VARCHAR2 ( 30 ) CONSTRAINT supl_chkCHECK ( s_city in ( ‘ Delhi ’ , ‘ Noida ‘ , ‘ Nagpur ‘ ) ) ,s_state VARCHAR2 ( 20 ) DEFAULT ‘ Delhi ‘ ) ;

The above listing shows specifying name, sppl_pk for PRIMARY KEY constraint that we create on s_id column of supplier table.Similarly, we can specify names for other constraints at column level.

Lecture 35

Cascading ConstraintsThe CASCADE CONSTRAINT clause is used along with DROP column clause.CASCADE CONSTRAINT clause drops all referential integrity constraints that refer to the primary and unique keys defined on the dropped columns.The CASCADE CONSTRAINTS clause also drops all multicolumn constraints defined on dropped columns.

Lecture 35

Viewing ConstraintsTo view all the constraint definitions and names we query USER_CONSTRAINTS table.

SELECT constraint_name, constraint_type,search_condition

FROM user_constraintsWHERE table_name = ‘ EMPLOYEES ‘ ;

The example will display the constraints on EMPLOYEES table.We can view columns associated with the constraint names in the USER_CONS_COLUMNS data dictionary view.

Page 170: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 36

Lecture 36

PL/SQL stands for Procedural Language extensions to the Structured Query Language. This chapter surveys what the PL/SQL is and points out the advantages they offer. It also acquaints with the basic concepts behind PL/SQL.

Lecture 36

Why PL/SQL?What is PL/SQL?The Origins of PL/SQLAdvantages of PL/SQL

Page 171: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 36

SQL does not have any procedural capabilitiesSQL statements are passed to the Oracle Engine one at a timeWhile processing an SQL sentence if an error occurs, the Oracle engine displays its own error messagesTo overcome such disadvantages Oracle provides PL/SQL

Lecture 36

A block structured language that enables developers to combine the power of SQL with procedural statementsStands for Procedural Language extensions to the Structured Query LanguageAn extension of non-procedural SQLEnables to access and manipulate the data of an Oracle database

Lecture 36

In 1988, Oracle Corporation released Oracle Version 6Key component of the version was the so-called procedural option or PL/SQLSQL*Forms V3.0 incorporated the PL/SQL engine for the first time on the tools side

Page 172: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 36

PL/SQL is a completely portable, high-performance transaction processing language with advantages:– Support for SQL– Support for object-oriented programming– Better performance– Higher productivity– Full portability– Tight integration with Oracle– Tight security

Lecture 36

PL/SQL allows to use all the SQL data manipulation, cursor control, and transaction control commandsPL/SQL allows to use all the SQL functions, operators and pseudocolumnsPL/SQL fully supports SQL datatypesPL/SQL supports dynamic SQL

Lecture 36

By encapsulating operations with data, object types let us move data-maintenance code out of SQL scripts and PL/SQL blocks into methodsObject types allow for realistic data modelingObject types hide implementation details, so that we can change the details without affecting client programs

Page 173: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 36

With PL/SQL, an entire block of statements can be sent to Oracle at one timePL/SQL stored procedures are compiled once and stored in executable formPL/SQL also improves performance by adding procedural processing power to Oracle tools

Lecture 36

PL/SQL adds functionality to non-procedural tools such as Oracle Forms and Oracle ReportsAn entire PL/SQL block is used in an Oracle Forms triggerPL/SQL is the same in all environments

Lecture 36

Applications written in PL/SQL are portable to any operating system and platform on which Oracle runsPL/SQL programs can run anywhere Oracle can runPL/SQL permits to write portable program libraries that can be reused in different environments

Page 174: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 36

PL/SQL manipulates Oracle data easily and efficientlyPL/SQL helps to write high-performance codeThe %TYPE and %ROWTYPE attributes further integrate PL/SQL with SQLPL/SQL provides data independence, reduces maintenance costs and allows programs to adapt as the database changes to meet new business needs

Lecture 36

PL/SQL stored procedures enable to partition application logic between the client and serverDatabase triggers written in PL/SQL can disable application updates selectively and do content-based auditing of user insertsPL/SQL restricts access to Oracle data by allowing users to manipulate it only through stored procedures

Page 175: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 37

Lecture 37

• In this lecture we will learn PL/SQL Block structure and execution of different blocks.

Lecture 37

• What is PL/SQL Block structure?• Anonymous Blocks• Named Blocks• Nested Blocks

Page 176: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 37

• In PL/SQL, the smallest meaningful grouping of code is known as a BLOCK.

• A block is a unit of code that provides execution and scoping boundaries for variable declarations and exception handling.

• A PL/SQL block has four different sections , only one of which is mandatory.

Lecture 37

Header SectionUsed only for Named blocks. The header

determines the way the named blocks or programs must be called, optional.Declaration Section

Identifies variables, cursors and sub blocks that are referenced in the execution and exception sections, optional.

contd . . .

Lecture 37

Execution SectionContain statements the PL/SQL runtime

engine will execute at runtime, mandatory.Exception Section

Handles exceptions for normal processing (warnings and error conditions), optional.

…contd

Page 177: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 37

Lecture 37

• Anonymous block in PL/SQL lacks header section altogether, instead it begins with either DECLARE or BEGIN.

• This block cannot be called by any other block i.e. it does not have a handle for reference.

• Instead, anonymous blocks serve as containers that execute PL/SQL statements, usually including calls to procedures and functions.

• Anonymous blocks execute a series of statements and then terminate, thus acting like procedures.

Lecture 37

[ DECLARE ... declaration statements ... ]

BEGIN ... one or more executable statements ...

[ EXCEPTION ... exception handler statement... ] END; The square brackets indicate an optional part of the syntax. You must have BEGIN and END statements, and you must have at least one executable statement.

Page 178: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 37

While anonymous PL/SQL blocks are indispensable, the majority of code you write will be in named blocks.This is a PL/SQL block stored in the database as a subprogram and identified by a unique name.This block is implemented by means of stored subprograms and database triggers.

Lecture 37

PL/SQL shares with Ada and Pascal the additional definition of being a block-structured language, that is, blocks may "nest" within other blocks. In contrast, the C language has blocks, but standard C isn't strictly block-structured, because its subprograms cannot be nested .Other terms you may hear for nested block are enclosed block , child block , or sub-block; the outer PL/SQL block may be called the enclosing block or the parent block .

Contd . . .

Lecture 37Contd . . .

Page 179: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 38

Lecture 38

• PL/SQL lets us declare constants and variables, then use them in SQL and procedural statements anywhere an expression can be used. In this session we will study the use of variables and constants in PL/SQL along with the use of comments.

Lecture 38

• What are variables?• Declaring variables• Assigning values to variables• Declaring Constants• What are comments?• Single Line comments• Multi-line comments

Page 180: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 38

• Variables in PL/SQL blocks are named variables

• Must begin with a character• Maximum 29 characters• Reserved words cannot be variable

names unless enclosed within “…”• Case is insignificant in variable name• A space cannot be used in a variable

name

Lecture 38

• Suppose we want to declare a variable named part_no to hold 4-digit numberspart_no NUMBER ( 4 ) ;

• And a variable named in_stock to hold the Boolean value TRUE or FALSEin_stock BOOLEAN ;

Lecture 38

• Ways of assigning values to a variable– uses the assignment operator ( := )

• valid_id := FALSE ;– by selecting or fetching database

values into it• SELECT sal * 0.10 INTO bonus

FROM empWHERE empno = emp_id ;

Contd…

Page 181: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 38

– by passing value as an OUT or IN OUT parameter to a subprogram

• DECLAREmy_sal REAL ( 7, 2 ) ; PROCEDURE adjust_salary( emp_id INT, salary IN OUT REAL ) IS ... BEGINSELECT AVG ( sal ) INTO my_salFROM emp ; adjust_salary ( 7788, my_sal ) ; -- assigns a new value to my_sal

Contd…

Lecture 38

• Keyword CONSTANT must be added• A value must be immediately

assigned• No more assignments to the

constant are allowed• Example that declares a constant

named credit_limit:credit_limit CONSTANT REAL := 5000.00 ;

Lecture 38

• Inline documentation, otherwise known as comments , is an important element of a good program

• The PL/SQL compiler ignores comments

• Adding comments to your program promotes readability and aids understanding

• Comments are used to describe the purpose and use of each code segment

Page 182: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 38

• Single-Line Comment – Begins with a double hyphen ( -- )

anywhere on a line and extend to the end of the line

• Multi-line Comments– Begins with a slash-asterisk ( /* ) and

ends with an asterisk-slash ( */ )

Lecture 38

• Cannot be separated by a space or any other characters

• All text after the double hyphen to the end of the physical line is considered commentary and is ignored by the compiler

• The double hyphen comments out the remainder of a physical line, not a logical PL/SQL statement

Lecture 38

• -- begin processing SELECT sal INTO salary FROM emp -- get current salary WHERE empno = emp_id ; bonus := salary * 0.15 ; -- compute bonus

• The following example shows how you can comment-out the line

• -- DELETE FROM emp WHERE comm IS NULL ;

Page 183: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 38

• Multiline comments start with a slash-asterisk ( /* ) and end with an asterisk-slash ( */ )

• PL/SQL considers all characters found between these two sequences of symbols to be part of the comment

• Can be used to block out lines of code for testing purposes

Lecture 38

• PROCEDURE calc_revenue( company_id IN NUMBER ) IS/* | Program: calc_revenue| Author: Steven Feuerstein | Change history: | 9/23/94 - Start program| 06-JUN-1999 - Y2K okay */ BEGIN... END ;

Lecture 38

• Comments cannot be nested• Single-line comments cannot be

used in a PL/SQL block that will be processed dynamically by an Oracle Precompiler program

Page 184: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 39

Lecture 39

►In this lecture we will learn different data types offered by PL/SQL as well as their categorization.

Lecture 39

►Introduction►Scalar Data Types►Composite Data Types►Object Data Types►Other PL/SQL specific Data Types

Page 185: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 39

►Whenever we declare a variable or a constant, we must assign it a data type.

►PL/SQL offers a variety of data types for use.

►These data types are categorized in four broad classes:-

Scalar Data TypesComposite Data TypesObject Data TypesOther PL/SQL specific Data Types

Lecture 39

PL/SQL Data Types

Scalar Composite Object PL/SQL specific

•NUMBER•CHAR•DATE •INTERVAL•TIMESTAMP

•RECORD•Index by table•VARRAY•Nested table

•OBJECT type•LOB•ANY •OBJECT REF

•BOOLEAN•REF CURSOR•User defined

Lecture 39

►Scalar Data type means which can hold a single value.

►Following are some of the scalar data types:• NUMBER: particularly useful when working

with monetary amounts.• CHAR: used for both fixed length ( CHAR )

and variable length ( VARCHAR ) strings.• DATE: stores date and time, resolved to

second. Does not include time zone.

Contd . . .

Page 186: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 39

• INTERVAL: subset of DATE data type and is used to compute intervals between the two dates.

• TIMESTAMP: same as DATE but can be used with time zone option.

TIMESTAMP WITH TIME ZONE:Stores the time zone along with each

date and time value:TIMESTAMP WITH LOCAL TIME ZONE

Stores a date and time that is assumed to be in the local time zone.

Contd . . .

Lecture 39

► Composite data consists of multiple values, such as a record, a collection, or an object type instance.

► Following are some composite data types:• RECORDS:

- is composed of one or more fields. - to initialize a record variable, we have to

assign a second record variable that's compatible with the record variable we are initializing. Contd . . .

Lecture 39

• INDEX-BY TABLE:- composed of a collection of homogenous

elements similar to an array.- the elements in this collection are

unbounded, sparsely distributed, and indexed by integers.

- the individual elements in the index-by tables are elements of a scalar data type or a PL/SQL record.

- we define an index-by table variable by first defining a table type and then declaring a variable of that type.

Page 187: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 39

►Defining the Table Type:TYPE table_type_name IS TABLE OF type [NOT NULL] INDEX BY BINARY_INTEGER;

►Declaring a variable of Table Type:<table_var_name> <table_type_name>;

►Accessing an Index-BY Table:<table_var_name>(<index_value>)

Lecture 39

• VARRAYS:- are bounded single-dimensional arrays

that are limited by a maximum number of elements.

- we can change the upper bound for VARRAYS.

- we use VARRAYS to store a fixed number of elements in a definite order.

- the maximum size of a VARRAY is 2GB.

Lecture 39

►Defining the VARRAY Type:TYPE type_name IS { VARRAY | VARRAYING ARRAY }(max_size) OF data_type [NOT NULL];

►Declaring variable of VARRAY type:<var_name> <VARRAY_type_name>;

►Accessing VARRAY Elements:varray_variable(subscript_index)

Page 188: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 39

• NESTED TABLE:- is an unbounded and unordered single-

dimensional array of data elements, all of the same data type.

- has no maximum limit and can be sparse, that means elements at any given random index can be deleted.

- it is similar to an index-by table except that the INDEX BY BINARY_INTEGER clause is missing in its definition.

Lecture 39

►Defining the NESTED Table Type:TYPE table_name IS TABLE OF data_type[NOT NULL];

►Declaring variable of TABLE Type:<var_name> <TABLE_type_name>;

►Accessing Nested Table elements:nested_table_variable(subscript_index)

Lecture 39

►The object data types include object types:

XML type: is a built-in object type, which enables you to store XML documents in a database column or in a PL/SQL variable.XQuery: query language used in retrieving and constructing XML documents.LOB: Large Objects can store large amounts

from 8 to 128 terabytes of binary data (such as images) or character text data.

Contd . . .

Page 189: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 39

ANY Type: enables us to write programs to manipulate data when we do not know the type of that data until runtime.OBJECT REF:

- built-in data type that references an Object ID of an object table.

- REF is a pointer to a row object in an object table.

Contd . . .

Lecture 39

► Following are some of the PL/SQL specific data types :

BOOLEAN: A variable of this type can have one of only three values: TRUE, FALSE, and NULL.REF CURSOR: allows developers to declare cursor variables, which can be used with static and dynamic SQL statements to implement very flexible requirements.

Contd . . .

Lecture 39

User-Defined Data Types: are used to create arbitrarily complex types of our own, that model closely the structure and behavior of data in systems.

Contd . . .

Page 190: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 40

Records

Lecture 40

Objective

A record is a composite data structure. Each row in a table has one or more columns of various datatypes. Similarly a record is composed of one or more fields. In this session we will study the record data structure and its use in PL/SQL.

Lecture 40

Topics Covered

Records in PL/SQLBenefits of using recordsDefining recordsDeclaring recordsInitializing recordsReferencing recordsAssigning recordsComparing records

Page 191: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 40

Records in PL/SQLA composite data type consisting of individual elements that are logically relatedA group of related data items stored in fields, each with its own name and datatypeThe record as a whole does not have a value of its ownA field in a record can be another record

Lecture 40

Benefits of Using RecordsWhen a record is created, all the different attributes or fields of the subject of that record are abstractedOnce the information is stored in records, operations can be performed on whole blocks of data at a time rather than on each individual attributeUsing records helps to write cleaner codeCorresponding cursors and records can be createdTable-based records can be createdRecords are passed as parameters

Lecture 40

Defining RecordsRECORD types are defined in the declarative part of any PL/SQL block, subprogram or package using the syntaxTYPE record_type_name IS RECORD

( field_name1 datatype [ NOT NULL ] [ DEFAULT value1 | := assign1 ],

field_name2 datatype [ NOT NULL ] [ DEFAULT value2 | := assign2 ],

... ... field_nameN datatype [ NOT NULL ] [

DEFAULT valueN | := assignN ] ) ;

Page 192: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 40

Declaring Records

Syntax is< record_var_name >

< record_type_name > ;record_type_name is the record type defined using the TYPE … RECORDspecificationrecord_var_name is an arbitrary variable name with a data type of the specified record type

Lecture 40

Ways of Declaring Records

Table-based recordUse the %ROWTYPE attribute with a table name to declare a record in which each field corresponds to and has the same name as a column in a table

Cursor-based recordUse the %ROWTYPE with an explicit cursor or cursor variable in which each field corresponds to a column or aliased expression in the cursor SELECT statement

Contd…

Lecture 40

Ways of Declaring Records

Programmer-defined recordUse the TYPE RECORD statement to define a record in which each field is defined explicitly ( with its name and datatype ) in the TYPE statement for that record

…contd

Page 193: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 40

Initializing Records

Record can be initialized in its type declarationDECLARE

TYPE TimeRec IS RECORD( secs SMALLINT := 0,mins SMALLINT := 0,hrs SMALLINT := 0 ) ;BEGIN...END ;

Lecture 40

Referencing Records

To reference an individual field, use dot notation and the following

syntax:record_name.field_nameField hire_date will be referenced in record emp_info as follows:

emp_info.hire_date ...When calling a parameterless function, use the following syntax:

function_name( ).field_name

Lecture 40

Assigning RecordsThe value of an expression is assigned to a specific field in a record using the following syntax: record_name.field_name := expression ;DECLARE

TYPE EmpRec IS RECORD( emp_id emp.empno%TYPE, job_title VARCHAR2 ( 9 ), salary NUMBER ( 7, 2 ) ) ; emp_info EmpRec ; emp_null EmpRec ; BEGINemp_info.emp_id := 7788 ; emp_info.job_title := 'ANALYST' ; emp_info.salary := 3500 ; emp_info := emp_null ; emp_info... END ;

Page 194: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 40

Comparing RecordsTo test for record equality, we must write code that compares each field individually

DECLAREfirst_book summer.reading_list_rt := summer.must_read ; second_book summer.reading_list_rt := summer.wifes_favorite ; BEGIN IFfirst_book.favorite_author = second_book.favorite_authorANDfirst_book.title = second_book.titleANDfirst_book.finish_by = second_book.finish_byTHEN lots_to_talk_about ; END IF ; END ;

Page 195: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 41

Lecture 41

Often, it is necessary to take alternative actions depending on circumstances. On completing this lecture we will be able to use one of the Conditional Control PL/SQL statements that is IF statement.

Lecture 41

What are conditional control statements?Why IF statement?IF THEN combinations

IF THEN END IF ;IF THEN ELSE END IF ;IF THEN ELSIF ELSE END IF ;

Page 196: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 41

The selection structure tests a condition and then executes one sequence of statements instead of another depending on whether the condition is True or False

ConditionTrue False

Selection Statement

Statements Statements

Stop

Lecture 41

The IF statement allows to design conditional logic into the programsThe IF statement lets us execute a sequence of statements conditionallyWhether the sequence is executed or not depends on the value of a condition

Lecture 41

IF conditionTHEN... sequence of executable statements ... END IF ;

condition is a Boolean variable, constant or expression and evaluates to TRUE, FALSE or NULLThe sequence of statements is executed only if the condition is true

Page 197: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 41

IF THEN END IF ;condition between IF and THENdetermines whether the set of statements between THEN and END IF should be executed

IF THEN ELSE END IF ;based on the condition between the IF and THEN keywords, execute the code either between THEN and ELSE or between ELSEand END IF

Contd…

Lecture 41

IF THEN ELSIF ELSE END IF ;selects a condition that is TRUE from a series of mutually exclusive conditions and then executes the set of statements associated with that condition

…contd

Lecture 41

This format is used when we want to choose between two mutually exclusive actionsIn this case IF statement adds the keyword ELSE followed by an alternative sequence of statementsThe sequence of statements in the ELSEclause is executed only if the condition is false or nullthe ELSE clause ensures that a sequence of statements is executed

Page 198: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 41

IF condition THEN... TRUE sequence of executable statements ... ELSE... FALSE / NULL sequence of executable

statements ... END IF ;

Contd…

Lecture 41

The condition is a Boolean variable, constant or expressionIf condition evaluates to TRUE then TRUE sequence of executable statements will be executedIf condition evaluates to FALSE or NULLthen FALSE sequence of executable statements will be executed.Note: the ELSE clause does not have a THEN associated with it

…contd

Lecture 41

IF salary <= 40000 THEN

give_bonus ( employee_id, 0 ) ; ELSE

give_bonus ( employee_id, 500 ) ; END IF ;Here employees with a salary greater than 40,000 will get a bonus of 500 while all other employees will get no bonus at all

Page 199: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 41

It is not an either/or situationProvides a way to handle multiple conditions within a single IF statementUsed with mutually exclusive alternatives i.e., only one condition can be TRUE for any execution of the IFstatementIf the first condition is false or null, the ELSIF clause tests another condition

Lecture 41

An IF statement can have any number of ELSIF clauses; the final ELSE clause is optionalConditions are evaluated one by one from top to bottomIf any condition is true, its associated sequence of statements is executed and control passes to the next statementIf all conditions are false or null, the sequence in the ELSE clause is executed

Lecture 41

IF condition-1 THENstatements-1

ELSIF condition-N THENstatements-N

ELSEelse_statements

END IF ;

Page 200: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 41

BEGIN ... IF sales > 50000 THEN

bonus := 1500 ; ELSIF sales > 35000 THEN

bonus := 500 ; ELSE

bonus := 100 ; END IF ; INSERT INTO payroll

VALUES ( emp_id, bonus, ... ) ; END ;

Contd…

Lecture 41

If the value of sales is larger than 50000, the first and second conditions are true. Bonus is assigned the proper value of 1500 because the second condition is never tested. Note: When the first condition is true, its associated statement is executed Control passes to the INSERT statement.

…contd

Page 201: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 42

Lecture 42

In this lecture we will learn CASE statement which is an improved alternative to the IF . . . ELSIF statement.

Lecture 42

Introduction to CASE StatementSimple CASE StatementSearched CASE StatementCASE Expressions

Page 202: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 42

CASE Statement is a non-object oriented feature of PL/SQL.It is an improved alternative to the IF . . . ELSIF statement.The use of CASE statement provides more compact code and increased usability on the part of the programmer.It increases readability on the part of the code reviewer.

CONTD . . .

Lecture 42

The CASE statement allows us to select one sequence of statements to execute, out of many possible sequences.In addition to CASE statements, PL/SQL also supports CASE expressions.CASE Statements are of two types:

Simple CASE StatementSearched CASE Statement

CONTD . . .

Lecture 42

Associates each of one or more sequences of PL/SQL statements with a value. Chooses which sequence of statements to execute based on an expression that returns one of those values. To select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions.The selector is evaluated only once.

Page 203: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 42

CASE selector WHEN value1 THEN action1; WHEN value2 THEN action2; WHEN value3 THEN action3; ... ... ELSE actionN;

END CASE; When evaluating such a CASE statement, PL/SQL first evaluates selector. It then compares the result of selector with value1. If the two matches, action1 is executed. Otherwise, value2 is checked, and so forth.

Lecture 42

CASE gradeWHEN 'A' THEN

dbms_output.put_line('Excellent');WHEN 'B' THEN

dbms_output.put_line('Very Good');WHEN 'C' THEN

dbms_output.put_line('Good');WHEN 'D' THEN

dbms_output.put_line(‘Poor');ELSE

dbms_output.put_line(‘Invalid grade‘);END CASE;

Lecture 42

The searched CASE statement is a variant of the CASE statement and has no selector defined. Instead of testing on the equality of the selector, the searched CASE statement tests a Boolean expression for a truth value.The search conditions are evaluated sequentially.

Page 204: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 42

CASEWHEN (boolean_condition1) THEN action1;WHEN (boolean_condition2) THEN action2;WHEN (boolean_condition3) THEN action3;... ...ELSE actionN;

END CASE;If a search condition yields TRUE, its WHEN clause is executed. If any WHEN clause is executed, control passes to the next statement, so subsequent search conditions are not evaluated.

Lecture 42

CASEWHEN grade = 'A' THEN

dbms_output.put_line('Excellent');WHEN grade = 'B' THEN

dbms_output.put_line('Very Good');WHEN grade = 'C' THEN

dbms_output.put_line('Good');WHEN grade = 'D' THEN

dbms_output.put_line('Fair');ELSE

dbms_output.put_line('No such grade');END CASE;

Lecture 42

CASE expressions do the same for expressions what CASE statements do for statements.When no WHEN conditions are met, a CASE expression will return NULL. CASE expressions also take two forms:

Simple CASE ExpressionsSearched CASE Expressions

CONTD . . .

Page 205: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 42

Simple CASE expressions lets us choose an expression to evaluate based on a scalar value that we provide as input.Searched CASE expressions evaluate a list of expressions to find the first one that evaluates to TRUE, and then return the result of an associated expression. Do not use END CASE to mark the end of the CASE expression.CASE expressions are terminated by a simple END.

CONTD . . .

Lecture 42

Simple CASE ExpressionCASE expression

WHEN result1 THEN result_expression1 WHEN result2 THEN result_expression2 ... ELSE result_expression_elseEND;

Searched CASE ExpressionCASE

WHEN expression1 THEN result_expression1 WHEN expression2 THEN result_expression2 ... ELSE result_expression_elseEND;

CONTD . . .

Lecture 42

DECLARE boolean_true BOOLEAN := TRUE ; boolean_false BOOLEAN := FALSE ;boolean_null BOOLEAN ; FUNCTION boolean_to_varchar2 (flag IN BOOLEAN) RETURN VARCHAR2 IS BEGIN

RETURN CASE flag WHEN TRUE THEN 'True' WHEN FALSE THEN 'False' ELSE 'NULL' END; END;

BEGIN DBMS_OUTPUT.PUT_LINE(boolean_to_varchar2(boolean_true)); DBMS_OUTPUT.PUT_LINE(boolean_to_varchar2(boolean_false)); DBMS_OUTPUT.PUT_LINE(boolean_to_varchar2(boolean_null)); END;

CONTD . . .

Page 206: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 43

Lecture 43

In this lecture we will learn sequential statements provided by PL/SQL.

- GOTO statement- NULL statement

Lecture 43

IntroductionGOTO StatementRestrictions on GOTO statementNULL StatementUse of NULL Statement

Page 207: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 43

Unlike the IF and LOOP statements, the GOTO and NULL statements are not crucial to PL/SQL programming.The structure of PL/SQL is such that the GOTO statement is seldom needed.The NULL statement can improve readability by making the meaning and action of conditional statements clear.Overuse of GOTO statements can result in complex, unstructured code (sometimes called "spaghetti" code) that is hard to understand and maintain.

Lecture 43

The GOTO statement performs unconditional branching to another executable statement in the same execution section of a PL/SQL block.The general format for a GOTO statement is:

GOTO label_name ;Where label_name is the name of a label identifying the target statement.

CONTD . . .

Lecture 43

The label must be unique within its scope.It must precede an executable statement or a PL/SQL block.When executed, the GOTO statement transfers control to the labeled statement or block.This GOTO label is defined in the program as follows:

<<label_name>>

CONTD . . .

Page 208: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 43

Following is a complete code block containing both a GOTO and a label:

BEGINGOTO second_output; DBMS_OUTPUT.PUT_LINE('This line will never execute.'); <<second_output>>DBMS_OUTPUT.PUT_LINE('We are here!'); END;

Lecture 43

At least one executable statement must follow a label.GOTO cannot be executed from inside an IF clause to a label inside the IF clause.GOTO cannot be executed outside an IF clause to a label inside the IF clause.GOTO cannot branch from an enclosing block into a sub-block.

Lecture 43

Usually when we write a statement in a program, we want it to do something.Sometimes PL/SQL does absolutely nothing, in such cases NULL statement comes in use.The NULL statement passes control to the next statement.The NULL statement has the following format:

NULL;

Page 209: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 43

In a conditional construct, the NULL statement tell us that a possibility has been considered, but no action is necessary. In the following example, the NULL statement shows that no action is taken for unnamed exceptions:EXCEPTION

WHEN ZERO_DIVIDE THEN ROLLBACK; WHEN VALUE_ERROR THEN INSERT INTO errors VALUES ... COMMIT; WHEN OTHERS THEN NULL; END ; CONTD . . .

Lecture 43

In IF statements or other places that require at least one executable statement, the NULL statement is used to satisfy the syntax.Example:

IF rating > 90 THEN compute_bonus(emp_id);

ELSENULL;

END IF; CONTD . . .

Lecture 43

The NULL statement is a handy way to create stubs when designing applications from the top down. A stub is dummy subprogram that lets you defer the definition of a procedure or function until you test and debug the main program. In the following example, the NULL statement meets the requirement that at least one statement must appear in the executable part of a subprogram:

CONTD . . .

Page 210: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 43

PROCEDURE debit_account (acct_id INTEGER, amount REAL) IS BEGIN

NULL ; END debit_account ;

CONTD . . .

Page 211: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 44

Lecture 44

This chapter explores the iterative control structures of PL/SQL, otherwise known as loops, which lets us execute the same code repeatedly.

Lecture 44

Introduction to LoopsThe simple or infinite loopThe FOR loopThe WHILE loopThe EXIT statement

Page 212: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 44

LOOP statements execute a sequence of statements multiple timesThere are three types of loops that perform repetitive control flow

the simple LOOPthe numeric FOR LOOPthe WHILE LOOP

The loop encloses the sequence of statements that is to be repeated

Lecture 44

Starts simply with the LOOP keywordEnds with the END LOOP statementTerminates if EXIT, EXIT WHEN or RETURN is executed within the body of the loopWith each iteration of the loop, the sequence of statements is executed and then control resumes at the top of the loopA raised exception may complete the loop

Lecture 44

[ << label_name >> ] LOOP statement [ statement ] ... END LOOP [ label_name ] ;

Page 213: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 44

DECLAREline_length NUMBER := 50 ; separator VARCHAR2 ( 1 ) := '=' ; actual_line VARCHAR2 ( 150 ) ; i NUMBER := 1 ; BEGIN

LOOP actual_line := actual_line || separator ; EXIT WHEN i = line_length ; i:= i + 1 ;

END LOOP ; DBMS_OUTPUT.PUT_LINE ( actual_line ) ;

END ;Displays a line made of equal signs (=) whose length equals 50The body of the loop must have an explicit EXITcondition

Lecture 44

With the numeric FOR loop, we specify the start and end integer valuesThe number of iterations is known before the loop is enteredIterate over a specified range of integersThe range is part of an iteration scheme, which is enclosed by the keywords FOR and LOOPThe bounds of a loop range can be literals, variables or expressions but must evaluate to numbersThe loop counter can be referenced like a constant but cannot be assigned values

Lecture 44

[ << label_name >> ] FOR index_name IN[ REVERSE ] lower_bound .. upper_boundLOOP statement [ statement ]

... END LOOP [ label_name ] ;

Page 214: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 44

DECLAREline_length NUMBER := 50 ; separator VARCHAR2 ( 1 ) := '=' ; actual_line VARCHAR2 ( 150 ) ; BEGIN

FOR idx in 1..line_length LOOPactual_line := actual_line || separator ;

END LOOP ; DBMS_OUTPUT.PUT_LINE ( actual_line ) ;

END ;No need to declare the index of the FOR LOOPNo need of an EXIT condition for the loop

Lecture 44

Associates a condition with a sequence of statements enclosed by the keywords LOOPand END LOOPBefore each iteration of the loop, the condition is evaluatedIf the condition is true, the sequence of statements is executed, then control resumes at the top of the loopIf the condition is false or null, the loop is bypassed and control passes to the next statementThe number of iterations depends on the condition and is unknown until the loop completes

Lecture 44

[ << label_name >> ] WHILE boolean_expressionLOOP statement [ statement ]

... END LOOP [ label_name ] ;

Page 215: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 44

DECLAREline_length NUMBER := 50 ; separator VARCHAR2 ( 1 ) := '=' ; actual_line VARCHAR2 ( 150 ) ; idx NUMBER := 1 ; BEGIN

WHILE ( idx<=line_length ) LOOPactual_line := actual_line || separator ; idx := idx +1 ;

END LOOP ; DBMS_OUTPUT.PUT_LINE ( actual_line ) ;

END ;The index of the WHILE LOOP must be declared and initializedThere is no need for an explicit EXIT condition for the loop

Lecture 44

Unless we want the loop to run "forever," we can put an EXIT or EXIT WHENstatement within the body of the loopThe syntax for these statements is:

EXIT ;EXIT WHEN condition ;where condition is a Boolean expression

Lecture 44

Forces a loop to complete unconditionallyWhen encountered, the loop completes immediately and control passes to the next statementMust be placed inside a loopIf used to exit a cursor FOR loop prematurely, the cursor is closed automatically

Page 216: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 44

Lets a loop complete conditionallyThe EXIT statement is encountered, the condition in the WHEN clause is evaluatedIf the condition is true, the loop completes and control passes to the next statement after the loopUntil the condition is true, the loop cannot completeA statement inside the loop must change the value of the condition

Lecture 44

EXIT [ label_name ] [ WHEN boolean_expression ] ;

where label_name identifies the loop to be exitedboolean_expression is an expression that yields the Boolean value and evaluated with each iteration of the loop in which the EXIT WHEN statement appears

Lecture 44

FOR i IN 1..10 LOOPFETCH c1 INTO emp_rec ; EXIT WHEN c1%NOTFOUND ; ttotal_comm := total_comm + emp_rec.comm ; END LOOP ;

The loop normally executes ten times, but it will exit prematurely if there are less than ten rows to fetchThe EXIT WHEN statement replaces a simple IF statementIF count > 100 THEN

EXIT ; END IF ;

Equivalent toEXIT

WHEN count > 100 ;

Page 217: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 45

Lecture 45

In this lecture we will learn the various data structures provided by PL/SQL, that are used for managing large sets of data.

Lecture 45

Introduction Advantages of ArraysTypes of ArraysAssociative ArraysDensely Populated arraysVarraysHow to choose a type of PL/SQL array?

Page 218: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 45

In PL/SQL, arrays are called as "Collections".Collection is a data structure that acts like a list or a single dimensional-array.A collection is an ordered group of elements, all of the same type.It is a general concept that encompasses lists, arrays and other datatypes.

Lecture 45

Keeps track of listsEmulates bidirectional or random access cursorsImproves performance of lookupsCache database information

Lecture 45

PL/SQL offers following three types of arrays:Associative Arrays:

- also known as Index-By Tables. It is a dynamic array. They are unbounded and sparse in nature.

Densely Populated Arrays:- also known as Nested Tables. It is alsoa dynamic array. They are unbounded but densely arranged.

Varrays:- they are variable size arrays. These are bounded and are never arranged sparsely.

Page 219: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 45

Associative arrays are single-dimensional structures.These are unbounded, sparse collection of homogeneous elements.They cannot be used in tables.They can be used only as programming structures.They can be accessed only in PL/SQL.Associative arrays are set of key-value pairs, where each key is unique.

CONTD . . .

Lecture 45

This key is used to locate a corresponding value in the array. The key can be an integer or a string.Assigning a value using a key for the first time adds that key to the associative array.These are intended for temporary data rather than storing persistent data, so we cannot use them with SQL statements such as INSERT and SELECT INTO.

CONTD . . .

Lecture 45

We define a table type using the TYPE statement. Here is the syntax:

TYPE table_type_name IS TABLE OF type [NOT NULL] INDEX BY BINARY_INTEGER ;

Example:TYPE num_tab IS TABLE OF NUMBER INDEX BY BINARY_INTEGER ;

Once we have defined a array type, we need to declare the actual associative array of that type. Here is the syntax:

<table_var_name> <table_type_name> ; CONTD . . .

Page 220: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 45

Example: v_example_tab num_tab;

We can access individual elements as follows:

<table_var_name>(<index_value>) The parentheses in the preceding code are necessary.When we access the elements of an associative array, we use the array variable name and not the array type name.

CONTD . . .

Lecture 45

It is an unbounded and unordered single-dimensional array of data elements, all of the same data type.It is similar to an associative array except that the INDEX BY BINARY_INTEGER clause is missing in its definition.They are initially dense but can become sparse through deletions.Nested tables are multiset, which means that there is no inherent order to the elements in a nested table.

Lecture 45

An array type is defined as follows:TYPE table_name IS TABLE OF data_type [NOT NULL] ;

Example:TYPE num_table IS TABLE OF NUMBER;

Once we have defined a array type, we need to declare variables of that type that represent the actual array. Here is the syntax:

<var_name> <TABLE_type_name>;CONTD . . .

Page 221: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 45

Example:v_numarray num_table;

We can access the individual elements of a nested table using valid subscription notation. Here is the syntax:

nested_table_variable(subscript_index) This is for both read and write operations on the nested table.Example:

v_numarray(1)

CONTD . . .

Lecture 45

VARRAY (variable-sized array) is a single-dimensional array of homogeneous elements. They are limited by a maximum number of elements.They are always bounded and never sparse.We can change the upper bound for VARRAYS.The maximum size of a VARRAY is 2GB.

Lecture 45

VARRAY type is defined as follows:

TYPE type_name IS { VARRAY | VARRAYING ARRAY } ( max_size) OF data_type [ NOT NULL ] ;

Example:TYPE num_varray IS VARRAY(5) OF NUMBER;

We declare variables of the type that represent the actual VARRAYS, in the following format:

<var_name> <VARRAY_type_name>;

CONTD . . .

Page 222: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 45

Example:v_numvarray num_varray;

Accessing of Varray elements can be done in the following format:

varray_variable(subscript_index) Example:

v_numvarray(1)

CONTD . . .

Lecture 45

Nested tables are appropriate for important data relationships that must be stored persistently.Associative arrays are appropriate for relatively small lookup tables.They are good for collecting information whose volume is unknown beforehand, because there is no fixed limit on their size.Varrays are a good choice:

- when the number of elements is known in advance.

- when all the elements are usually accessed in sequence.

Page 223: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 46

Cursor – An Introduction

Lecture 46

Objective

This chapter introduces the concept of cursors that are used to manage the private work areas. It also describes the Explicit and Implicit cursors with their advantages and disadvantages.

Lecture 46

Topics Covered

Cursor BasicsImplicit CursorsExplicit Cursors

Page 224: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 46

Cursor Basics

PL/SQL interacts with SQL by combining SQL statements with PL/SQL constructs inside a PL/SQL blockCursors exhibits interaction with SQL by using SQL within PL/SQLA cursor is a handle to a work area that holds the resultset of a multirow SQL query

Lecture 46

Types of Cursor

Implicit CursorOracle automatically handles many of the cursor-related operations, such as allocating a cursor, opening the cursor, fetching records and even closing the cursor

Explicit CursorThis is a SELECT statement that is declared as a cursor explicitly in the application code

Lecture 46

Implicit Cursor

Keeps track of other types of DML statementsAlso known as the SQL cursorOracle PL/SQL engine automatically opens the implicit or SQL cursor that points to the work areaAfter the execution of the DML statements, the implicit cursor is automatically closed

Contd…

Page 225: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 46

Implicit Cursor

Oracle implicitly opens a cursor to process each SQL statement not associated with an explicitly declared cursorThe OPEN, FETCH and CLOSE statements cannot be used to control the SQL cursorPL/SQL declares and manages an implicit cursor every time we execute a SQL DML statement or a SELECT INTO that returns a single row from the database directly into a PL/SQL data structure

…contd

Lecture 46

Drawbacks of Implicit Cursor

Inefficiencies of implicit cursorsAn implicit cursor executes as a SQL statement and Oracle's SQL is ANSI-standardAn implicit query always performs a minimum of two fetches

Vulnerability to data errorsIf an implicit SELECT statement returns more than one row, it raises the TOO_MANY_ROWS exception

Contd…

Lecture 46

Drawbacks of Implicit Cursor

Diminished programmatic controlWe cannot get inside the separate operations of the cursor, such as the open and close stagesWe cannot examine the attributes of the cursor

…contd

Page 226: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 46

Example of Implicit Cursor

BEGINDELETE sec_hrc_org_tab WHERE hrc_code = 1 ; INSERT INTO sec_hrc_org_tab

SELECT h.hrc_code, h.hrc_descr, o.org_id, o.org_short_name, o.org_long_name

FROM org_tab o, hrc_tab h WHERE o.hrc_code = h.hrc_code

AND h.hrc_code = 1 ; IF ( SQL%FOUND ) THENdbms_output.put_line( TO_CHAR ( SQL%ROWCOUNT ) || ' rows inserted into secondary table for

hierarchy 1' ) ; END IF ;

COMMIT ; END ;

Contd…

Lecture 46

Example of Implicit Cursor

The code refreshes a secondary table named sec_hrc_org_tab with new rowsIt first deletes all rows from the sec_hrc_org_tab table where the hrc_codematches 1It then inserts new rows into the same tableSQL%FOUND returns a boolean true when at least one row has been inserted into the temp_hrc_org_tabSQL%ROWCOUNT gives the numbers of rows inserted into the sec_hrc_org_tab table

…contd

Lecture 46

Explicit Cursor

The cursor name is explicitly associated with a SELECT statementThis is done using the PL/SQL CURSOR … IS SELECT … statementExplicit cursors can be associated with a SELECT statement onlyAn explicit cursor can be used to process multirow queries, including queries that fetch one rowDefined in the declaration section of the code

Contd…

Page 227: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 46

Explicit Cursor

It is assigned with a name in the processThere is no such thing as an explicit cursor for UPDATE, DELETE and INSERT statementsWith this we have complete control over the different PL/SQL steps involved in retrieving information from the databaseInformation about the current state of the cursor is availableBasic Syntax of declaration is

CURSOR cursor_name IS SELECT_statement ;

…contd

Lecture 46

Advantages of Explicit Cursor

Only needs to perform a single fetchWith this, the program will be protected against changes in data With this, the program will continue to fetch rows without raising exceptionsImproved programmatic control over that data accessFinely-tuned exception handling for the cursor

Lecture 46

Example of Explicit Cursor

DECLARECURSOR csr_org ISSELECT h.hrc_descr, o.org_short_nameFROM org_tab o, hrc_tab h WHERE o.hrc_code = h.hrc_code ORDER by 2 ;

v_hrc_descr VARCHAR2 ( 20 ) ; v_org_short_name VARCHAR2 ( 30 ) ;

BEGIN/* ... <Process the cursor resultset> ... */ null ;

END ;

Page 228: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 46Points to Remember about Explicit Cursor

The order of declaring cursors and other variables is immaterialThe SELECT statement associated with a cursor cannot contain an INTO clauseIt may, however, have GROUP BY and ORDER clauses, as well as joins and set operators such as UNION, INTERSECT and MINUSThe scope of a cursor is the PL/SQL block in which it is defined or any of its nested blocksEnclosing ( outer ) blocks cannot reference a cursor defined within them

Page 229: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 47

Lecture 47

Objective• In this lecture we will learn

– Working with Explicit Cursors– Working with Implicit Cursors

Lecture 47

Topics Covered• Working with Explicit Cursors

Declare the CursorOpen the CursorFetch Records from the CursorClose the CursorExplicit Cursor Attributes

• Working with Implicit CursorsImplicit Cursor Attributes

Page 230: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 47

Working with Explicit Cursors• An explicit cursor is a SELECT statement that is

explicitly defined in the declaration section of our code.

• With explicit cursors , we have complete control over the different PL/SQL steps involved in retrieving information from the database.

• To use an explicit cursor, it must be declared, opened, fetched from, and closed.

• Information about the current state of your cursor is available through examination of cursor attributes.

Lecture 47

Declaring the Explicit Cursors• To use an explicit cursor, we must first declare it in

the declaration section of our PL/SQL block or in a package, as shown here:

CURSOR cursor_name [ parameter_list ][ RETURN return_type ] IS SELECT_statement [ FOR UPDATE [ OF [ column list ] ] ;

• where cursor_name is the name of the cursor• return_type is an optional RETURN clause for the

cursor• SELECT_statement is any valid SQL SELECT

statement. CONTD . . .

Lecture 47

Declaring the Explicit Cursors• Parameter _list is optional and can be any valid

parameter used for query execution.• Finally, the optional FOR UPDATE clause locks the

records when the cursor is opened.• The SELECT statement associated with a cursor can

not contain an INTO clause.• Example:

CURSOR name_cur ( company_id_in IN NUMBER ) IS

SELECT name FROM company WHERE company_id = company_id_in ;

CONTD . . .

Page 231: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 47

Open the Explicit Cursor• Cursors are opened in the Execution or Exception

sections of the block.• The syntax is:

OPEN cursor_name [ ( parameter_values ) ] ;• where cursor_name is the name of the cursor we

declared.• Parameter_values are the values to be passed if

the cursor was declared with a parameter list.• The OPEN command prepares the cursor for use.• When executed, the query is parsed, bind values

are evaluated, rows are recorded in the context area, and the result set is made ready.

Lecture 47

Fetch Records from the Cursor• FETCH is what retrieves record from the context

area into a variable so that it can be used.• This command operates on the current record only

and proceeds through the result set, one record at a time.

• The syntax for FETCH is:FETCH cursor_name INTO record_or_variable_list ;

• where cursor_name is the name of the cursor from which the record is fetched.

• record_or_variable_list is the PL/SQL data structures into which the next row of the active set of records is copied.

Lecture 47

Close the Explicit Cursor• The context area is memory used for the cursor.• Until the cursor is closed, the memory is not

released.• To close a cursor, use the following syntax:

CLOSE cursor_name ;• Cursor_name is the name of the opened cursor.• If a CLOSE is used on a cursor that is not currently

open, the following exception is raised:ORA-01001: invalid cursor

Page 232: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 47

Explicit Cursor Attributes• Oracle offers four attributes that allow us to

retrieve information about the state of our cursor. • Reference these attributes using this syntax:

cursor% attributewhere cursor is the name of the cursor we have declared.cursor% FOUND

Returns TRUE if a record was fetched successfully.

cursor%NOTFOUNDReturns TRUE if a record was not fetched successfully. CONTD . . .

Lecture 47

Explicit Cursor Attributescursor%ROWCOUNT

Returns the number of records fetched from the specified cursor at that point in time.

cursor%ISOPENReturns TRUE if the specified cursor is open.

• If you try to use %FOUND, %NOTFOUND, or %ROWCOUNT before the cursor is opened or after it is closed, Oracle will raise an exception:

INVALID_CURSOR error (ORA-01001).

CONTD . . .

Lecture 47

Working with Implicit Cursors• PL/SQL declares and manages an implicit cursor:

- every time when we execute a DML statement (INSERT, UPDATE, or DELETE) - when we use a SELECT INTO that returns a

single row from the database directly into a PL/SQL data structure.

• This kind of cursor is called implicit because Oracle implicitly or automatically handles many of the cursor-related operations for us, such as:

– allocating a cursor– opening the cursor– fetching, and so on.

CONTD . . .

Page 233: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 47

Working with Implicit Cursors• The SELECT statement appears in the executable

section of your block.• It is not defined in the declaration section, as

explicit cursors are.• The query contains an INTO clause.• The INTO clause is a part of the PL/SQL language

and is the mechanism used to transfer data from the database into local PL/SQL data structures.

• Syntax:SELECT column_list [ BULK COLLECT ] INTO PL/SQL variable list ...rest of SELECT statement...

CONTD . . .

Lecture 47

Implicit Cursors Attributes• Oracle allows us to access information about the

most recently executed implicit cursor by referencing the special implicit cursor attributes.

• Because the cursors are implicit, they have no name, and therefore, the keyword "SQL" is used to denote the implicit cursor.

• All the implicit cursor attributes return NULL if no implicit cursors have yet been executed in the session.

• SQL%FOUNDReturns TRUE if one row was fetched successfully, otherwise FALSE. CONTD . . .

Lecture 47

Implicit Cursors Attributes• SQL%NOTFOUND

Returns TRUE if a row was not fetched successfully otherwise FALSE.

• SQL%ROWCOUNTReturns the number of rows fetched from the specified cursor. For a SELECT INTO, this will be 1if a row was found and 0 if Oracle raises the NO_DATA_FOUND exception.

• SQL%ISOPENAlways returns FALSE for implicit cursors because Oracle opens and closes implicit cursors atomically.

CONTD . . .

Page 234: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 48

Lecture 48

• Every explicit cursor and cursor variable has attributes. This section describes each of the different cursor attributes at a high level. We will also study the implementation of these attributes.

Lecture 48

• Introduction to Cursor Attributes• Explicit Cursor Attributes

– %FOUND– %ISOPEN– %NOTFOUND– %ROWCOUNT

• Implicit Cursor Attributes– %FOUND– %ISOPEN– %NOTFOUND– %ROWCOUNT

Page 235: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 48

• When appended to the cursor or cursor variable, the cursor attributes return useful information about the execution of a data manipulation statement

• Cursor attributes can be used in procedural statements but not in SQL statements

• PL/SQL offers a total of six cursor attributes• To reference a cursor attribute, we attach it to

the name of the cursor or cursor variable about which we want an information

Lecture 48

Returns exception information for rows modified by the FORALL statement for each collection element

%BULK_EXCEPTIONS

Returns the number of records modified by the FORALL statement for each collection element

%BULK_ROWCOUNT

Returns TRUE if cursor is open, FALSE otherwise%ISOPEN

Returns number of records fetched from cursor at that point in time

%ROWCOUNT

Returns TRUE if record was not fetched successfully, FALSE otherwise

%NOTFOUND

Returns TRUE if record was fetched successfully, FALSE otherwise

%FOUND

DescriptionAttribute

Lecture 48

• Used to determine whether a cursor is open or not

• Used to determine whether a fetch yielded a row or not

• Used to determine how many rows have been fetched so far

• To use these attributes, the cursor name is prefixed with the corresponding attribute

• Returns information about the execution of a multi-row query

Page 236: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 48

• Used to determine whether a FETCH returned a row or not

• Used after a cursor is opened• Returns a value of TRUE if the immediate

FETCH yielded a row, and a value of FALSE if the immediate FETCH did not fetch any row

• After a cursor or cursor variable is opened but before the first fetch, %FOUND yields NULL

• If a cursor or cursor variable is not open, referencing it with %FOUND raises the predefined INVALID_CURSOR exception

Lecture 48

• Logical opposite of %FOUND• Used to determine if a FETCH resulted in no

rows• Returns a value of TRUE if the immediate

FETCH yielded no row and a value of FALSE if the immediate FETCH resulted in one row

• Using %NOTFOUND before opening a cursor or after a cursor is closed raises the invalid cursor error or the predefined INVALID_CURSOR exception

• Before the first fetch, %NOTFOUND evaluates to NULL

Lecture 48

• Used to determine the number of rows fetched from a cursor

• Returns 1 after the first fetch and is incremented by 1 after every successful fetch

• Can be referenced after a cursor is opened or before the first fetch and returns zero in both cases

• When its cursor or cursor variable is opened, %ROWCOUNT is zeroed

• If a cursor or cursor variable is not open, referencing it with %ROWCOUNT raises INVALID_CURSOR

Page 237: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 48

• Used to check if a cursor is already open or not• Used to prevent an already opened cursor from

opening or an already closed cursor from closing• Returns a value of TRUE if the referenced

cursor is open otherwise returns FALSE• %ISOPEN can be referenced after a cursor is

closed

Lecture 48

Indicates whether the cursor is OPEN or not. This is FALSE always, as the implicit cursor is closed after the DML statement is executed.

SQL%ISOPEN

Indicates the number of rows affected by the DML statement

SQL%ROWCOUNT

Indicates if a DML statement failed to modify any rows.

SQL%NOTFOUND

Indicates whether an INSERT, UPDATE, or DELETE affected any row ( s ) or not.

SQL%FOUND

UseAttribute

Lecture 48

• Used to determine whether an INSERT, UPDATE or DELETE affected any row or not, or a SELECT … INTO returned a row or not

• Used immediately after the DML statement• Returns TRUE if the INSERT, UPDATE or

DELETE affected one or more rows or the SELECT … INTO fetched a row

• Until a SQL data manipulation statement is executed, %FOUND yields NULL

Page 238: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 48

• Used to determine if an INSERT, UPDATE, or DELETE failed to modify any rows

• Returns a value of TRUE if no rows were modified by the INSERT, UPDATE or DELETE and a value of FALSE if at least one row was modified

• Using SQL%NOTFOUND before executing any DML statement yields a NULL value

• If the cursor has not yet been opened, a reference to the %NOTFOUND attribute raises the INVALID_CURSOR exception

Lecture 48

• Used to determine the number of rows affected by a DML statement

• Returns a value greater than zero if the DML statement succeeded otherwise returns zero

• A good alternative to SQL%NOTFOUND• If a SELECT INTO statement returns more

than one row, PL/SQL raises the predefined exception TOO_MANY_ROWS and %ROWCOUNT yields 1, not the actual number of rows that satisfy the query

Lecture 48

• SQL%ISOPEN is always FALSE because the implicit cursor is closed after the DML statement is executed

Page 239: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 48

• The values of the cursor attributes always refer to the most recently executed SQL statement, wherever that statement is

• To save an attribute value for later use, assign it to a Boolean variable immediately

• If a SELECT INTO statement fails to return a row, PL/SQL raises the predefined exception NO_DATA_FOUND whether %NOTFOUND is checked on the next line or not

Lecture 48

• DECLAREv_num_rows NUMBER ; BEGIN

DELETE sec_hrc_org_tab WHERE hrc_code = 1 ; INSERT INTO sec_hrc_org_tabSELECT h.hrc_code, h.hrc_descr, o.org_id,

o.org_short_name, o.org_long_nameFROM org_tab o, hrc_tab h WHERE o.hrc_code = h.hrc_code AND h.hrc_code = 1 ; v_num_rows := SQL%ROWCOUNT ; IF ( SQL%FOUND ) THENUPDATE sec_hrc_audit SET num_rows = v_num_rowsWHERE hrc_code = 1 ; IF ( SQL%NOTFOUND ) THENINSERT INTO sec_hrc_audit ( hrc_code, num_rows )

VALUES ( 1, v_num_rows ) ; END IF ; END IF ; COMMIT ;

END ;Contd…

Lecture 48

• The code first deletes all rows from the sec_hrc_org_tab table where the hrc_codematches 1

• Then inserts new rows into the same table• SQL%FOUND returns a boolean true when at

least one row has been inserted into the sec_hrc_org_tab

• SQL%NOTFOUND returns TRUE and a record is inserted into the sec_hrc_audit table

…contd

Page 240: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 49

Lecture 49

In this lecture we will learn - cursor FOR loop- Parameterized Cursors

Lecture 49

Cursor FOR Loop- Syntax of Cursor FOR Loop- Example of Cursor FOR Loop- Points to be remembered

Parameterized Cursors- Advantages of Parameterized Cursors- Default values for Parameters

Page 241: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 49

In most situations which require an explicit cursor, we can simplify coding by using a cursor FOR loop instead of the OPEN, FETCH, and CLOSE statements.A cursor FOR loop implicitly declares its loop index as a record that represents a row fetched from the database.An important use of the cursor FOR LOOP is when we process all the rows in a cursor unconditionally.

Lecture 49

Here is the basic syntax of a cursor FOR loop:

FOR record_index IN { cursor_name | (explicit SELECT statement) } LOOP executable statements END LOOP ;

where record_index is a record declared implicitly by PL/SQL with the %ROWTYPE attribute.

Lecture 49

DECLARE CURSOR occupancy_cur IS SELECT pet_id, room_number FROM occupancy WHERE occupied_dt = TRUNC ( SYSDATE ) ; BEGIN FOR occupancy_rec IN occupancy_cur LOOP update_bill (occupancy_rec.pet_id,

occupancy_rec.room_number) ; END LOOP ;

END ;

Page 242: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 49

We should use a cursor FOR loop when there are no EXIT or EXIT WHEN inside the loop that cause early termination.The cursor FOR loop terminates unconditionally when all of the records in the associated cursor have been fetched. We can pass parameters to the cursor in a cursor FOR loop. Using a cursor FOR LOOP does not make the cursor an implicit cursor. It is still an explicit cursor and has to be declared explicitly.

Lecture 49

Parameters provide a way to pass information into and out of a module. Used properly, parameters improve the usefulness and flexibility of modules.PL/SQL allows us to pass parameters into cursors. We can specify as many cursor parameters as we need.

Lecture 49

Makes the cursor more reusable:- We can use a parameter, instead of

hard coding a value into the WHERE clause of a query to select particular information.

- Then pass different values to the WHERE clause each time a cursor is opened.

CONTD . . .

Page 243: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 49

Avoids scoping problems:- When we pass parameters instead of

hard coding values, the result set for that cursor is not tied to a specific variable in a program or block.

- If our program has nested blocks, we can define the cursor at a higher-level block and use it in any of the subblocks with variables defined in those local blocks.

CONTD . . .

Lecture 49

Cursor parameters can be assigned default values.Here is an example of a parameterized cursor with a default value:CURSOR emp_cur ( emp_id_in NUMBER := 0 ) IS

SELECT employee_id, emp_name FROM employee WHERE employee_id = emp_id_in ;

Because the emp_id_in parameter has a default value, we can also open and fetch from the cursor without specifying a value for the parameter.

Page 244: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 50

Lecture 50

After completing this session we will be able to understand– what is exception handling– advantages of PL/SQL exceptions– how to define exceptions

Lecture 50

Exception-Handling Concepts and TerminologyAdvantages of PL/SQL ExceptionsDefining Exceptions

Page 245: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 50

An error generated by the system– out of memory – duplicate value in index

An error caused by a user actionA warning issued by the application to the user

Lecture 50

In the PL/SQL language, errors of any kind are treated as exceptionsAn exception is an error raised at runtime either by Oracle or by the programmerOnce raised, an exception has to be properly handledPL/SQL traps and responds to errors using an architecture of exception handlers

Lecture 50

All PL/SQL exceptions are characterized by,Error Type– indicates whether the error is an ORA error or a

PLS errorError Code– a number indicating the error number

Error Text– the text of the error message, including the error

code

Page 246: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 50

System exception– defined by Oracle – usually raised by the PL/SQL runtime engine when

it detects an error conditionProgrammer-defined exception– defined by the programmer – specific to the application at hand

Lecture 50

Errors can be handled conveniently without the need to code multiple checksReadability is improved by allowing to isolate error-handling routinesThe primary algorithm is not obscured by error recovery algorithms

Lecture 50

EXCEPTION declaration– used while declaring a user- defined exception

RAISE statement– used to raise an exception

PRAGMA EXCEPTION_INIT directive– used to associate an Oracle error with a user-

defined exceptionSAVE EXCEPTIONS clause– used to continue processing after a row-wise

failure during bulk binding

Page 247: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 50

Before an exception can be raised or handled, it must be definedOracle predefines exceptions by assigning numbers and messages to those exceptionsNames are assigned in the STANDARD package as well as in other built-in packages

Lecture 50

The exceptions that PL/SQL has declared in the STANDARD package cover internal or system-generated errorsAn exception is declared by listing the name of the exception we want to raise in the program followed by the keyword EXCEPTION:– exception_name EXCEPTION ;

Lecture 50

Exceptions without names are perfectly legitimateExceptions can be raised using RAISE_APPLICATION_ERROR that consist of nothing more than an error number and an error messageSQLCODE is a built-in function that returns the number of the last error raised

Page 248: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 50

A compile-time command or pragmaUsed to associate a name with an internal error codeInstructs the compiler to associate an identifier declared as an EXCEPTION with a specific error numberThis pragma must appear in the declaration section of a block

Lecture 50

To give names to otherwise anonymous system exceptions that are commonly referenced in the codeTo assign names to the application-specific errors raised using – RAISE_APPLICATION_ERROR

Lecture 50

Named system exceptions– Globally available and can be raised and handled

in any blockNamed programmer defined exceptions– Can be raised and handled only in the execution

and exception sections of the block in which they are declared

Contd…

Page 249: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 50

Anonymous system exceptions– Can be handled in any PL/SQL exception section

via the WHEN OTHERS sectionAnonymous programmer-defined exceptions– Defined only in the call to

RAISE_APPLICATION_ERROR and then are passed back to the calling program

…contd

Page 250: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 51

Lecture 51

In this lecture we will learn How exceptions are raisedException PropagationHow to handle raised ExceptionUse of Built-in function

Lecture 51

Raising ExceptionsUsing RAISE_APPLICATION_ERRORException PropagationHandling Raised Exceptions

- Exceptions Raised in Declaration section - Exceptions Raised in Execution section - Exceptions Raised in Exception section

Use of Built-in Functions

Page 251: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 51

When the error associated with an exception occurs, the exception is raised.User defined exceptions are raised explicitly via the RAISE statement.Predefined exceptions are raised implicitly when their associated Oracle error occurs.Predefined exceptions can be raised explicitly via RAISE statement as well, if desired. When an exception is raised, control immediately passes to the section of the block.

Lecture 51

Oracle offers the RAISE statement so that we at or discretion, raise a named exception. We can raise a exception of our own or a system exception. The RAISE statement can take any one of the following forms:RAISE exception_name ;RAISE package_name . exception_name ;RAISE ; CONTD . . .

Lecture 51

The first form without a package name qualifier can be used to raise an exception we have defined in the current block.The second form is used if an exception has been declared inside a package other than STANDARD and is raised outside that package.The third form of RAISE statement does not require an exception name, but can only be used within a WHEN clause of the exception section.

CONTD . . .

Page 252: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 51

This built-in procedure is used to create our own error messages, which can be more descriptive than named exceptions. This procedure is defined in the default DBMS_STATNDARD package.When this procedure is raised, execution of the current PL/SQL block halts immediately.Any changes made to OUT and IN OUT arguments will be reversed. CONTD . . .

Lecture 51CONTD . . .

The syntax of RAISE_APPLICATION_ERROR:RAISE_APPLICATION_ERROR ( error_number,

error_message, [ keep_errors ] ) ;error_number is a value between -20,000 and -20,999.error_message is the text associated with this error.keep_errors is a Boolean value.

Lecture 51

When an exception is raised, and if PL/SQL cannot fine a handler for it in the current block or sub program, then the exception propagates.the exception reproduces itself in successive enclosing blocks until a handler is found.When all the blocks are exhausted, PL/SQL returns an unhandled exception.This unhandled exception halts the execution of host program.

Page 253: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 51

The figure below shows propagation of an exception through nested blocks:

Lecture 51

When an exception is raised, normal execution of our PL/SQL block or subprogram stops.The control transfers to its exception-handling part. Exceptions can occur in:

- declarative section - executable section- exception section

Lecture 51

Exceptions are raised in declarative section by faulty initialization of expressions.For example, the following declaration raises an exception because the constant credit_limit cannot store number larger than 999.DECLARE

credit_limit CONSTANT NUMBER(3) := 5000 ; - -raisedBEGIN ...

EXCEPTION WHEN OTHERS THEN - -cannot catch...END ;

Page 254: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 51

In this case, if the current block has a handler for exception, then execute it and complete the block successfully. The control is then passed to the enclosing block. But if there is no handler for current exception, propagate the exception by raising it in enclosing block.If there is no enclosing block then exception will be propagated out to the calling environment.

Lecture 51

Exceptions can be raised while in an exception handler, either explicitly via RAISE statement, or implicitly via a run-time error. Only one exception at a time can be active in the exception-handling part of a block or subprogram. An exception raised inside a handler propagates immediately to the enclosing block.

Lecture 51

SQLCODE:It returns error code of most recently raised exception in our block.If there is no error, SQLCODE returns 0. It also returns 0 when we call it outside of an exception handler. For user-defined exceptions SQLCODE

returns 1. Oracle maintains a stack of SQLCODE values.

Contd…

Page 255: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 51

SQLERRM:It is a function that returns a error message for a particular error code. If SQLCODE is 0, SQLERRM returns the string: ORA-0000: normal, successful completion. If SQLCODE is 1, SQLERRM returns the string: user-defined exception. The maximum length string that SQLERRM will return is 512 bytes.

…contd

Page 256: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 52

Lecture 52

After completing this session we will be able to understand– predefined exceptions– user defined exceptions– handling predefined exceptions– handling user defined exceptions

Lecture 52

Predefined ExceptionsUser-defined ExceptionsHandling Predefined ExceptionsHandling User defined Exceptions

Page 257: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 52

An internal exception is raised implicitly whenever the PL/SQL program violates an Oracle rule or exceeds a system-dependent limitEvery Oracle error has a number, but exceptions must be handled by namePL/SQL predefines some common Oracle errors as exceptionsPL/SQL raises the predefined exception NO_DATA_FOUND if a SELECT INTO statement returns no rowsPL/SQL declares predefined exceptions globally in package STANDARD

Lecture 52

No need to declare and raise a predefined PL/SQL exceptionImplicitly raised by PL/SQLCan be raised if needed explicitly using the RAISE statementHandled using exception handlers

Lecture 52

-1476ORA-01476ZERO_DIVIDE

-6502ORA-06502VALUE_ERROR

-1ORA-00001DUP_VAL_ON_INDEX

-1001ORA-01001INVALID_CURSOR

-6592ORA-06592CASE_NOT_FOUND

-6530ORA-06530ACCESS_INTO_NULL

SQLCODE ValueOracle ErrorException

Page 258: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 52

attempts to divide a number by zeroZERO_DIVIDE

the conversion of a character string into a number failsVALUE_ERROR

attempts to store duplicate values in a database column that is constrained by a unique index

DUP_VAL_ON_INDEX

attempts an illegal cursor operation such as closing an unopened cursor

INVALID_CURSOR

None of the choices in the WHEN clauses of a CASE statement is selected and there is no ELSE clause

CASE_NOT_FOUND

attempts to assign values to the attributes of an uninitialized object

ACCESS_INTO_NULL

Raised whenException

Lecture 52

DECLAREv_descr VARCHAR2 ( 20 ) ; BEGIN

SELECT hrc_descr INTO v_descrFROM hrc_tabWHERE hrc_code = 10 ; dbms_output.put_line ( ' The hierarchy description

for code 10 is: ' || v_descr ) ; EXCEPTION WHEN NO_DATA_FOUND THEN

dbms_output.put_line ( 'ERR: Invalid Hierarchy Code 10' ) ;

END ;Contd…

Lecture 52

The SELECT … INTO does not return any row for hrc_code 10The NO_DATA_FOUND predefined exception is raised implicitlyControl transfers to the exception handler specified by EXCEPTION WHENNO_DATA_FOUND THENThe code in this exception handler is executedThe code following the SELECT statement is not executed at all

…contd

Page 259: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 52

PL/SQL allows to define exceptions of our ownMust be declared and must be raised explicitly by RAISE statementsDeclared only in the declarative part of a PL/SQL block, subprogram or packageDeclared by introducing its name, followed by the keyword EXCEPTIONCannot appear in assignment statements or SQL statementsNot the part of the exceptions defined by PL/SQL in the STANDARD package

Lecture 52

Defined in a PL/SQL program that are specific to the application programNot the part of the exceptions defined by PL/SQL in the STANDARD packageNot the ORACLE errors occurring in program executionIdentified by name

Lecture 52

Declared explicitly in the declaration section of a PL/SQL block just like other PL/SQL declarationsThe data type of the exceptions are specified with the keyword EXCEPTIONNot associated with any error number or error message textDefined for trapping and handling application-specific errors

Page 260: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 52

exception_name EXCEPTION ;

Example:DECLARE

sites_undefined_for_org EXCEPTION ; BEGIN

... ... END ;

Lecture 52

Once declared, has to be raised explicitly using the RAISE statementSyntax:

RAISE exception_name ;

Example:DECLARE

sites_undefined_for_org EXCEPTION ; BEGIN

... ... IF ( condition ) THEN RAISE

sites_undefined_for_org ; END IF ; EXCEPTION WHEN sites_undefined_for_org THEN

... ... END ;

Lecture 52

DECLAREsites_undefined_for_org EXCEPTION ; -- a user-defined exception v_cnt NUMBER ; BEGIN

SELECT COUNT ( * ) INTO v_cntFROM org_site_tabWHERE org_id = 1007 ; IF ( v_cnt = 0 ) THEN

-- explicitly raising the user-defined exception RAISE sites_undefined_for_org ;

END IF ; EXCEPTION

-- handling the raised user-defined exception WHEN sites_undefined_for_org THEN

dbms_output.put_line ( 'There are no sites defined for organization 1007' ) ;

WHEN OTHERS THENdbms_output.put_line ( 'ERR: An error occurred

with info :' || TO_CHAR ( SQLCODE ) || ' ' || SQLERRM ) ; END ;

Page 261: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 53

Lecture 53

In this lecture we will learn about the concept of Subprograms in PL/SQL as well as its advantages and types.

Lecture 53

What are Subprograms?Example of SubprogramAdvantages of SubprogramsFeatures of SubprogramsTypes of Subprograms

Page 262: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 53

PL/SQL block has a disadvantage that we cannot store it in the database like a table. If we need to share a block within another application, then we must rewrite it for that specific application.PL/SQL provides us with a mechanism that permits us to share code between applications called as "stored subprogram".

Contd . . .

Lecture 53

It has the major advantage of being stored in the database and is therefore shareable.Subprograms are named PL/SQL blocks that can take parameters and be invoked. Like anonymous PL/SQL blocks, Subprograms have a declarative part, an executable part and an optional exception-handling part.

Contd . . .

Lecture 53

PROCEDURE debit_account ( acct_id INTEGER, amount REAL ) IS old_balance REAL ;

new_balance REAL ;overdrawn EXCEPTION ;BEGINSELECT bal INTO old_balance FROM accts

WHERE acct_no = acct_id ;new_balance := old_balance – amount ;IF new_balance < 0 THEN

RAISE overdrawn ;ELSE

UPDATE accts SET bal = new_balance WHERE acct_no = acct_id ;

END IF ;EXCEPTION WHEN overdrawn THEN. . . .END debit_account ; Contd . . .

Page 263: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 53

The given is an example of a subprogram named debit_account, which debits a bank account.When invoked or called, this procedure accepts an account number and a debit amount. It uses the account number to select the account balance from the accts database table. Then, it uses the debit amount to compute a new balance. If the new balance is less than zero, an exception is raised; otherwise, the bank account is updated.

Contd . . .

Lecture 53

Modularity: This supports top-down design and the stepwise refinement approach to problem solving.Encapsulation: Stored subprograms enables the encapsulation of business logic, such as business rules and application logic, into the database.

Contd . . .

Lecture 53

Centralization of Code: The code is available in a single location and multiple applications can use it.Reusability: Multiple programs can reuse the same subprogram, with different sets of data.Better Performance: A subprogram allows us to group together sets of SQL statements, which results in better performance with fewer database calls.

Contd . . .

Page 264: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 53

Subprograms are uniquely named.Subprograms are stored in the database.They are available as metadata in the data dictionary.Parameters can be passed to it and values can be returned from it.It can be executed at the top level or called from other Pl/SQL programs by using its name.

Lecture 53

Pl/SQL 9i supports three types of stored subprograms. They are given below:

ProceduresFunctionsPackages

PROCEDURES:It is a certain piece of code consisting of declarative and procedural SQL statements in the catalog of the database.

Contd . . .

Lecture 53

FUNCTIONS: They shows a strong resemblance to stored procedures.They must contain a RETURN statement.This special SQL statement is not allowed in stored procedures.PACKAGES: A package is a grouping or packaging together of PL/SQL code elements.

Contd . . .

Page 265: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 54

Lecture 54

In this lesson we will learn how to create Procedures, calling them and removing of procedures.

Lecture 54

Introduction Creating a ProcedureThe Procedure BodyExample of ProcedureCalling a ProcedureThe RETURN StatementRemoving Stored Procedures

Page 266: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 54

Stored Procedures are known as "procedural database object".A stored procedure is a certain piece of code ( the procedure ) consisting of declarative and procedural SQL statements.They are stored in the catalog of a database and can be activated by calling them from a program, a trigger or another stored procedure.Procedures are key building blocks of modular code, allowing us to both consolidate and reuse our program logic.

CONTD . . .

Lecture 54

For calling stored procedures, a new SQL statement has been introduced. When calling stored procedures, we can also specify input and output parameters. The stored procedure offers the possibility of storing certain parts of a program centrally in the catalog of the database server.They can then be called from all programs. For this reason, a database server that supports stored procedures is sometimes also called a "Programmable Database Server".

CONTD . . .

Lecture 54

We can create a procedure with the CREATE or REPLACE PROCEDURE statement.Syntax:CREATE [ OR REPLACE ]

PROCEDURE < procedure_name > [ parameter_list ][ AUTHID { DEFINER CURRENT_USER } ] { IS | AS }

[ PRAGMA AUTONOMOUS_TRANSACTION ; ][ local declaration section ]

BEGINexecutable section

[ EXCEPTIONexception handlers ]

END [ name ] ;CONTD . . .

Page 267: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 54

Where < procedure_name > is the name of the procedure to be created.Parameter is the name of the procedure parameter.The executable statements is the PL/SQL block that consists of source code.The name of the procedure mentioned with the END statement is optional. The procedure parameters consists of three attributes:

NameModeDatatype

CONTD . . .

Lecture 54

The body of a procedure is a PL/SQL block with declarative, executable and exception sections. Declarative section is located between the IS or AS keyword and the BEGIN keyword. Executable section ( the only one that is required ) is located between the BEGIN and EXCEPTION keywords, Exception handling section, if present, is located between the EXCEPTION and END keywords. There is no DECLARE keyword in a procedure declaration.

Lecture 54

PROCEDURE raise_salary (emp_id INTEGER, amount REAL) IScurrent_salary REAL ; salary_missing EXCEPTION ; BEGINSELECT sal INTO current_salary FROM empWHERE empno = emp_id ;IF current_salary IS NULL THEN RAISE salary_missing ;ELSE UPDATE emp SET sal = sal + amount

WHERE empno = emp_id ; END IF ;EXCEPTION WHEN NO_DATA_FOUND THENINSERT INTO emp_audit VALUES ( emp_id, ‘Invalid’ ) ;WHEN salary_missing THENINSERT INTO emp_audit VALUES (emp_id, 'Salary is null') ;END raise_salary;

Page 268: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 54

Calling a stored procedure is comparable to calling a "normal" procedure in procedural languages. For calling stored procedures, a new SQL statement CALL has been introduced.When calling stored procedures, we can also specify input and output parameters.The syntax for this is:

CALL [ < database name > . ] < StoredProcedureName >( expression list ) ;

CONTD . . .

Lecture 54

A procedure is called as an executable statement, So it must end with a semicolon. In font of the procedure name, the name of the database may be specified. SQL automatically places that same database name in all the DML statements in front of all table names This does not apply when a database name is explicitly specified in front of a table name. Any scalar expression may be used as the input parameter of a stored procedure.

CONTD . . .

Lecture 54

The RETURN statement is generally associated with a function because it is required to RETURN a value from a function.PL/SQL also allows us to use a RETURN statement in a procedure. The procedure version of the RETURN does not take an expression; it therefore cannot pass a value back to the calling program unit.The RETURN simply halts execution of the procedure and returns control to the calling code.Use of the RETURN in a procedure usually leads to very unstructured code.

Page 269: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 54

Just as for tables, views, and indexes, it is possible to remove stored procedures from the catalog. For this, SQL supports the DROP PROCEDUREstatement. This removes the procedure from the data dictionary. The syntax for dropping a procedure is:

DROP PROCEDURE procedure_name ;

Page 270: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 55

Lecture 55

In this lecture we will learn creation of stored functions, calling of functions and RETURN statement of functions.

Lecture 55

IntroductionCreating a FunctionExamples of FunctionCalling a FunctionThe RETURN StatementFunction BodyRemoving Stored Functions

Page 271: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 55

Stored functions show a strong resemblance to stored procedures.Stored functions are also pieces of code consisting of SQL and procedural statements. They are stored in the catalog and can be called from applications and SQL statements.They are stored in the catalog and can be called from applications and SQL statements

Contd . . .

Lecture 55

However, there are a few differences. A stored function can have input parameters but does not have output parameters.The stored function itself is the output parameter. A function is a module that returns a value.Unlike a procedure call, which is a standalone executable statement, a call to a function can exist only as part of an executable statement.

Contd . . .

Lecture 55

Syntax:CREATE [ OR REPLACE ] FUNCTION function_name

[ ( parameter_name1 parameter_mode datatype,... ...parameter_nameN parameter_mode datatype ) ]RETURN datatype[ AUTHID { DEFINER | CURRENT_USER } ] { IS | AS }[ PRAGMA AUTONOMOUS_TRANSACTION ; ][ local declaration section ]BEGIN

executable section[ EXCEPTION

exception handling section ]END [ function_name ] ;

Contd . . .

Page 272: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 55

Where function_name is the name of the function being created.parameter1 through parameter N are the names of the function parameters.parameter_mode is one of [ { IN | OUT [ NOCOPY ] | IN OUT [NOCOPY ] } ].datatype is the data type of the associated parameter. As in the case of procedures, the local declaration section is specified without the DECLARE keyword.

Contd . . .

Lecture 55

AUTHID clause specifies the execution privileges of the function.PRAGMA refers to autonomous transactions.It is mandatory that we specify the RETURN clause while defining a function.RETURN clause specifies the data type of the return value of the function.

Contd . . .

Lecture 55

CREATE FUNCTION DOLLARS ( AMOUNT DECIMAL ( 7 , 2 ) )

RETURNS DECIMAL (7 , 2 )BEGIN

RETURN AMOUNT * ( 1 / 0.8 ) ;END

CREATE FUNCTION NUMBER_OF_PLAYERS()RETURNS INTEGERBEGINRETURN (SELECT COUNT(*) FROM PLAYERS) ;END

Page 273: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 55

Unlike a procedure, a function is called as a part of an expression that evaluates to a value whose data type matches the return type of the function.Also, functions can be called from DML statements such as SELECT, INSERT, and so forth. The RETURN statement inside the body of the function, it returns a value to the calling environment

Lecture 55

The RETURN statement can return a value in three ways:

a hard-coded valuea single variable holding a valuean expression that evaluates to a value.

We can specify more than one RETURN statement in the body of the function. As soon as the RETURN statement is encountered, the function execution stops and the control returns to the calling environment.

Contd . . .

Lecture 55Contd . . .

The RETURN statement has two general forms:

- RETURN ;

- RETURN expression ;We can use the first form of the RETURNstatement in procedures. The second form of the RETURN statement is and must be used in functions. It not only transfers control to the calling program, but it also returns a value.

Page 274: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 55

The body of the function is the code required to implement the function.Everything after the IS keyword in the function makes up that function's body. A function's execution section should have a RETURN statement in it, although it is not necessary for the function to compile.If, however, our function finishes executing without processing a RETURN statement, Oracle will raise error.

Lecture 55

Using DROP statement, we can remove the desired function.Here is the syntax for removing a function:

DROP FUNCTION [ <database name> . ] <function name>

Page 275: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 56

Lecture 56

Objective

In this lesson we will learn different modes of parameters and concept of overloading in stored procedures and functions.

Lecture 56

Topics Covered

IntroductionDefining ParametersActual and Formal ParametersParameter ModesMatching actual and formal parameters in PL/SQL

The NOCOPY parameterRestrictions on NOCOPYOverloadingBenefits of Overloading

Page 276: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 56

Introduction

Procedures and functions can both use parameters to pass information back and forth between the module and the calling PL/SQL block. Parameters to stored subprograms are of two types:

Actual parameters Formal parameters

PL/SQL offers many different features to help us design parameters effectively.

Lecture 56

Defining Parameters

Formal parameters are defined in the parameter list of the program. A parameter definition parallels closely to the syntax for declaring variables in the declaration section of a PL/SQL block.A parameter has a passing mode while a variable declaration does not.A parameter declaration must be unconstrained. Contd . . .

Lecture 56

Defining Parameters

A "constrained declaration" is one that constrains or limits the kind of value that can be assigned to a variable declared with that datatype. An "unconstrained declaration" is one that does not limit values in this way.When we declare a parameter, however, we must leave out the constraining part of the declaration:PROCEDURE display_company

( company_name IN VARCHAR2 ) IS ...

Contd . . .

Page 277: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 56

Actual and Formal Parameters

The formal parameters are the names that are declared in the parameter list of the header of a module. The actual parameters are the values or expressions placed in the parameter list of the actual call to the module. The formal parameters do not exist outside of the function. We can think of them as placeholders for real or actual parameter values that are passed into the function when it is used in a program.

Lecture 56

Parameter Modes

We can define formal parameters with three modes:

INOUTIN OUT

The mode determines how the program can use and manipulate the value assigned to the formal parameter. We specify the mode of the parameter immediately after the parameter name.

Lecture 56

IN Mode

An IN parameter allows us to pass values into the module but will not pass anything out of the module and back to the calling PL/SQL block.In other words, IN parameters function like constants. Just like constants, the value of the formal IN parameter cannot be changed within the program. IN is the default mode.IN parameters can be given default values in the program header.

Page 278: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 56

OUT Mode

We use the OUT parameter to pass a value back from the program to the calling PL/SQL block.An OUT parameter is like the return value for a function, but it appears in the parameter list.Inside the program, an OUT parameter acts like a variable that has not been initialized. We cannot provide a default value to an OUT parameter. We can only assign a value to an OUT parameter inside the body of the module.

Lecture 56

IN OUT Mode

With an IN OUT parameter, we can pass values into the program and return a value back to the calling program. An IN OUT parameter cannot have a default value An IN OUT actual parameter or argument must be a variable. It cannot be a constant, literal, or expression.We can use the IN OUT parameter in both sides of an assignment because it functions like an initialized, rather than uninitialized, variable.

Lecture 56Matching Actual and Formal Parameters in PL/SQL

PL/SQL offers two ways to make the association between actual and formal parameters: Positional Notation: Associate the actual parameter implicitly ( by position ) with the formal parameter.Named Notation: Associate the actual parameter explicitly ( by name ) with the formal parameter.

Page 279: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 56

The NOCOPY Parameter

PL/SQL offers an option for definitions of parameters: the NOCOPY clause. NOCOPY is a hint to the compiler about how we would like the PL/SQL engine to work with the data structure being passed in as an OUT or IN OUT parameter. There are two ways to pass parameter values:

By Reference By Value

Contd . . .

Lecture 56

The NOCOPY Parameter

When an actual parameter is passed by reference, it means that a pointer to the actual parameter is passed to the corresponding formal parameter. When an actual parameter is passed by value, the value of the actual parameter is copied to the corresponding formal parameter.NOCOPY is a hint, not a command. Whenever the subprogram containing the OUT parameter is called, corresponding actual parameter for an OUT parameter under the NOCOPY hint is set to NULL .

Contd . . .

Lecture 56

Restrictions on NOCOPY

We cannot use NOCOPY in following situations:When the actual parameter is an element on an associate array.When certain constraints are applied to actual parameters.When the actual and formal parameters are record structures.In passing the actual parameter, the PL/SQL engine must perform an implicit datatype conversion.The subprogram requesting the NOCOPY hint is used in an external or remote procedure call.

Page 280: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 56

Overloading

When more than one program in the same scope share the same name, the programs are said to be overloaded. PL/SQL supports the overloading of procedures and functions in the declaration section of a block.Overloading is a very powerful feature, and we should exploit it fully to improve the usability of your software. This technique consolidates the call interfaces for many similar programs into a single module name, transferring the burden of knowledge from the developer to the software.

Lecture 56

Benefits of Overloading

Supporting many data combinations:This is the most common motivation for overloading.Fitting the program to the user:To make your code as useful as possible, we may construct different versions of the same program that correspond to different patterns of use.Overloading by type, not value:This really comes in use only when we are writing very generic software.

Page 281: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 57

Packages

Lecture 57

Objective

A package is a grouping or packaging together of PL/SQL code elements. Packages provide a structure in which we can organize the programs and other PL/SQL elements such as cursors, TYPEsand variables. In this chapter we will study the packages in PL/SQL.

Lecture 57

Topics Covered

Why Packages?Package-Related ConceptsDiagramming PrivacyRules for Building PackagesRules for Calling Packaged ElementsWorking with Package DataWhen to Use Packages

Page 282: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 57

Why Packages?

Easier enhancement and maintenance of applicationsImproved overall application performanceAbility to shore up application or built-in weaknessesMinimize the need to recompile code

Lecture 57

Some Package-Related Concepts

Information hidingPublic and privatePackage specificationPackage bodySession persistence

Lecture 57

Diagramming Privacy

Contd…

Page 283: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 57

Diagramming Privacy

External programs cannot cross the boundary from outside to insideThose elements defined in the package specification straddle the boundary between inside and outsidePublic elements of the package offer the only path to the inside of the packageThe package specification acts as a control mechanism for the package as a whole

…contd

Lecture 57

Rules for Building Packages

Declare elements of almost any datatype at the package levelCannot declare cursor variables in a package specification or bodyDeclare almost any type of data structureDeclare procedures and functions in a package specificationInclude explicit cursors in the package specification

Contd…

Lecture 57

Rules for Building Packages

Include an AUTHID clause in a package specificationInclude an optional package name label after the END statement of the packageA package body can have declaration, execution and exception sectionsWe may not include an AUTHID clause in the package bodyA package may be reinitialized in a session

…contd

Page 284: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 57

Rules for Calling Packaged Elements

When elements defined in a package specification are referenced from outside of that package, dot notation must be used in the form package_name.element_nameWhen package elements are referenced from within the package, no need to include the name of the packagePL/SQL automatically resolves the reference within the scope of the package

Lecture 57

Working with Package Data

Declaring packaged cursorsWorking with packaged cursorsSerializable Packages

Lecture 57

Declaring packaged cursors

CREATE OR REPLACE PACKAGE book_infoIS CURSOR byauthor_cur ( author_in IN books.author%TYPE ) IS SELECT * FROM books WHERE author = author_in ; CURSOR bytitle_cur ( title_filter_in IN books.title%TYPE ) RETURN books%ROWTYPE ; TYPE author_summary_rtIS RECORD ( author books.author%TYPE,

total_page_count PLS_INTEGER, total_book_count PLS_INTEGER ) ;

CURSOR summary_cur ( author_in IN books.author%TYPE ) RETURN author_summary_rt ; END book_info ;

Page 285: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 57

Working with packaged cursors

DECLARE onebook book_info.bytitle_cur%ROWTYPE ; BEGIN

OPEN book_info.bytitle_cur ( '%PL/SQL%' ) ; LOOP EXIT WHEN

book_info.bytitle_cur%NOTFOUND ; FETCH book_info.bytitle_cur INTO

onebook ;

book_info.display ( onebook ) ; END LOOP ; CLOSE book_info.bytitle_cur ;

END ;

Lecture 57

Serializable Packages

To manage the use of memory in packages PL/SQL offers the SERIALLY_REUSABLE pragmaMust appear in both the package specification and the bodyMarks the package as serially reusableThe global memory for serialized packages is allocated in the System Global Area and not in the User Global AreaThe maximum number of work areas needed for a serialized package is the number of concurrent users of that package

Lecture 57

When to Use Packages

Encapsulating data manipulationAvoiding the hardcoding of literalsImproving the usability of built-in featuresGrouping together logically related functionalityCaching session-static data to improve application performance

Page 286: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 58

Triggers - An Introduction

Lecture 58

Objective

A database server is passive by nature. It performs an action only if we explicitly ask for it with, for example, an SQL statement. In this chapter, we describe the database concept that turns a passive database server into an active one. This concept is called a trigger.

Lecture 58

Topics Covered

What are triggers?Uses of TriggersTypes of TriggersTriggers and MetadataEnabling and Disabling TriggersPrivileges required to create TriggersMethods on compiling TriggersRestrictions on Using Triggers

Page 287: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 58

What are Triggers?

A piece of code consisting of procedural and declarative statements stored in the catalogActivated by the database server if a specific operation is executed on the databaseA stored subprogram that is stored in the database and executed implicitly on the occurrence of an eventNamed program units that are executed in response to events that occur in the database

Lecture 58

Some facts of Triggers

UPDATE, SELECT, CREATE, IF-THEN-ELSE and WHILE-DO statements can occur within a triggerCannot be called explicitly either from a program or from a stored proceduresThe way in which triggers are called deviates from that of stored proceduresCALL or EXECUTE TRIGGER statement or similar statement are not availableTriggers are called by SQL itself

Contd…

Lecture 58

Some facts of TriggersExecuted automatically by SQLIt is impossible to activate triggers from a programIt is impossible to switch off triggers from a programEnable to perform various functions that would otherwise be tedious to codeA triggering event is initiated on the execution of a triggering statement such as an INSERT, UPDATE or DELETE statement or a CREATE, ALTER or DROP statement

…contd

Page 288: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 58

Uses of Triggers

DDL and DML auditingSystem event handlingPerforming related actions when a particular action occursEnforcing complex data-integrity relationships that cannot be specified declarativelyAutomatically generating derived valuesEnforcing complex validation rules to prevent inappropriate and inconsistent data from being input into the database

Lecture 58

Types of Triggers

DML Triggers:– fire when an INSERT, UPDATE or DELETE

statement is executed on a database tableINSTEAD-OF Triggers– fire on DML statements issued against either a

relational view or an object viewTriggers on System and User Events– fire on the occurrence of system events such as

database startup and shutdownBEFORE and AFTER triggers

Lecture 58

Triggers and Metadata

Database triggers are stored in the database in compiled form as p-codeUSER_TRIGGERS view stores information about triggers in the current user schemaALL_TRIGGERS view stores information about objects in all schemas so far definedUSER_OBJECTS and ALL_OBJECTS store the trigger name, its status and other information

Page 289: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 58

Enabling & Disabling TriggersBy default a trigger is enabled provided any condition specified in the trigger is metA disabled trigger does not fire on the execution of the triggering statement even if the trigger condition evaluates to TRUEALTER TRIGGER statement is used to enable or disable triggersIt is possible to enable or disable all triggers on a particular tableA trigger on a particular table can be dropped

Lecture 58

Privileges to Create Triggers

creating system triggers at the database level

ADMINISTER DATABASE TRIGGER

drop a trigger in any schemaDROP ANY TRIGGER

alter a trigger in any schema for enabling, disabling or compiling triggers

ALTER ANY TRIGGER

create a trigger in any schemaCREATE ANY TRIGGER

create a trigger in the current schemaCREATE TRIGGER

ActionPrivilage

Lecture 58

Methods on Compiling Triggers

A trigger is compiled when it is first createdCompiling a trigger involves resolving syntax and semantic references and p-code generationWays to recompile triggers:

Automatically: We do this when a trigger that is invalidated due to dependencies is invoked the next timeDeclaratively: We do this using the ALTER TRIGGER statement

Page 290: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 58

Restrictions on Using TriggersCannot exceed 32KB in sizeCannot use DDL statementsCannot use DML statements such as COMMIT, ROLLBACK and SAVEPOINTCannot declare variables of LONG and LONG RAWLOB columns can be read only inside the body of a triggerThe trigger body cannot read from or modify a mutating table of the triggering statement

Page 291: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 59

DML Triggers

Lecture 59

Objective

In this session we will study– The concept of DML Triggers– How a DML Trigger is created / defined– Types of DML Triggers– REFERENCING clause– WHEN Clause– How multiple triggering events work in a single

DML Trigger– Number and Type of DML Triggers that can be

defined on a Single Table

Lecture 59

Topics CoveredConcept of DML TriggersTransaction participationDefining DML TriggersCreating a DML TriggerROW and STATEMENT TriggersREFERENCING clauseWHEN clauseMultiple Triggering Events in a Single DML TriggerNumber and Type of DML Triggers that can be defined on a Single Table

Page 292: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 59

DML Triggers

Fire when records are inserted into, updated within or deleted from a particular tableCan fire after or before a DML statementCan fire after or before each row is processed within a statementCan fire for INSERT, UPDATE or DELETE statements or combinations of the three

Lecture 59

Firing DML Triggers

Lecture 59

DML Trigger Concepts

BEFORE trigger– executes before a certain operation occurs

AFTER trigger– executes after a certain operation occurs

Statement-level trigger– executes for a SQL statement as a whole

Contd…

Page 293: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 59

DML Trigger Concepts

Row-level trigger– executes for a single row that has been affected

by the execution of a SQL statementNEW pseudo-record– contains the values for the affected row after

any changes were madeOLD pseudo-record– contains the values for the affected row before

any changes were made

…contd

Lecture 59

Transaction participation

If a trigger raises an exception, that part of the transaction will be rolled backIf the trigger performs any DML itself then that DML becomes a part of the main transaction.We cannot issue a COMMIT or ROLLBACK from within a DML trigger

Lecture 59

Defining DML Triggers

DML triggers are defined on a particular database tableDML triggers are defined with the CREATE OR REPLACE TRIGGER statementWe can specify multiple DML operations for the triggering event by separating them with the OR keyword

Page 294: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 59

Creating a DML TriggerCREATE [ OR REPLACE ] TRIGGER trigger name

{ BEFORE | AFTER } { INSERT | DELETE | UPDATE | UPDATE OF

column list } ON table name [ FOR EACH ROW ] [ WHEN ( ... ) ] [ DECLARE ... ] BEGIN

... executable statements ... [ EXCEPTION ... ]

END [ trigger name ] ;

where trigger_name is the name of the DML trigger being created

Lecture 59

ROW and STATEMENT Triggers

Does not lock rowsAFTER ROW triggers lock the data rows

Currently affected by the triggering event

Currently affected by the triggering event

Trigger body doesn't have access to the row data

Trigger body has access to the row data

Both BEFORE and AFTER can be specified

Both BEFORE and AFTER can be specified

Fired even if the triggering event does not affect any rows

Not fired if the triggering event affects no rows

Fired once for the triggering statement

Fired for each row affected by the triggering statement

STATEMENT TriggersROW Triggers

Lecture 59

REFERENCING ClauseSpecifies how the data being currently modified by the triggering event should be referenced inside the trigger bodyBy default, currently modified data available in ROW trigger is referenced by two correlation identifiers– :NEW– :OLD

The correlation identifiers act as bind variables and hold the data of the current row as a record of type table_name%ROWTYPE

Contd…

Page 295: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 59

REFERENCING Clause

Allows to reference the columns in row currently being modified by using custom names instead of :NEW and :OLDWe should reference NEW and OLD with a colon (:) inside the trigger bodyWe can use NEW and OLD in both BEFORE and AFTER ROW triggersThe REFERENCING clause can be used only for ROW- level triggers

…contd

Lecture 59

WHEN Clause

Specifies any WHERE condition to be specified for the execution of the trigger bodyFollows the FOR EACH ROW clauseColon ( : ) is not used when referencing OLD and NEW in the WHEN clauseOnly valid for ROW-level triggersThe triggering statement is not rolled back if the condition in the WHEN clause evaluates to FALSE

Lecture 59

Multiple Triggering Events in a Single DML Trigger

Multiple DML operations can be specified for the triggering event by separating them with the OR keywordPL/SQL provides trigger predicates– INSERTING– UPDATING– DELETING

With the use of trigger predicates, a single trigger can achieve the same functionality for specified different operations

Page 296: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

6

Lecture 59

ExampleCREATE OR REPLACE TRIGGER ai_org_trig

AFTER INSERT OR DELETE ON org_tabFOR EACH ROW BEGIN

IF INSERTING THEN UPDATE sec_hrc_auditSET num_rows = num_rows + 1 WHERE hrc_code = :NEW.hrc_code ; IF ( SQL%NOTFOUND ) THEN

INSERT INTO sec_hrc_auditVALUES ( :NEW.hrc_code, 1 ) ;

END IF ; ELSIF DELETING THEN

UPDATE sec_hrc_auditSET num_rows = num_rows - 1 WHERE hrc_code = :OLD.hrc_code ;

END IF ; END ;

Lecture 59

DML Triggers defined on a Single Table ( ROW level )

After deleting each row affected by a DELETE, firing once per row

AFTER DELETE

Before deleting each row affected by a DELETE, firing once per row

BEFORE DELETE

After writing each change affected by an UPDATE, firing once per row

AFTER UPDATE

Before modifying each row affected by an UPDATE, firing once per row

BEFORE UPDATE

After writing each row affected by an INSERT, firing once per row

AFTER INSERT

Before writing each row affected by an INSERT, firing once per row

BEFORE INSERTDescriptionTrigger Type

Lecture 59

DML Triggers defined on a Single Table ( STATEMENT level )

After deleting all rows as a result of a DELETEAFTER DELETE

Before deleting rows as a result of an INSERTBEFORE DELETE

After modifying all rows as a result of an UPDATE

AFTER UPDATE

Before modifying rows as a result of an UPDATE

BEFORE UPDATE

After inserting all rows as a result of an INSERTAFTER INSERT

Before writing new rows to the database as a result of an INSERT

BEFORE INSERTDescriptionTrigger Type

Page 297: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

1

Lecture 60

Database Event Triggers

Lecture 60

Objective

In this session we will study– Types of Database Event Triggers– How to create Database Event Trigger– System Event and User Event Triggers– Trigger Attributes

Lecture 60

Topics CoveredTypes of Database Event Triggers– The STARTUP Trigger– The SHUTDOWN Trigger– The LOGON Trigger– The LOGOFF Trigger– The SERVERERROR Trigger

Creating Database Event TriggerSystem Event and User Event TriggersTrigger Attributes

Page 298: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

2

Lecture 60

New Database TriggersDatabase event triggers fire whenever database-wide events occurIndependent of tables and independent of DMLCan be created during system events such as– Database startup and shutdown– Logon and logoff from the database– Server-side error occurrence

Can be created during user events such as– Session logon and logout– User events such as DDL execution

Lecture 60

Types of Database Event TriggersSTARTUP– Fires when the database is opened

SHUTDOWN– Fires when the database is shut down normally

SERVERERROR– Fires when an Oracle error is raised

LOGON– Fires when an Oracle session begins

LOGOFF– Fires when an Oracle session terminates normally

Lecture 60

STARTUP & SHUTDOWN Trigger

STARTUP trigger execute during database startup processingIn order to create startup event triggers, users must have been granted the ADMINISTER DATABASE TRIGGER privilegeBEFORE SHUTDOWN triggers execute before database shutdown processing is performedSHUTDOWN triggers execute only when the database is shut down using NORMAL or IMMEDIATE mode

Page 299: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

3

Lecture 60

LOGON & LOGOFF TriggerAFTER LOGON triggers fire when an Oracle session is begunAFTER LOGON triggers are the perfect place to establish session context and perform other session setup tasksBEFORE LOGOFF triggers execute when sessions disconnect normally from the databaseBEFORE LOGOFF trigger is a good place to gather statistics regarding session activity

Lecture 60

SERVERERROR Trigger

Fire after an Oracle error is raisedWill not fire when an exception is raised inside this triggerDo not provide facilities to fix the errorProvide facilities only to log information about the error

Lecture 60

Creating a Database Event Trigger

CREATE [ OR REPLACE ] TRIGGER trigger name { BEFORE | AFTER } { database event } ON { DATABASE | SCHEMA } DECLARE

Variable declarations BEGIN

... some code...

END ;

Page 300: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

4

Lecture 60

System Event Triggers

Before logging out of a client application, just before start of logoff. Can be at the database or schema level.

BEFORELOGOFF

After a client application logs onto a database successfully. Can be at the database or schema level.

AFTERLOGON

Once an exception occurs. Can be at the database or schema level.

AFTERSERVERERROR

During database shutdown. Can only be created at the database level.

BEFORESHUTDOWN

During database startup. Can only be created at the database level.

AFTERSTARTUP

DESCRIPTIONTIMINGEVENT NAME

Lecture 60User Event Triggers

Before or after a database object is dropped. It can be created at the schema level or for an entire database.

BEFORE & AFTER

DROP

Before or after a database object is altered. It can be created at the schema or database level.

BEFORE & AFTER

ALTER

Whenever a new database object is created. It can be created at the schema level or for an entire database.

BEFORE & AFTER

CREATE

In response to a server error. Can be at the database or schema level.

AFTERSERVERERROR

Before logging out of a session, just before the start of user logoff. Can be at the database or schema level.

BEFORELOGOFF

After logging into a session. Can be at the database or schema level.

AFTERLOGON

DESCRIPTIONTIMINGEVENT NAME

Lecture 60

Trigger Attributes

Like the :NEW and :OLD attributes available on DML BEFORE and AFTER ROW triggers, there are attributes associated with the system and user eventsWe can use these attributes in the SYSTEM or USER EVENT INITIATED triggersUsed by prefixing them with SYS.Available as functions

Page 301: An Introduction To RDBMS - saintangelos.comsaintangelos.com/studentdesk/Download/YCMOU_Books... · An Introduction To RDBMS Lecture 01 Objective z This lecture gives an idea of database

5

Lecture 60Attributes for Database-Level Events

Login user name.VARCHAR2(30)

Sys.login_user

Returns TRUE if given error is on error stack; otherwise, it returns FALSE.

BOOLEANSys.is_servererror

Returns the error number at a given position on error stack:@@@1 – Top of the stack.

NUMBERSys.server_error

Database name.VARCHAR2(50)

Sys.database_name

Instance number.NUMBERSys.instance_num

System event firing the trigger. The event name refers to one of the system events.

VARCHAR2(20)

Sys.sysevent

DESCRIPTIONTYPEATTRIBUTE

Lecture 60Attributes for User-Level Events

The DES encrypted password of the user being created or altered

VARCHAR(2)Sys.des_encrypted_Password

Owner of the dictionary object on which the DDL operation occurred

VARCHAR(30)Sys.dictionary_obj_Owner

Name of the dictionary object on which the DDL operation occurred

VARCHAR(30)Sys.dictionary_obj_Name

Type of the dictionary object on which the DDL operation occurred

VARCHAR(20)Sys.dictionary_obj_Type

DESCRIPTIONTYPEATTRIBUTE