0% found this document useful (0 votes)
33 views18 pages

Types of Triggers

The document discusses triggers in database management systems, which are stored procedures that automatically execute in response to certain events like INSERT, UPDATE, or DELETE. It details the types of triggers based on timing, events, and levels, as well as their implementation process, benefits, and limitations. Additionally, it covers concurrency control techniques, particularly locking mechanisms, and introduces cursors in PL/SQL, including their types, advantages, limitations, and best practices for usage.

Uploaded by

yomankgg
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
0% found this document useful (0 votes)
33 views18 pages

Types of Triggers

The document discusses triggers in database management systems, which are stored procedures that automatically execute in response to certain events like INSERT, UPDATE, or DELETE. It details the types of triggers based on timing, events, and levels, as well as their implementation process, benefits, and limitations. Additionally, it covers concurrency control techniques, particularly locking mechanisms, and introduces cursors in PL/SQL, including their types, advantages, limitations, and best practices for usage.

Uploaded by

yomankgg
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/ 18

Triggers

In database management systems (DBMS), triggers are special kinds of stored procedures that are
automatically executed or triggered when certain events occur in the database. These events are usually
associated with data modification operations such as INSERT, UPDATE, or DELETE statements on a table or
view.
Triggers are used to enforce business rules, maintain data integrity, automate system tasks, and monitor
database changes without requiring manual intervention by the user or application.

Types of Triggers:
Triggers can be classified based on various criteria. The most common classifications are based on timing,
events, and levels.

1. Based on Timing:
These triggers determine when the trigger should be executed in relation to the triggering event.
a. BEFORE Trigger:
• This trigger executes before the operation (INSERT, UPDATE, or DELETE) is performed on the table.
• Mainly used for validation or modification of data before it is committed to the database.
Example use case: Validating that a salary entered for an employee is not negative before inserting the
record.
b. AFTER Trigger:
• Executes after the data modification operation has taken place.
• Commonly used for logging, auditing, or sending notifications.
Example use case: Logging the changes made to a customer’s information after the update has occurred.

2. Based on Events:
These are based on the type of data modification that causes the trigger to fire.
a. INSERT Trigger:
• Fires when a new row is inserted into a table.
b. UPDATE Trigger:
• Fires when a row is updated in a table.
• Can also be configured to fire only when certain columns are updated.
c. DELETE Trigger:
• Fires when a row is deleted from a table.

3. Based on Level:
a. Row-level Trigger:
• Executes once for each row affected by the DML operation.
• If an UPDATE affects 5 rows, the trigger will execute 5 times—once for each row.
• Accesses special pseudo-records like OLD and NEW.
b. Statement-level Trigger:
• Executes once per SQL statement, regardless of the number of rows affected.
• Does not allow access to OLD or NEW values.

Process and Implementation of Triggers:


The process of implementing triggers involves understanding the scenario, writing the trigger logic, and
attaching it to the right table and event.

Step 1: Identify the Requirement


Before creating a trigger, understand the business rule or condition you want to enforce or automate.
Examples include:
• Preventing data entry errors
• Automatically updating audit logs
• Cascading changes to related tables

Step 2: Define Trigger Conditions


Decide:
1
• What kind of trigger is needed (BEFORE/AFTER)
• Which operation will activate it (INSERT/UPDATE/DELETE)
• Whether it will be a row-level or statement-level trigger

Step 3: Write the Trigger Code


The general syntax of a trigger in SQL (e.g., in Oracle or MySQL) is:
CREATE TRIGGER trigger_name
[BEFORE | AFTER] [INSERT | UPDATE | DELETE]
ON table_name
[FOR EACH ROW]
BEGIN
-- Trigger logic goes here
END;
Explanation of parts:
• trigger_name: Unique name for the trigger
• BEFORE or AFTER: Specifies when the trigger should execute
• INSERT, UPDATE, DELETE: Specifies the event
• ON table_name: Indicates which table the trigger is attached to
• FOR EACH ROW: Optional clause that makes it a row-level trigger

Step 4: Use OLD and NEW Pseudo-Records


In row-level triggers, you can access the old and new values of the record:
• OLD.column_name: Refers to the value before the change (for UPDATE or DELETE)
• NEW.column_name: Refers to the value after the change (for INSERT or UPDATE)
These are useful for comparing values or logging changes.

Step 5: Test the Trigger


After creating the trigger, perform actions that should activate it and verify that the desired behavior occurs.
Make sure to test:
• Edge cases
• Valid and invalid data
• Rollbacks and transactions

Example:
Suppose we want to prevent employees from entering a salary less than 10,000.
CREATE TRIGGER check_salary
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF NEW.salary < 10000 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Salary must be at least 10000';
END IF;
END;
In this example:
• The trigger is fired before an INSERT.
• It checks the new salary value.
• If the salary is below 10,000, it raises an error and prevents insertion.

Benefits of Triggers:
1. Automatic Execution: Runs without user or application input.
2. Enforces Complex Rules: Can implement logic that cannot be defined using just constraints.
3. Improves Data Integrity: Ensures consistent and valid data.
4. Auditing and Logging: Useful for tracking data changes.
5. Centralized Logic: Keeps validation and automation logic inside the database rather than the
application.

Limitations of Triggers:
1. Complex Debugging: Triggers can make debugging difficult due to their automatic nature.

2
2. Hidden Execution: Since they run automatically, it may not be obvious that they have altered data
or behavior.
3. Performance Overhead: Can slow down data modification operations if not carefully written.
4. Recursive Triggers: If not handled properly, a trigger can fire another trigger, leading to infinite
loops.

Concurrency
In database systems, concurrency refers to the ability of the system to allow multiple users or transactions
to access and manipulate the database at the same time without interfering with one another.
Concurrency is essential in multi-user environments such as banking systems, e-commerce platforms, and
reservation systems where many transactions occur simultaneously.
Concurrency ensures that:
• The database remains consistent.
• Users can work independently.
• System performance is optimized, using parallelism effectively.
However, with concurrency, certain issues can arise, such as:
• Lost updates
• Dirty reads
• Non-repeatable reads
• Phantom reads
To avoid these issues, concurrency control techniques are used, and one of the most commonly used
techniques is locking.

Importance of Concurrency Control:


Concurrency control ensures:
• Isolation in transactions (as per ACID properties),
• Correctness of database operations, and
• No interference or data conflicts when multiple users access the same data.

Locking Techniques for Concurrency Control


Locking is the most widely used method for controlling concurrent access. It prevents conflicts by
restricting access to data being used in a transaction. Locks can be placed on:
• Entire databases
• Tables
• Pages
• Rows
• Even specific fields
Locks ensure that only one transaction can access the data in a certain way at a time, based on the type
of lock used.

Types of Locks:
1. Binary Lock:
• Simplest type of lock.
• Each data item is either locked (1) or unlocked (0).
• If an item is locked, no other transaction can access it until it is unlocked.
• Not flexible for allowing concurrent read access.
Limitation: Doesn’t support shared reading, which makes it too restrictive in many scenarios.

2. Shared and Exclusive Locks (S-X Locks):


This is the standard locking mechanism used in many DBMS.
• Shared Lock (S):
o Allows multiple transactions to read a data item simultaneously.
o No transaction can modify the data while it’s shared-locked.
• Exclusive Lock (X):
3
o
Allows a single transaction to both read and write the data.
o
Prevents all other access (read/write) while held.
Lock Compatibility Matrix:
Shared (S) Exclusive (X)
Shared (S) Yes No
Exclusive (X) No No
This matrix ensures:
• Multiple readers can access the same data.
• Only one writer at a time, and no readers during a write.

3. Two-Phase Locking Protocol (2PL):


A protocol that ensures serializability by dividing the execution into two phases:
1. Growing Phase:
o Transaction may acquire locks but cannot release any.
o Keeps acquiring all the locks it needs.
2. Shrinking Phase:
o Transaction releases locks and cannot acquire new ones.
Why it works:
• Ensures no conflicts due to overlapping lock and unlock operations.
• Guarantees serializable schedules.
Types of 2PL:
• Basic 2PL: Just follows growing and shrinking rules.
• Strict 2PL: Holds all exclusive locks until transaction ends (prevents cascading rollbacks).
• Rigorous 2PL: Holds all locks (shared and exclusive) until the transaction commits.

4. Timestamp Ordering with Locking:


Although timestamp ordering is a separate concurrency control technique, it can be combined with locking.
Each transaction gets a timestamp, and locks are managed in timestamp order.
This prevents deadlocks but can cause more aborts if transactions wait for long.

Granularity of Locks:
Locks can be applied at different levels of data granularity:
• Database-level lock – Affects the entire database.
• Table-level lock – Locks one table.
• Page-level lock – Locks one page (a fixed-size block of data).
• Row-level lock – Locks only the row being accessed.
• Field-level lock – Locks a specific column in a row.
Trade-off:
• Coarser granularity (e.g., table-level) = less overhead but more locking conflicts.
• Finer granularity (e.g., row-level) = more overhead but better concurrency.

Deadlock in Locking Systems:


A deadlock occurs when two or more transactions wait indefinitely for each other’s locks to be released.
Deadlock Prevention Strategies:
• Timeouts: Abort a transaction if it waits too long.
• Wait-die / Wound-wait schemes: Use transaction timestamps to decide which one should wait or
abort.
• Deadlock detection: The system detects cycles in the wait-for graph and aborts one of the
transactions.

Advantages of Lock-Based Concurrency Control:


• Easy to understand and implement.
• Ensures data consistency.
• Works well for systems where read/write conflicts are common.

Limitations of Locking:
4
• Deadlocks can halt system progress.
• Starvation may occur if a transaction keeps waiting.
• Can reduce performance if overused, especially with coarse-grained locks.

Cursor
In database systems, a cursor is a database object used to retrieve, manipulate, and navigate through a
result set row by row. While SQL is generally set-oriented and operates on entire sets of rows at once,
cursors are helpful when row-by-row processing is required.
Think of a cursor like a pointer or a temporary work area in memory that allows you to fetch one record at
a time from a larger query result. Cursors are particularly useful in procedural database programming,
such as with PL/SQL in Oracle or T-SQL in SQL Server.

Why Use Cursors?


Cursors are used when:
• Complex row-by-row logic is required (such as iterative processing).
• Updates or actions must be performed on each row individually.
• Control structures like loops and conditions need to be applied at the row level.

Types of Cursors:
Cursors can be categorized in various ways depending on their behavior, visibility, and data sensitivity.
Below are the main types:

1. Implicit Cursor:
An implicit cursor is automatically created by the database whenever a DML statement (INSERT, UPDATE,
DELETE, SELECT INTO) is executed.
• You do not define or control it explicitly.
• Mainly used for single-row queries.
• The system manages its lifecycle and operations.
Example (PL/SQL):
BEGIN
UPDATE employees SET salary = salary + 1000 WHERE department_id = 10;
IF SQL%ROWCOUNT > 0 THEN
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' rows updated');
END IF;
END;
Here, Oracle uses an implicit cursor to perform the update and tracks the number of affected rows using
SQL%ROWCOUNT.

2. Explicit Cursor:
Explicit cursors are declared and controlled manually by the programmer. They are used when a query
returns multiple rows, and the program needs to process each row one by one.
Basic Steps in Using an Explicit Cursor:
1. Declare the cursor.
2. Open the cursor (execute the query).
3. Fetch each row into a variable.
4. Process the data.
5. Close the cursor.

Classification of Cursors Based on Behavior:


a. Static Cursor:
• The result set is fixed at the time of opening the cursor.
• Changes made to the underlying data after opening the cursor do not affect the cursor.
5
• Most default cursors are static.

b. Dynamic Cursor:
• Reflects all changes (insert, update, delete) made to the data while the cursor is open.
• Useful when real-time data tracking is needed.

c. Forward-Only Cursor:
• Can only move in one direction (from the first row to the last).
• Fetching backward is not allowed.
• Often more efficient and less memory-intensive.

d. Scrollable Cursor:
• Can move forward and backward, jump to specific rows, or re-fetch.
• Offers flexibility but is heavier on performance and memory.
Example SQL Server Syntax:
DECLARE emp_cursor CURSOR SCROLL FOR
SELECT employee_id FROM employees;

Cursor Attributes:
Most DBMSs support cursor attributes that provide status information:
• %FOUND – TRUE if the last fetch returned a row.
• %NOTFOUND – TRUE if the last fetch did not return a row.
• %ROWCOUNT – Number of rows processed so far.
• %ISOPEN – TRUE if the cursor is currently open.
These attributes help in controlling the cursor’s behavior during loops and conditional processing.

Advantages of Cursors:
• Allows row-by-row processing of query results.
• Offers fine-grained control over data manipulation.
• Ideal for procedural operations that cannot be easily expressed with set-based SQL.

Limitations of Cursors:
• Performance Overhead: Processing rows one at a time is slower than set-based operations.
• Memory Usage: Active cursors consume memory, especially if not closed properly.
• Complexity: Cursor-based logic is often harder to read and maintain.

Best Practices:
• Avoid cursors when a set-based SQL statement can achieve the same result.
• Always close cursors after use to free resources.
• Use explicit cursors only when truly necessary (e.g., complex row-level logic).
• Monitor and manage transaction scope carefully to avoid locks and performance issues.

6
PL/SQL Block and Its Components
In Oracle, PL/SQL (Procedural Language for SQL) is a powerful extension of SQL that allows the use of
procedural constructs like loops, conditions, and variables. A PL/SQL block is the basic unit of execution
in PL/SQL programs and consists of a group of statements organized into three distinct sections.

Components of a PL/SQL Block:


Each PL/SQL block has the following structure:
DECLARE
-- Declarations (optional)
BEGIN
-- Executable statements (mandatory)
EXCEPTION
-- Exception handling (optional)
END;
Let’s explore each section in detail.

1. Declaration Section (DECLARE):


• This section is optional.
• Used to declare variables, constants, cursors, exceptions, and user-defined data types.
• These declarations are only valid inside the block (local scope).
Example:
DECLARE
v_salary NUMBER(8,2);
v_name VARCHAR2(50);
CURSOR emp_cursor IS SELECT name FROM employees;

2. Execution Section (BEGIN ... END):


• This section is mandatory.
• Contains the actual SQL and PL/SQL statements to be executed.
• Statements are written in sequential order and may include loops, conditionals (IF, CASE), DML
statements (INSERT, UPDATE, DELETE), and procedure calls.
Example:
BEGIN
v_salary := 30000;
UPDATE employees SET salary = salary + 1000 WHERE department_id = 10;

3. Exception Handling Section (EXCEPTION):


• This section is optional.
• Used to handle runtime errors (such as divide-by-zero, no data found, etc.).
• Prevents abrupt termination of the program by gracefully handling errors.
Example:
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee found');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred');

Types of PL/SQL Blocks:


PL/SQL blocks are of two types:
1. Anonymous Block:
o Does not have a name.
o Cannot be stored in the database for reuse.
o Used for one-time execution.
2. Named Block:
o Has a name (Procedure, Function, Package, or Trigger).
o Can be stored in the database for reuse and sharing.
o Supports parameters and modular design.

7
Example of Full PL/SQL Block:
DECLARE
v_emp_id NUMBER := 101;
v_salary NUMBER;
BEGIN
SELECT salary INTO v_salary FROM employees WHERE employee_id = v_emp_id;
DBMS_OUTPUT.PUT_LINE('Salary is: ' || v_salary);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee not found');
END;

PL/SQL Data Types:


PL/SQL supports a variety of data types categorized into scalar, composite, reference, and large object
types. These allow developers to store, manipulate, and transfer different kinds of data.

1. Scalar Data Types:


These store single values like numbers, characters, and dates.
a. Numeric Types:
• NUMBER – Can store integers, decimals, or floating-point numbers.
• v_price NUMBER(6,2);
• BINARY_INTEGER, PLS_INTEGER – Optimized for integer arithmetic operations.
• v_count PLS_INTEGER := 0;
b. Character Types:
• CHAR(size) – Fixed-length string.
• VARCHAR2(size) – Variable-length string.
• LONG – For long text up to 2 GB (deprecated in favor of CLOB).
v_name VARCHAR2(50);
c. Date/Time Types:
• DATE – Stores date and time.
• TIMESTAMP – Stores date with fractional seconds.
• INTERVAL – Stores time intervals.
v_dob DATE;
d. Boolean Type:
• BOOLEAN – Can store TRUE, FALSE, or NULL.
• v_flag BOOLEAN := TRUE;

2. Composite Data Types:


These hold multiple values or structured data.
a. Records:
• User-defined structured type to hold related data.
TYPE emp_rec IS RECORD (
emp_id NUMBER,
emp_name VARCHAR2(100)
);
b. Collections:
• VARRAY – Fixed-size array.
• Nested Table – Unbounded array that can be modified.
• Associative Array (Index-by table) – Key-value pair like a dictionary.
TYPE num_list IS TABLE OF NUMBER;

3. Reference Data Types:


Used to create pointers to rows in database tables.
• REF CURSOR – A cursor variable that can point to different queries at runtime.
TYPE ref_cursor IS REF CURSOR;

4. Large Object (LOB) Types:


Used to store large data like documents, images, and multimedia.
• CLOB – Character Large Object.

8
• BLOB – Binary Large Object.
• NCLOB – Multilingual character data.
• BFILE – External binary file stored outside the database.

Predefined Subtypes:
Oracle defines several subtypes to improve readability and compatibility:
• VARCHAR is a subtype of VARCHAR2.
• DEC and INT are subtypes of NUMBER.

RDBMS
A Relational Database Management System (RDBMS) is a type of database management system that
stores data in the form of related tables. These tables are made up of rows and columns, where:
• Each row represents a unique record (also called a tuple).
• Each column represents a field or attribute.
RDBMS is based on E.F. Codd’s relational model introduced in 1970. It uses Structured Query
Language (SQL) to manage and manipulate relational data.
Popular RDBMS software includes Oracle, MySQL, PostgreSQL, SQL Server, and IBM DB2.

Key Characteristics of RDBMS:


1. Tables (Relations): Data is organized into multiple tables with rows and columns.
2. Primary Keys: Each table has a unique identifier for its records.
3. Foreign Keys: Used to define relationships between tables.
4. Data Integrity: Maintains accuracy and consistency using constraints.
5. Normalization: Reduces redundancy by organizing data into related tables.
6. SQL Support: Provides standardized language for querying and modifying data.

Difference Between DBMS and RDBMS:


Before understanding the advantages of RDBMS over DBMS, it’s important to understand the basic
difference.
Feature DBMS RDBMS
Data Storage Files or simple structures Tables with rows and columns
Relationship Support No relation between data Supports relationships using foreign keys
Normalization Not enforced Follows normalization rules
Data Redundancy More Less due to normalization
Data Integrity Minimal support Strong enforcement using constraints
Multi-user Access Limited Handles multiple users efficiently
Examples MS Access (basic), FoxPro MySQL, Oracle, SQL Server, PostgreSQL

Advantages of RDBMS over DBMS:


RDBMS provides significant improvements over traditional DBMS systems in terms of structure,
efficiency, integrity, and usability. Let's explore these advantages in detail.

1. Data Structuring through Tables:


• DBMS: Stores data in files, arrays, or hierarchical structures, which may not be uniform.
• RDBMS: Organizes data into standardized tables, making it easier to access, update, and maintain.
Advantage: Easier to model complex data and relationships in a structured way.

2. Data Redundancy Minimization:


9
• RDBMS uses normalization techniques to reduce data duplication.
• DBMS often stores the same data in multiple places due to lack of normalization.
Advantage: Saves storage space and ensures consistency across records.

3. Data Integrity and Accuracy:


• RDBMS supports integrity constraints like:
o Primary Key: Ensures each record is unique.
o Foreign Key: Ensures referential integrity.
o Check constraints and NOT NULL rules.
• These constraints are not well-enforced in traditional DBMS.
Advantage: Prevents invalid or inconsistent data from entering the database.

4. Support for Relationships:


• In DBMS, no direct way to define relationships between datasets.
• RDBMS supports one-to-one, one-to-many, and many-to-many relationships via foreign keys.
Advantage: Reflects real-world connections between data entities.

5. Better Security Control:


• RDBMS allows user authentication, authorization, and role-based access.
• DBMS lacks advanced security layers.
Advantage: More secure and better suited for multi-user environments.

6. Concurrency and Multi-user Access:


• RDBMS handles simultaneous access to data using techniques like locking and transactions.
• DBMS struggles with concurrent access and often risks data inconsistency.
Advantage: Supports enterprise-level applications with many users.

7. Use of SQL (Structured Query Language):


• RDBMS uses SQL as a standard language for querying, inserting, updating, and managing data.
• In DBMS, no standard querying language; it may use proprietary methods.
Advantage: SQL makes RDBMS more powerful, flexible, and easier to use.

8. Transaction Management:
• RDBMS supports ACID properties:
o Atomicity: All or nothing execution
o Consistency: Maintains database rules
o Isolation: No interference from other transactions
o Durability: Changes are permanent after commit
• DBMS generally does not enforce all ACID properties.
Advantage: Ensures reliable and consistent data even in failure or concurrent environments.

9. Scalability and Performance:


• RDBMS is optimized for high performance, especially for large datasets and complex queries.
• Supports indexing, query optimization, and partitioning.
• DBMS performance degrades with complexity and size.
Advantage: Suitable for large-scale business and enterprise applications.

10. Backup and Recovery:


• RDBMS provides built-in mechanisms for automatic backup and recovery.
• In DBMS, such features are either manual or limited.
Advantage: Ensures data safety in case of hardware/software failure.

10
Oracle Database
Introduction to Oracle Database
Oracle Database is a relational database management system (RDBMS) developed by Oracle
Corporation. It is one of the most widely used and robust database systems in the world, known for its:
• High performance
• Scalability
• Reliability
• Security features
It supports both OLTP (Online Transaction Processing) and OLAP (Online Analytical Processing) and
is commonly used in enterprise-level applications like banking, telecommunications, government, and e-
commerce.
Oracle supports SQL for querying and PL/SQL (Procedural Language/SQL) for procedural operations.

Key Features of Oracle


• Multi-user Access: Supports thousands of concurrent users.
• Portability: Runs on various platforms (Windows, Linux, UNIX).
• Concurrency Control: Ensures transaction isolation and ACID compliance.
• Backup and Recovery: Includes robust tools like RMAN.
• Data Integrity & Security: Uses roles, privileges, and encryption.
• Partitioning & Clustering: Enables handling of large datasets and high-availability setups.
• Support for Advanced Data Types: Includes LOBs, XML, JSON, spatial data, etc.

Oracle Database Architecture


The architecture of Oracle Database is based on two major components:
1. Instance
2. Database
Together, they enable Oracle to store and manage data efficiently.

1. Oracle Instance
An instance is a set of memory structures and background processes that interact with the physical
database files. Each time a database is started, an instance is created.
Main Components of an Instance:

A. Memory Structures
These are allocated when the instance starts and deallocated when it shuts down.
i. System Global Area (SGA):
A shared memory area used by all server processes. It includes:
• Database Buffer Cache: Stores recently accessed data blocks.
• Shared Pool: Holds SQL statements, PL/SQL code, data dictionary info.
• Redo Log Buffer: Temporarily stores redo entries before writing to redo logs (for recovery).
• Large Pool: Used for large memory allocations like parallel processing.
• Java Pool: Used if Java is executed inside the database.
• Streams Pool: Used by Oracle Streams for data replication.
ii. Program Global Area (PGA):
A private memory area used by each server process. It stores session-specific information like:
• Sort area
• Session variables
• Cursor state

B. Background Processes
Oracle starts a set of background processes automatically with the instance. Key ones include:
• DBWn (Database Writer): Writes modified data blocks from buffer cache to data files.
• LGWR (Log Writer): Writes redo entries from the redo log buffer to the redo log files.
• CKPT (Checkpoint): Signals DBWn to write data and updates metadata in control files.
• SMON (System Monitor): Performs recovery after system failure.
11
• PMON (Process Monitor): Cleans up after failed processes.
• ARCn (Archiver): Copies redo logs to archive storage (used in ARCHIVELOG mode).
• MMON (Manageability Monitor): Collects performance data.
• RECO (Recoverer): Handles distributed transaction failures.
These background processes are essential for performance, recovery, and data integrity.

2. Oracle Database (Physical Storage)


The database consists of physical files stored on disk.
Main Types of Physical Files:

i. Data Files (.dbf):


• Store the actual user and system data.
• Every table, index, and other schema object is stored in data files.
ii. Control Files (.ctl):
• Hold metadata about the database structure such as:
o Database name
o Data file locations
o Redo log locations
o Timestamp and checkpoints
iii. Redo Log Files (.log):
• Store all changes made to the data (before they are written to data files).
• Used to recover the database in case of failure.
iv. Archived Redo Logs (optional):
• Saved copies of redo logs.
• Used in point-in-time recovery and backup scenarios.
v. Parameter Files (spfile/init.ora):
• Store configuration settings for the instance.
• SPFILE (Server Parameter File) is the preferred format.
vi. Password File:
• Allows remote authentication of database administrators.

Working of Oracle Architecture (Step-by-Step Flow):


1. User connects to the database using SQL*Plus or any application.
2. A server process is created to handle the request.
3. The server process checks the shared pool for the SQL statement:
o If found → reused (known as soft parse)
o If not → parsed, optimized, and stored (known as hard parse)
4. Data is fetched from the buffer cache if available, or from data files.
5. Any changes are recorded in the redo log buffer, then written to redo log files by LGWR.
6. The DBWn process writes modified blocks to the data files.
7. If any failure occurs, SMON and PMON ensure recovery.
8. The control file maintains synchronization and tracks checkpoint info.

Logical Structure of Database:


Oracle also organizes data logically using these elements:
• Tablespaces: Logical storage units. Each tablespace maps to one or more data files.
• Segments: A set of extents used by tables, indexes, etc.
• Extents: A group of contiguous data blocks.
• Blocks: The smallest unit of storage.

Oracle Architecture Diagram (Textual View) Advantages of Oracle Database:


User Session • Highly Reliable and Scalable

Server Process • Strong Security and Role Management
↓ • Powerful Backup and Recovery Tools
SGA (Buffer Cache, Shared Pool, Redo Buffer)

• Advanced Performance Features (Partitioning,
Background Processes (DBWn, LGWR, SMON, etc.) Parallelism)
↓ • Cross-platform Portability
Physical Files (Data Files, Redo Logs, Control Files)
• Support for Distributed Databases
12
Stored Procedure and Difference from Function
What is a Stored Procedure in Oracle?
A stored procedure in Oracle is a named PL/SQL subprogram that is stored in the database and can be
executed repeatedly. It performs one or more actions (such as inserting, updating, deleting, or processing
data) but does not return a value directly like a function does.
Stored procedures are used to encapsulate business logic, automate tasks, and modularize code,
especially in complex applications.

Syntax of a Stored Procedure:


CREATE OR REPLACE PROCEDURE procedure_name (
param1 IN datatype,
param2 OUT datatype,
param3 IN OUT datatype
)
IS
-- Variable declarations (optional)
BEGIN
-- Executable statements
EXCEPTION
-- Exception handling (optional)
END;

Components of a Stored Procedure:


1. Procedure Name: Unique identifier.
2. Parameters:
o IN – Input only
o OUT – Output only
o IN OUT – Both input and output
3. Executable Section: Contains SQL and PL/SQL code.
4. Exception Section (optional): Handles runtime errors.

Example:
CREATE OR REPLACE PROCEDURE update_salary (
p_emp_id IN employees.employee_id%TYPE,
p_increment IN NUMBER
)
IS
BEGIN
UPDATE employees
SET salary = salary + p_increment
WHERE employee_id = p_emp_id;

DBMS_OUTPUT.PUT_LINE('Salary updated successfully.');


END;

Calling a Stored Procedure:


BEGIN
update_salary(101, 5000);
END;

Advantages of Stored Procedures:


1. Modularity: Logic is organized into reusable blocks.
2. Performance: Precompiled and stored in the database for faster execution.
3. Reduced Network Traffic: Logic runs on the server; only results are sent to the client.
4. Security: Access to underlying data can be restricted via procedure interfaces.
5. Maintainability: Business logic centralized in one place for easy updates.
6. Support for Multiple Actions: Can include multiple DML statements and complex operations.

13
Difference Between Function and Stored Procedure in Oracle
Both functions and procedures are PL/SQL subprograms, but they have key differences in purpose,
behavior, and usage.

1. Return Value
Feature Function Stored Procedure
Return Must return a single value Does not return a value directly
Usage Can be used in SQL expressions Called from PL/SQL blocks only

2. Purpose and Usage


Feature Function Stored Procedure
Main Purpose Perform computations Perform actions/tasks
Use in SQL Queries Yes (e.g., SELECT get_bonus(...)) No (cannot be used in SQL SELECT)
Example Use Case Return total salary, compute age Update record, insert data, log activity

3. Parameter Modes
Feature Function Stored Procedure
Parameter Types Only IN IN, OUT, and IN OUT

4. SQL Usage and Restrictions


• Function: Can be called from SELECT, WHERE, ORDER BY.
• Procedure: Cannot be used in SQL statements; must be invoked from BEGIN...END.

5. Flexibility
• Function: Suitable for returning computed values.
• Procedure: Suitable for multiple operations, complex processing, and transaction control.

When to Use What?


• Use a function when:
o You need to compute and return a value.
o The result is used within SQL queries.
• Use a stored procedure when:
o You need to perform actions like updates, inserts, or logging.
o You require multiple outputs or transaction control.
o Logic needs to be executed repeatedly and securely.

Data Constraints
Definition of Data Constraints
In Oracle, data constraints are rules applied to table columns to enforce data integrity and restrict
invalid data entry. These constraints ensure that the data stored in the database remains accurate,
consistent, and meaningful.
Constraints are defined at the time of table creation or later using the ALTER TABLE command. Once
applied, they automatically validate all incoming data and prevent operations that would violate the rules.

Why Use Constraints?


• To maintain data consistency and correctness.
• To prevent duplicate, null, or invalid entries.

14
• To enforce business rules at the database level.
• To avoid application-level validation repetition.

Types of Data Constraints in Oracle


Oracle supports the following types of constraints:

1. NOT NULL Constraint


• Ensures that a column cannot have NULL values.
• Must be specified at the column level only.
Example:
CREATE TABLE employees (
emp_id NUMBER,
name VARCHAR2(50) NOT NULL
);
Explanation:
The name column must always have a value. Any attempt to insert a NULL will raise an error.

2. UNIQUE Constraint
• Ensures that all values in a column (or group of columns) are distinct.
• Allows one NULL value per column.
Example:
CREATE TABLE users (
user_id NUMBER PRIMARY KEY,
email VARCHAR2(100) UNIQUE
);
Explanation:
No two users can have the same email address.

3. PRIMARY KEY Constraint


• Uniquely identifies each record in a table.
• Combines the rules of UNIQUE and NOT NULL.
• A table can have only one primary key (single or composite).
Example:
CREATE TABLE departments (
dept_id NUMBER PRIMARY KEY,
dept_name VARCHAR2(50)
);
Explanation:
Each department must have a unique, non-null dept_id.

4. FOREIGN KEY Constraint


• Establishes a relationship between two tables.
• Ensures that a value in one table must exist in another table (referential integrity).
Example:
CREATE TABLE employees (
emp_id NUMBER PRIMARY KEY,
name VARCHAR2(50),
dept_id NUMBER,
CONSTRAINT fk_dept
FOREIGN KEY (dept_id)
REFERENCES departments(dept_id)
);
Explanation:
The dept_id in employees must match an existing dept_id in departments.

5. CHECK Constraint
• Validates column values based on a logical condition.
• Ensures that values meet custom-defined rules.
Example:
CREATE TABLE products (

15
product_id NUMBER,
price NUMBER CHECK (price > 0)
);
Explanation:
Product price must always be greater than zero.

6. DEFAULT Constraint (Bonus)


• Assigns a default value to a column when no value is specified during insertion.
Example:
CREATE TABLE orders (
order_id NUMBER,
status VARCHAR2(20) DEFAULT 'Pending'
);
Explanation:
If status is not specified during INSERT, it defaults to 'Pending'.

How Constraints Are Applied in Oracle


Constraints can be applied in two ways:

A. At Table Creation Time


Example:
CREATE TABLE student (
roll_no NUMBER PRIMARY KEY,
name VARCHAR2(50) NOT NULL,
age NUMBER CHECK (age >= 18)
);

B. Using ALTER TABLE Command (After Creation)


Example:
ALTER TABLE student
ADD CONSTRAINT unique_name UNIQUE(name);

ALTER TABLE student


MODIFY age NUMBER NOT NULL;

Naming Constraints (Best Practice)


While Oracle auto-generates names for constraints, it’s better to name them manually for clarity and
maintenance.
Example:
CONSTRAINT pk_emp PRIMARY KEY(emp_id)
CONSTRAINT chk_salary CHECK (salary > 0)

Viewing Constraints in Oracle


You can query the USER_CONSTRAINTS and USER_CONS_COLUMNS views to see constraints:
SELECT constraint_name, constraint_type, table_name
FROM user_constraints
WHERE table_name = 'EMPLOYEES';

Constraint Types in Dictionary (Shortcut Codes):


Code Constraint Type
C CHECK
P PRIMARY KEY
U UNIQUE
R FOREIGN KEY (REFERENTIAL)
N NOT NULL

16
Comprehensive Explanation of JOIN in SQL with Types and Examples

What is a JOIN?
In SQL, a JOIN is a clause used to combine rows from two or more tables based on a related column
between them—usually a foreign key in one table that references a primary key in another.
Joins help retrieve related data stored across multiple tables in a relational database. Without JOINs,
you’d have to manage redundant data, which violates the principles of normalization.

Why Use JOINs?


• To fetch data from multiple tables in a single query.
• To reflect relationships between entities, like employees and departments.
• To reduce redundancy and maintain data consistency.
• To apply business logic based on multiple table conditions.

Basic Syntax of JOIN:


SELECT columns
FROM table1
JOIN table2
ON table1.common_column = table2.common_column;

Types of JOINs in SQL


JOINs are categorized based on how they match records from the participating tables. The major types are:

1. INNER JOIN (Equi Join)


Definition:
An INNER JOIN returns only the rows that have matching values in both tables.
Syntax:
SELECT e.employee_id, e.name, d.department_name
FROM employees e
INNER JOIN departments d
ON e.department_id = d.department_id;
Example Tables:
employees
employee_id name department_id
101 Alice 1
102 Bob 2
departments
department_id department_name
1 HR
2 IT
Result:
employee_id name department_name
101 Alice HR
102 Bob IT

2. LEFT JOIN (LEFT OUTER JOIN)


Definition:
Returns all rows from the left table, and the matched rows from the right table. If there is no match,
NULLs are returned from the right side.
Syntax:
SELECT e.name, d.department_name
FROM employees e
LEFT JOIN departments d
ON e.department_id = d.department_id;

17
Example:
If one employee has a NULL department_id, that employee still appears, with NULL for the department name.

3. RIGHT JOIN (RIGHT OUTER JOIN)


Definition:
Returns all rows from the right table, and the matched rows from the left table. If no match, NULLs are
returned from the left.
Syntax:
SELECT e.name, d.department_name
FROM employees e
RIGHT JOIN departments d
ON e.department_id = d.department_id;
Use Case:
To find departments that don’t have any employees yet.

4. FULL OUTER JOIN


Definition:
Returns all rows from both tables. When there is a match, rows are joined. When there is no match,
NULLs fill the missing side.
Syntax (in systems that support it):
SELECT e.name, d.department_name
FROM employees e
FULL OUTER JOIN departments d
ON e.department_id = d.department_id;
Example:
Combines results of LEFT and RIGHT JOIN.
Note: Not all RDBMSs support FULL OUTER JOIN (e.g., MySQL doesn’t by default).

5. CROSS JOIN
Definition:
Produces a Cartesian product of both tables: every row from the first table is combined with every row
from the second.
Syntax:
SELECT e.name, d.department_name
FROM employees e
CROSS JOIN departments d;
Result:
If employees has 3 rows and departments has 2, output will have 3 × 2 = 6 rows.
Use Case:
Rare in practical scenarios unless deliberate; useful in generating combinations or test cases.

6. SELF JOIN
Definition:
A SELF JOIN is a JOIN where a table is joined with itself, usually to compare rows within the same table.
Syntax:
SELECT e1.name AS Employee, e2.name AS Manager
FROM employees e1
JOIN employees e2
ON e1.manager_id = e2.employee_id;
Use Case:
Used in hierarchical data, such as employee-manager relationships.

18

You might also like