100% found this document useful (1 vote)
1K views

CS409 Final Term Handouts - MCQS Part 2

Uploaded by

pakiataniking
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

CS409 Final Term Handouts - MCQS Part 2

Uploaded by

pakiataniking
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

What is an Oracle Triggers?

 A trigger is a named PL/SQL block stored in the Oracle Database and executed
automatically when a triggering event takes place. The event can be any of the following:
 A data manipulation language (DML) statement executed against a table e.g., INSERT,
UPDATE, or DELETE.
 For example, if you define a trigger that fires before an INSERT statement on the
customers table, the trigger will fire once before a new row is inserted into the customers
table.
 A data definition language (DDL) statement executes e.g., CREATE or ALTER
statement. These triggers are often used for auditing purposes to record changes of the
schema.
 A system event such as startup or shutdown of the Oracle Database.
 A user event such as login or logout.
 The act of executing a trigger is also known as firing a trigger. We say that the trigger is
fired.

Oracle Trigger Usage

Oracle triggers are useful in many cases such as the following:

 Enforcing complex business rules that cannot be established using integrity constraint
such as UNIQUE, NOT NULL, and CHECK.
 Preventing invalid transactions.
 Gathering statistical information on table accesses.
 Generating value automatically for derived columns.
 Auditing sensitive data.
Trigger’s Disable/ Enable

Sometimes, you may want to disable a trigger for testing and troubleshooting purposes. To
disable a trigger, you use the ALTER TRIGGER DISABLE statement:

ALTER TRIGGER trigger_name DISABLE;

ALTER TABLE table_name DISABLE ALL TRIGGERS;


What is a Cursor?

 A cursor is a pointer that points to a result of a query.


 It is mainly used with tables which return more than one row.
 It is handled implicitly and explicitly.

Implicit Cursor

 Whenever Oracle executes an SQL statement such as SELECT INTO, INSERT,


UPDATE, and DELETE, it automatically creates an implicit cursor.
 Oracle internally manages the whole execution cycle of implicit cursors and reveals only
the cursor’s information and statuses such as SQL%ROWCOUNT, SQL%ISOPEN,
SQL%FOUND, and SQL%NOTFOUND.

Implicit Cursor

 The implicit cursor is not elegant when the query returns zero or multiple rows which
cause NO_DATA_FOUND or TOO_MANY_ROWS exception respectively.

Explicit Cursor

 An explicit cursor is an SELECT statement declared explicitly in the declaration section


of the current block or a package specification.
 For an explicit cursor, you have control over its execution cycle from OPEN, FETCH,
and CLOSE.
 Oracle defines an execution cycle that executes an SQL statement and associates a cursor
with it.

Execution Cycle of Explicit Cursor

Cursor’s usage
 Declare a cursor

CURSOR cursor_name IS query;

 Open a cursor

OPEN cursor_name;

Cursor’s usage

 Fetch from a cursor

The FETCH statement places the

contents of the current row into var.

FETCH cursor_name INTO variable_list;

To retrieve all rows in a result set, you

need to fetch each row till the last one.

 Closing a cursor

CLOSE cursor_name;

Explicit Cursor Attributes

 %ISOPEN
 %FOUND
 %NOTFOUND
 %ROWCOUNT

Implicit Cursor – Record Type

 A record is a composite data structure, which means that it is composed of one or more
elements.
 Records are very much like a row of a database table, but each element of the record does
not stand on its own. PL/SQL supports three kinds of records: table-based, cursor-based,
and programmer-defined.
What is an Array?
All VARRAYS consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.

Declaration of an Array

A varray type is created with the CREATE TYPE statement. You must specify the maximum size and
the type of elements stored in the varray.

CREATE Or REPLACE TYPE namearray AS VARRAY(3) OF VARCHAR2(10);


Concepts of Oracle Instance-1

Introduction

A database instance is a set of memory structures that manage database files. A database is a set of
physical files on disk created by the CREATE DATABASE statement. The instance manages its
associated data and serves the users of the database.

Every running Oracle database is associated with at least one Oracle database instance. Because an
instance exists in memory and a database exists on disk, an instance can exist without a database and a
database can exist without an instance.

Configuration Option

During installation, oracle has an option to install instance, database or both

Database Instance Structure


When an instance is started, Oracle Database allocates a memory area called the system global area
(SGA) and starts one or more background processes. The SGA serves various purposes, including the
following:

■Maintaining internal data structures that are accessed by many processes and threads concurrently

■Caching data blocks read from disk

■Buffering redo data before writing it to the online redo log files

■Storing SQL execution plans

The SGA is shared by the Oracle processes, which include server processes and background processes,
running on a single computer. The way in which Oracle processes are associated with the SGA varies
according to operating system.
A database instance includes background processes. Server processes, and the process memory allocated in these
processes, also exist in the instance. The instance continues to function when server processes terminate.

Database Instance Configurations

You can run Oracle Database in either of the following mutually exclusive configurations:

■Single-instance configuration
A one-to-one relationship exists between the database and an instance.

■Oracle Real Application Clusters (Oracle RAC) configuration

A one-to-many relationship exists between the database and instances.

Duration of an Instance
An instance begins when it is created with the STARTUP command and ends when it is terminated. During this
period, an instance can associate itself with one and only one database. Furthermore, the instance can mount a
database only once, close it only once, and open it only once. After a database has been closed or shut down, you
must start a different instance to mount and open this database.

Instance Startup

 Login with user sys / as sysdba


 After shutdown database, run the following:
Connection with Administrator Privileges

Database start-up and shutdown are powerful administrative options that are restricted to users who
connect to Oracle Database with administrator privileges. Normal users do not have control over the
current status of an Oracle database.

Depending on the operating system, one of the following conditions establishes administrator privileges
for a user:

■The operating system privileges of the user enable him or her to connect using administrator privileges.

■The user is granted the SYSDBA or SYSOPER system privileges and the database uses password files
to authenticate database administrators over the network.

When you connect with the SYSDBA system privilege, you are in the schema owned by SYS. When you
connect as SYSOPER, you are in the public schema.

Database with Shutdown Instance

In a typical use case, you manually shut down the database, making it unavailable for users while you perform
maintenance or other administrative tasks. You can use the SQL*Plus SHUTDOWN command or Enterprise
Manager to perform these steps.

Progress from OPEN to Shutdown

Steps to perform Database Shutdown

Database closed

The database is mounted, but online data files and redo log files are closed.

Database unmounted
The instance is started, but is no longer associated with the control file of the database.

Database instance shut down

The database instance is no longer started.

Oracle Database does not go through all of the preceding steps in an instance failure or SHUTDOWN
ABORT, which immediately terminates the instance.

SHUTDOWN ABORT

This mode is intended for emergency situations, such as when no other form of shutdown is successful.
This mode of shutdown is the fastest. However, a subsequent open of this database may take substantially
longer because instance recovery must be performed to make the data files consistent.

SHUTDOWN IMMEDIATE

This mode is typically the fastest next to SHUTDOWN ABORT. Oracle Database terminates any
executing SQL statements and disconnects users. Active transactions are terminated and uncommitted
changes are rolled back.

SHUTDOWN TRANSACTIONAL

This mode prevents users from starting new transactions, but waits for all current transactions to complete
before shutting down. This mode can take a significant amount of time depending on the nature of the
current transactions.

SHUTDOWN NORMAL

This is the default mode of shutdown. The database waits for all connected users to disconnect before
shutting down.

Shutdown Modes Summary

A database administrator with SYSDBA or SYSOPER privileges can shut down the database using the
SQL*Plus SHUTDOWN command or Enterprise Manager.
What is a Checkpoint?

A checkpoint is a crucial mechanism in consistent database shutdowns, instance recovery, and Oracle
Database operation generally. The term checkpoint has the following related meanings:

■A data structure that indicates the checkpoint position, which is the SCN in the redo stream where
instance recovery must begin

The checkpoint position is determined by the oldest dirty buffer in the database buffer cache. The
checkpoint position acts as a pointer to the redo stream and is stored in the control file and in each data
file header.

■The writing of modified database buffers in the database buffer cache to disk.

Whenever checkpoint happens all the dirty buffers of DB buffer cache (volatile storage) moves into data
files (Non volatile storage).

Purpose of Checkpoints

Oracle Database uses checkpoints to achieve the following goals:


■Reduce the time required for recovery in case of an instance or media failure

■Ensure that dirty buffers in the buffer cache are written to disk regularly

■Ensure that all committed data is written to disk during a consistent shutdown

Recovery without Checkpoints

Extra time is wasted in processing the entire log file

Redoing of unnecessary transactions


When to initiate Checkpoint

The checkpoint process (CKPT) is responsible for writing checkpoints to the data file headers and control
file. Checkpoints occur in a variety of situations

Checkpoint Process

The checkpoint process (CKPT)updates the control file and data file headers with checkpoint information
and signals DBWn to write blocks to disk. Checkpoint information includes the checkpoint position,
SCN, location in online redo log to begin recovery, and so on.

Thread checkpoints

The database writes to disk all buffers modified by redo in a specific thread before a certain target. The
set of thread checkpoints on all instances in a database is a database checkpoint. Thread checkpoints
occur in the following situations:

 Consistent database shutdown


 ALTER SYSTEM CHECKPOINT statement
 Online redo log switch
 ALTER DATABASE BEGIN BACKUP statement

Tablespace and data file checkpoints

The database writes to disk all buffers modified by redo before a specific target. A tablespace checkpoint
is a set of data file checkpoints, one for each data file in the tablespace. These checkpoints occur in a
variety of situations, including making a tablespace read-only or taking it offline normal, shrinking a data
file, or executing ALTER TABLESPACE BEGIN BACKUP.

Incremental checkpoints

An incremental checkpoint is a type of thread checkpoint partly intended to avoid writing large numbers
of blocks at online redo log switches. DBWn checks at least every three seconds to determine whether it
has work to do. When DBWn writes dirty buffers, it advances the checkpoint position, causing CKPT to
write the checkpoint position to the control file, but not to the data file headers.
Overview of Instance Recovery

Instance recovery is the process of applying records in the online redo log to data files to reconstruct
changes made after the most recent checkpoint. Instance recovery occurs automatically when an
administrator attempts to open a database that was previously shut down inconsistently.
Restore & Recovery Overview

To recover a SQL Server database from a failure, a database administrator has to restore a set of SQL
Server backups in a logically correct and meaningful restore sequence.:

 The database (a complete database restore)


 The data file (a file restore)
 The data page (Bulk load, restore individual DB)

Overview of Restore Scenarios


A restore scenario in SQL Server is the process of restoring data from one or more backups and then
recovering the database. The supported restore scenarios depend on the recovery model of the database
and the edition of SQL Server.

 Complete DB Restore
 File Restore (individual files)

Steps to Restore a Database

To perform a database restore, the Database Engine executes three steps:

 Creates the database and transaction log files if they do not already exist.
 Copies all the data, log, and index pages from the backup media of a database to the database
files.
 Applies the transaction log in what is known as the recovery process.

Accelerated Database Recovery

 Accelerated Database Recovery (ADR) improves database availability, especially in the presence
of long running transactions, by redesigning the SQL database engine recovery process. ADR is
new in SQL Server 2019.
 ADR is available for Azure SQL Database, Azure SQL Managed Instance and Azure Synapse
SQL.

Steps to Restore a Database

To perform a file restore, the Database Engine executes two steps:

 Creates any missing database file(s).


 Copies the data from the backup devices to the database file(s).

If you restore a file, you cannot recover it and bring it online until it has been rolled far enough forward to
be consistent with the database.
Instance Recovery

Introduction

The first phase of instance recovery is called cache recovery or rolling forward, and involves reapplying
all of the changes recorded in the online redo log to the data files.

Because rollback data is recorded in the online redo log, rolling forward also

regenerates the corresponding undo segments.

Rolling Forward

Rolling forward proceeds through as many online redo log files as necessary to bring

the database forward in time.

After rolling forward, the data blocks contain all committed changes recorded in the online redo log files.
These files could also contain uncommitted changes that were either saved to the data files before the
failure, or were recorded in the online redo log and introduced during cache recovery.
After Roll Forward

After the roll forward, any changes that were not committed must be undone. Oracle Database uses the
checkpoint position, which guarantees that every committed change with an SCN lower than the
checkpoint SCN is saved on disk. Oracle Database applies undo blocks to roll back uncommitted changes
in data blocks that were written before

the failure or introduced during cache recovery. This phase is called rolling back or transaction recovery.
Overview of Diagnostic Files

Oracle Database includes a fault diagnosability infrastructure for preventing, detecting, diagnosing, and
resolving database problems. Problems include critical errors such as code bugs, metadata corruption, and
customer data corruption.

Goals of fault Diagnosability Infrastructure

 Detecting problems proactively


 Limiting damage and interruptions after a problem is detected
 Reducing problem diagnostic and resolution time
 Simplifying customer interaction with Oracle Support

Automatic Diagnostic Repository

Automatic Diagnostic Repository (ADR) is a file-based repository that stores database diagnostic data
such as trace files, the alert log, and Health Monitor reports. Key characteristics of ADR include:

 Unified directory structure


 Consistent diagnostic data formats
 Unified tool set
Overview of Alert File

Each database has an alert log, which is an XML and text file containing a chronological log of database
messages and errors. The alert log contents include the following:

 Deadlock occurs
 Any error written by Oracle Server process
 Any unexpected messages and corruptions happened
 Any DBA DDL operations are managed
Overview of Trace Files

A trace file is an administrative file that contain diagnostic data used to investigate problems. Also, trace files can
provide guidance for tuning applications or an instance.
Reading Material:

Types of Security

Following are the database security types and issues

 Legal & Ethical Issues


 Policy Issues in Enterprises
 Systems’ related Issues
 Needs of Enterprises

Threats to Databases

Following are the database related threats and issues

 Loss of integrity
 Loss of availability
 Loss of Confidentiality

Security Domain
The database administrator defines the names of the users who are allowed to access a database. A
security domain defines the settings that apply to the user.

Authentication mechanisms are

 Data Dictionary
 Operating System
 Network

Schema Objects & User

 A Schema is a collection of objects


 A user is associated (owner) of schema
 Creating schema means creating a user as an owner of schema

User & Database

 Accessing Database (connection with the database)


 Specifying database unique user account of ID
 Specifying authentication (roles & privileges) to user account

Allocating space, quota, buffer etc. are additional features in security.

Creating Oracle User

 A unique user name or account


 Authentications (roles/ rights)
 A default tablespace
 A temporary tablespace
 A user profile
 An account status (lock/unlock)

Pre-defined Accounts

 SYS account (sys as sysdba)


o is granted the DBA role
o has all privileges with ADMIN OPTION
o is used for startup, shutdown etc.
o owns the data dictionary
 SYSTEM account is granted the DBA role
o Normally not used for routine operations
Types of Oracle User Privileges

 System: Enables users to perform particular actions in the database


 Object: Enables users to access and manipulate a specific object

System Privileges
 More than 100 distinct system privileges
 ANY keyword in privileges signifies that users have the privilege in any schema
 GRANT command adds a privilege to a user or a group of users
 REVOKE command deletes the privileges

What is User Privileges?


A user privilege is the right to run a particular type of SQL statement, or the right to access an object
that belongs to another user, run a PL/SQL package, and so on.

 System Privileges
 Object Privileges
 Roles

Managing Roles

Introduction

 Roles are named groups of related privileges or rights.


 Each user can be granted roles and privileges for each role, giving them a tailored set of abilities.
 Roles define what actions the user can take, and privileges specify the targets to which their
roles apply.
 You can view the permissions granted by each role, add and remove users, and assign roles and
notification profiles to users.

Data Dictionary for Privileges

We can use string search PRIV to display possible data dictionary views.

For Example,

select table_name

from dict

where table_name like '%PRIV%';


Benefits of Roles

 Easier privilege management


 Dynamic privilege management
 Selective availability of privileges
 Can be granted through the operating system

Easier privilege management


Use roles to simplify privilege management. Rather than granting the same set of privileges to several
users, you can grant the privileges to a role, and then grant that role to each user.

Dynamic privilege management

If the privileges associated with a role are modified, all the users who are granted the role acquire the
modified privileges automatically and immediately.

Selective availability of privileges

Roles can be enabled or disabled to turn privileges on or off temporarily. Enabling a role can also be
used to verify that a user has been granted that role.

Granting through the operating system

Operating system commands or utilities can be used to assign roles to users in the database.

Standard and Default Roles

 CONNECT is a role that Enterprise Manager automatically grants to a user when you create a
user as shown in "Creating Users". This role has the CREATE SESSION privilege.
 RESOURCE extends the privileges of a user beyond those granted by the CONNECT role. It
includes CREATE PROCEDURE, CREATE TRIGGER, and other system privileges.
 DBA is the standard role that can be granted by an administrator to another administrator. It
includes all system privileges and should only be granted to the most trusted and qualified of
users. Assigning this role to a user enables the user to administer the database.

Roles of User SYS

 When you create an Oracle database, the user SYS is automatically created and granted the DBA
role.
 All base tables and views for the database data dictionary are stored in the schema SYS. These
base tables and views are critical for the operation of Oracle Database.
 To maintain the integrity of the data dictionary, tables in the SYS schema are manipulated only
by the database. They should never be modified by any user or database administrator.
 Also, you should not create any tables in the schema of user SYS, although you can change the
storage parameters of the data dictionary settings if necessary.

Analyzing Roles & Privileges to Users

 Assuming there are three departments in some Enterprise


o Sales
o Accounting
o Human Development & Resource (HR)
 Employees are working as an external users in these departments
 Analyzing how Roles and Privileges are need to be decided
 Users Ali(Sales), Jamil(HR) and Nadeem (Accounting)
Characteristics of Roles

 Roles can be granted to and revoked from users with the same commands that are used to grant
and revoke system privileges.
 Roles can be granted to any user or role. However, a role cannot be granted to itself and cannot
be granted circularly.
 A role can consist of both system and object privileges.
 A role can be enabled or disabled for each user who is granted the role.
 A role can be required a password to be enabled.
 Each role name must be unique among existing usernames and role names.
 Roles are not owned by anyone; and they are not in any schema.
 Roles have their description stored in the data dictionary.
Reading Material:

SQL-Create Role

 Use the CREATE ROLE statement to create roles. You must have the CREATE ROLE system
privilege to create roles. When you create a role that is not identified externally or by password,
the role is granted with the ADMIN option.
 You need to decide set of privileges to put in one role and a user who will use those privileges by
assigning just role.

Syntax of SQL-Create Role

Use the following command to create a role:

CREATE ROLE role [NOT IDENTIFIED 1 IDENTIFIED {BY password I EXTERNALLY I GLOBALLY I USING
package}]

where:

• role: Is the name of the role


• NOT IDENTIFIED: Indicates that no verification is required when enabling the role

• IDENTIFIED: Indicates that verification is required when enabling the role

• BY password: Provides the password that the user must specify when enabling the role

• USING package: Creates an application role, which is a role that can be enabled only by applications
using an authorized package

• EXTERNALLY: Indicates that a user must be authorized by an external service (such as the operating
system or a third-party service) before enabling the role

• GLOBALLY: Indicates that a user must be authorized to use the role by the enterprise directory service
before the role is enabled with the SET ROLE statement, or at login.

Roles with ADMIN option

 Not identified:

Create role oe_clerk;

 By password:

Create role hr_clerk

IDENTIFIED BY bonus;

 Identified externally:

Create role hr_manager

identified Externally;
Syntax of SQL-Create Role using EM

Alter Role

 ALTER ROLE modifies the authentication method.


 Modifying roles requires the ADMIN option or ALTER ANY ROLE privilege

Default Role

A user can be assigned many roles. A default role is a subset of these roles that is automatically enabled
when the user logs on. By default, all the roles are assigned to a user are enabled at logon without the
need of a password. Limit the default roles for a user with the ALTER USER command.
Application Roles

 Application roles can be enabled only by authorized PL/SQL packages


 The USING package clause creates an application role

Enable & Disable Role

 Disable a role to temporarily revoke the role from a user.


 Enable a role to grant it temporarily.
 The SET ROLE command enables and disables roles
 Default roles are enabled for a user at login.
 A password may be required to enable a role.
 Enable and disable roles to temporarily activate and deactivate the privileges associated with
the roles.
 To enable a role, a role must first be granted to the user.
 When a role is enabled, the user can use the privileges granted to that role. If a role is disabled,
the user cannot use the privileges associated with that role unless those privileges are granted
directly to a user or to another role enabled for that user. Roles are enabled for a session. At the
next session, the user’s active roles revert to default roles.

Specifying Roles to be Enabled

 The SET command and the DBMS_SESSION.SET_ROLE procedure enable all of the roles included
in the command and disable all other roles. Roles can be enabled from any tool or program that
allows PL/SQL commands; however, a role cannot be enabled in a stored procedure.
 You can use the ALTER USER-DEFAULT ROLE command to indicate which roles will be enabled
for a user at login. All other roles are disabled.
 A password may be required to enable a role. The password must be included in the SET ROLE
command to enable the role.
 Default roles assigned to a user do not require a password; they are enabled at login, the same
as a role without a password.

Restrictions on Enable & Disable Role

 A role cannot be enabled from a stored procedure, because this action may change the security
domain (set of privileges) that allowed the procedure to be called in the first place.
 So, in PL/SQL, Role can be enabled and disabled in anonymous blocks and application
procedures (for example, client Oracle Forms procedures), but not in stored procedures.
Reading Material:

Guidelines
Because a role includes the privileges that are necessary to perform a task, the role name is usually an
application task or a job title.

Our example uses both application tasks and job titles for role names.

Guidelines for an Example

Use the following steps to create, assign, and grant users roles:

 Create a role for each application task. The name of the application role corresponds to a task in
the application, such as PAYROLL.
 Assign the privileges necessary to perform the task to the application role.
 Create a role for each type of user. The name of the user role corresponds to a job title, such as
PAY_CLERK.
 Grant application roles to user's roles.
 Grant user's roles to users.

If a modification to the application requires that the new privileges are needed to perform the payroll
task, then the DBA only needs to assign the new privileges to the PAYROLL application role. All of the
users that are currently performing this task will receive the new privileges.

Guidelines for Assigning Roles

Guidelines for using Password and Default Roles

Passwords provide an additional level of security when enabling a role.

For example, the application might require a user to enter a password when enabling the PAY_CLERK
role, because this role can be used to issue checks.

Passwords allow a role to be enabled only through an application. This technique is shown in the
example in the slide.

 The DBA has granted the user two roles, PAY_CLERK and PAY_CLERK_RO.
 The PAY_CLERK has been granted all of the privileges that are necessary to perform the payroll
clerk function.

Roles with Password

You might also like