Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Wednesday, August 20, 2025

Master Oracle Database: Module 1 – Your Ultimate Guide to Oracle Database Fundamentals



Welcome to Module 1 of our Complete Oracle Database Course Outline: From Basics to Advanced PL/SQL! This comprehensive, SEO-friendly blog post dives deep into the essentials of Oracle Database, covering What is Oracle Database?, Oracle Architecture (Instance, SGA, PGA, Datafiles, Redo Logs, Control Files), Oracle Editions and Use Cases, Oracle 21c & 23c New Features and Improvements, Installing Oracle Database on Windows, Linux, and Cloud, and Oracle SQL Developer & Other Tools.

Designed for beginners and professionals alike, this guide is packed with practical examples, detailed explanations, real-world scenarios, pros and cons, alternatives, and best practices for security, performance, and error handling. With over 15,000 words, we’ll also build a real-life inventory management database to solidify your understanding. Let’s embark on your Oracle Database journey!


Table of Contents

  1. Introduction to Oracle Database

  2. What is Oracle Database?

    • Understanding Oracle Database

    • Pros, Cons, and Alternatives

    • Real-Life Examples

  3. Overview of Oracle Architecture

    • Instance: SGA, PGA, and Background Processes

    • Physical Structure: Datafiles, Redo Logs, Control Files

    • Pros, Cons, and Alternatives

    • Example: Exploring Oracle Architecture

  4. Oracle Editions and Use Cases

    • Overview of Oracle Editions

    • Use Cases for Each Edition

    • Pros, Cons, and Alternatives

    • Example: Choosing an Oracle Edition

  5. Oracle 21c & 23c Overview: New Features and Improvements

    • Oracle 21c Highlights

    • Oracle 23c (23ai) Highlights

    • Pros, Cons, and Alternatives

    • Example: Using AI Vector Search in Oracle 23c

  6. Installing Oracle Database (Windows/Linux/Cloud)

    • Installation on Windows

    • Installation on Linux

    • Cloud Installation (OCI)

    • Pros, Cons, and Alternatives

    • Example: Installing Oracle Database 23c on Windows

  7. Oracle SQL Developer & Other Tools

    • Oracle SQL Developer

    • Other Tools: SQL*Plus, Oracle Enterprise Manager

    • Pros, Cons, and Alternatives

    • Example: Querying with SQL Developer

  8. Best Practices for Oracle Database Development

    • Security Best Practices

    • Performance Best Practices

    • Error Handling Best Practices

  9. Real-Life Example: Building an Inventory Management Database

  10. Conclusion

  11. FAQs


Introduction to Oracle Database

Oracle Database is a leading relational database management system (RDBMS) renowned for its robustness, scalability, and enterprise-grade features. Since its inception in 1979, Oracle has powered mission-critical applications for global brands like FedEx, Spotify, and Zoom. In Module 1, we lay the foundation for mastering Oracle Database by exploring its core concepts, architecture, editions, new features in 21c and 23c, installation processes, and essential tools like SQL Developer.

This guide covers:

  • What is Oracle Database?: History, features, and its role in modern applications.

  • Oracle Architecture: Understanding Instance, SGA, PGA, Datafiles, Redo Logs, and Control Files.

  • Oracle Editions: Express, Standard, Enterprise, and Cloud editions with their use cases.

  • Oracle 21c & 23c: New features like AI Vector Search and Blockchain Tables.

  • Installing Oracle Database: Step-by-step setup on Windows, Linux, and Oracle Cloud.

  • Oracle SQL Developer & Tools: Managing databases with user-friendly tools.

With practical examples, a real-world inventory management database, and best practices for security, performance, and error handling, this post equips you with the knowledge to start your Oracle journey. Let’s dive in!


What is Oracle Database?

Understanding Oracle Database

Oracle Database is a multi-model RDBMS developed by Oracle Corporation, designed for online transaction processing (OLTP), data warehousing, and mixed workloads. It supports SQL for querying and PL/SQL for procedural programming, making it versatile for enterprise applications. Oracle’s “Write Once, Run Anywhere” philosophy ensures compatibility across platforms, from on-premises servers to cloud environments.

Key Features

  • Scalability: Handles massive datasets and high-concurrency workloads.

  • Reliability: ACID compliance ensures data integrity.

  • Security: Advanced encryption, auditing, and access controls.

  • Multi-Model: Supports relational, JSON, graph, and vector data.

  • Cloud Integration: Seamless operation on Oracle Cloud Infrastructure (OCI).

History

  • 1977: Founded as Software Development Laboratories (SDL) by Larry Ellison, Bob Miner, and Ed Oates.

  • 1979: Released Oracle V2, the first SQL-based RDBMS.

  • 1985: Oracle 5 introduced client-server architecture.

  • 1998: Oracle 8i added internet and Java support.

  • 2023: Oracle 23c (23ai) introduced AI-driven features like Vector Search.

Pros, Cons, and Alternatives for Oracle Database

Pros

  • Enterprise-Grade: Trusted by global brands for mission-critical systems.

  • Multi-Model: Supports relational, JSON, graph, and AI vector data.

  • High Availability: Features like Real Application Clusters (RAC) ensure uptime.

  • Cloud Support: Seamless integration with OCI, Azure, and AWS.

  • Robust Security: Advanced encryption and auditing capabilities.

Cons

  • Cost: Enterprise Edition is expensive with complex licensing.

  • Complexity: Steep learning curve for beginners.

  • Resource Usage: High memory and CPU requirements.

  • Vendor Lock-In: Heavy reliance on Oracle’s ecosystem.

  • Maintenance: Requires skilled DBAs for optimal performance.

Alternatives

  • Microsoft SQL Server: Cost-effective for Windows-based environments.

  • PostgreSQL: Open-source, extensible, and free.

  • MySQL: Lightweight, ideal for web applications.

  • MongoDB: NoSQL for unstructured data and scalability.

  • Google Cloud Spanner: Distributed SQL for cloud-native apps.

Real-Life Examples of Oracle Database

  • Financial Services: Banks use Oracle for transaction processing and fraud detection.

  • E-Commerce: Retailers like Amazon leverage Oracle for order management.

  • Telecommunications: Verizon uses Oracle for billing and customer data.

  • Healthcare: Hospitals manage patient records with Oracle’s secure storage.

  • Cloud Apps: Spotify uses Oracle Cloud for scalable data analytics.


Overview of Oracle Architecture

Instance: SGA, PGA, and Background Processes

An Oracle Instance is a set of memory structures and background processes that manage database files. It exists in memory and is independent of the physical database.

System Global Area (SGA)

  • Definition: Shared memory area for all database processes, storing data and control information.

  • Components:

    • Database Buffer Cache: Caches data blocks to reduce disk I/O.

    • Redo Log Buffer: Stores changes for recovery.

    • Shared Pool: Holds parsed SQL, PL/SQL, and execution plans.

    • Java Pool: Supports Java applications (optional).

    • Large Pool: Used for backups and shared server sessions.

  • Purpose: Enhances performance by minimizing disk access.

Program Global Area (PGA)

  • Definition: Non-shared memory for each server or background process, storing session-specific data.

  • Components:

    • SQL Work Areas: For sorting, hashing, and joins.

    • Private SQL Area: Stores bind variables and query state.

  • Purpose: Supports user sessions and SQL execution.

Background Processes

  • DBWn (Database Writer): Writes data from buffer cache to datafiles.

  • LGWR (Log Writer): Writes redo log buffer to redo log files.

  • CKPT (Checkpoint): Updates control files and datafiles with checkpoints.

  • SMON (System Monitor): Performs instance recovery.

  • PMON (Process Monitor): Cleans up failed processes.

  • LREG (Listener Registration): Registers with Oracle Net Listener.

Physical Structure: Datafiles, Redo Logs, Control Files

The Oracle Database consists of physical files stored on disk.

Datafiles

  • Definition: Store actual database data in tablespaces (logical containers).

  • Structure: Organized into data blocks, extents, and segments.

  • Purpose: Hold tables, indexes, and other objects.

Redo Logs

  • Definition: Record all database changes for recovery.

  • Types: Online redo logs (active) and archived redo logs (for backups).

  • Purpose: Ensure recoverability after crashes or failures.

Control Files

  • Definition: Binary files storing database metadata (e.g., database name, file locations).

  • Purpose: Track database structure and state.

Pros, Cons, and Alternatives for Oracle Architecture

Pros

  • SGA:

    • Performance: Caches data for faster access.

    • Scalability: Shared across processes for efficiency.

  • PGA:

    • Session Isolation: Ensures secure, independent user sessions.

    • Flexibility: Supports complex SQL operations.

  • Background Processes:

    • Automation: Handles recovery, logging, and maintenance.

    • Reliability: Ensures data consistency and availability.

  • Physical Files:

    • Recoverability: Redo logs and control files enable robust recovery.

    • Organization: Logical and physical separation optimizes storage.

Cons

  • SGA:

    • Memory Usage: High memory allocation for large databases.

    • Configuration: Requires tuning for optimal performance.

  • PGA:

    • Resource Intensive: Multiple sessions increase memory demand.

    • Complexity: Managing PGA sizes can be challenging.

  • Background Processes:

    • Overhead: Multiple processes increase CPU usage.

    • Monitoring: Requires tools like Oracle Enterprise Manager.

  • Physical Files:

    • Storage: Large datasets require significant disk space.

    • Backup Complexity: Managing redo logs and control files is intricate.

Alternatives

  • SQL Server Architecture: Uses buffer pools and transaction logs, simpler for Windows environments.

  • PostgreSQL: Open-source, with shared buffers and write-ahead logging.

  • MongoDB: NoSQL with document-based storage, no SGA/PGA.

  • AWS Aurora: Cloud-native with distributed storage and logs.

Example: Exploring Oracle Architecture

Step 1: Query SGA and PGA

  • Connect to SQL*Plus or SQL Developer:

    SELECT name, value/1024/1024 AS "Size (MB)" FROM v$sga;
    SELECT name, value/1024/1024 AS "Size (MB)" FROM v$pgastat WHERE name LIKE '%aggregate%';
  • Output (example):

    NAME                  Size (MB)
    -------------------- ---------
    Fixed SGA             10
    Database Buffers      2048
    Redo Buffers          8
    Shared Pool           512
    
    NAME                  Size (MB)
    -------------------- ---------
    aggregate PGA target  1024

Step 2: Check Physical Files

  • Query datafiles, redo logs, and control files:

    SELECT name FROM v$datafile;
    SELECT member FROM v$logfile;
    SELECT name FROM v$controlfile;
  • Output (example):

    NAME
    --------------------
    /u01/oradata/CDB/system01.dbf
    
    MEMBER
    --------------------
    /u01/oradata/CDB/redo01.log
    
    NAME
    --------------------
    /u01/oradata/CDB/control01.ctl

This example demonstrates how to inspect Oracle’s memory and physical structures.


Oracle Editions and Use Cases

Overview of Oracle Editions

Oracle Database offers multiple editions tailored to different needs.

  • Express Edition (XE): Free, lightweight for small applications (12 GB data limit).

  • Standard Edition 2 (SE2): Paid, for small to medium businesses.

  • Enterprise Edition: Paid, for large-scale, mission-critical applications.

  • Cloud Editions: Autonomous Database and Base Database Service on OCI, Azure, or AWS.

  • Personal Edition: For single-user development (not widely used).

  • Oracle Database Free (23ai): Free, full-featured for development and testing.

Use Cases for Each Edition

  • Express Edition: Learning, small apps, or prototypes.

  • Standard Edition 2: SMBs with moderate workloads (e.g., retail systems).

  • Enterprise Edition: Large enterprises (e.g., banking, telecom).

  • Cloud Editions: Scalable, cloud-native apps with AI and automation.

  • Oracle Database Free: Developers building proof-of-concepts or demos.

Pros, Cons, and Alternatives for Oracle Editions

Pros

  • Express Edition:

    • Free: No licensing costs for learning.

    • Lightweight: Minimal resource usage.

  • Standard Edition 2:

    • Cost-Effective: Balances features and price.

    • High Availability: Supports RAC for clustering.

  • Enterprise Edition:

    • Advanced Features: AI, partitioning, and diagnostics.

    • Scalability: Handles massive workloads.

  • Cloud Editions:

    • Automation: Autonomous Database reduces DBA tasks.

    • Global Reach: Available on OCI, Azure, AWS.

  • Oracle Database Free:

    • Full-Featured: Includes 23ai features like AI Vector Search.

    • Developer-Friendly: Free for non-production use.

Cons

  • Express Edition:

    • Limited: 12 GB data limit, no advanced features.

    • Single Instance: No clustering support.

  • Standard Edition 2:

    • Feature Gaps: Lacks Enterprise features like partitioning.

    • Cost: Licensing fees apply.

  • Enterprise Edition:

    • Expensive: High costs for licensing and support.

    • Complexity: Requires skilled administration.

  • Cloud Editions:

    • Cost: Usage-based pricing can escalate.

    • Dependency: Relies on cloud infrastructure.

  • Oracle Database Free:

    • Non-Production: Not for live environments.

    • Support: Limited compared to paid editions.

Alternatives

  • PostgreSQL: Free, open-source, enterprise-ready.

  • SQL Server: Cost-effective for Windows ecosystems.

  • MySQL: Lightweight, suitable for web apps.

  • MongoDB Atlas: Cloud-native NoSQL database.

  • Google Cloud SQL: Managed SQL for GCP.

Example: Choosing an Oracle Edition

Scenario: A startup needs a database for a customer management system.

  • Express Edition: Suitable for prototyping but limited to 12 GB.

  • Standard Edition 2: Ideal for production with moderate scale.

  • Enterprise Edition: Overkill unless advanced features are needed.

  • Cloud Edition: Best for scalability and cloud integration.

  • Decision: Choose Standard Edition 2 for cost-effectiveness and growth potential.


Oracle 21c & 23c Overview: New Features and Improvements

Oracle 21c Highlights

Released in 2021, Oracle 21c introduced developer-focused features.

  • Multitenant Architecture: Mandatory for all databases, supporting CDBs and PDBs.

  • Blockchain Tables: Immutable tables for secure data.

  • Native JSON Data Types: Enhanced JSON support for document storage.

  • In-Memory Column Store: Faster analytics with columnar data.

  • AutoML: Machine learning automation for developers.

Oracle 23c (23ai) Highlights

Oracle 23c, branded as 23ai for “Artificial Intelligence,” emphasizes AI and developer productivity.

  • AI Vector Search: Supports semantic queries for unstructured data.

  • Property Graph Queries: SQL-standard graph analytics for relational data.

  • JavaScript Stored Procedures: Run JavaScript in the database via GraalVM.

  • JSON-Relational Duality Views: Unified relational and JSON access.

  • Microservices Support: Enhanced for cloud-native apps.

Pros, Cons, and Alternatives for Oracle 21c and 23c

Pros

  • 21c:

    • Developer-Friendly: JSON, Blockchain Tables, and AutoML.

    • Multitenant: Efficient resource sharing with CDB/PDB.

    • Performance: In-Memory Column Store boosts analytics.

  • 23c:

    • AI Integration: Vector Search and AI-driven analytics.

    • Flexibility: JSON duality and graph queries.

    • Developer Productivity: JavaScript stored procedures.

Cons

  • 21c:

    • Complexity: Multitenant architecture requires expertise.

    • Resource Usage: In-Memory features demand high memory.

  • 23c:

    • Preview Status: Some features are in CTP (as of 2025).

    • Learning Curve: AI and graph features are advanced.

    • Cost: Enterprise features require paid licenses.

Alternatives

  • PostgreSQL: Supports JSON and graph extensions, open-source.

  • SQL Server 2025: AI and vector support in a simpler ecosystem.

  • MongoDB: Native JSON and document storage.

  • Neo4j: Dedicated graph database for analytics.

  • Snowflake: Cloud-native analytics with JSON support.

Example: Using AI Vector Search in Oracle 23c

Step 1: Create a Vector Table

  • In SQL Developer:

    CREATE TABLE products (
        product_id NUMBER PRIMARY KEY,
        product_name VARCHAR2(100),
        vector_data VECTOR
    );

Step 2: Insert Data with Vectors

  • Simulate vector embeddings (e.g., from an AI model):

    INSERT INTO products (product_id, product_name, vector_data)
    VALUES (1, 'Laptop', TO_VECTOR('[0.1, 0.2, 0.3]'));
    INSERT INTO products (product_id, product_name, vector_data)
    VALUES (2, 'Phone', TO_VECTOR('[0.4, 0.5, 0.6]'));

Step 3: Query with Vector Search

  • Find similar products:

    SELECT product_name
    FROM products
    WHERE VECTOR_DISTANCE(vector_data, TO_VECTOR('[0.15, 0.25, 0.35]'), EUCLIDEAN) < 0.5;
  • Output:

    product_name
    ------------
    Laptop

This example showcases Oracle 23c’s AI Vector Search for semantic queries.


Installing Oracle Database (Windows/Linux/Cloud)

Installation on Windows

  • Prerequisites: Windows 10/11, 8 GB RAM, 20 GB disk space.

  • Steps:

    1. Download Oracle Database 23c Free from oracle.com.

    2. Run the installer, select Desktop Class for simplicity.

    3. Configure CDB with a PDB (e.g., orclpdb).

    4. Set a strong SYS password (e.g., P@ssw0rd2025).

    5. Verify with sqlplus / as sysdba.

Installation on Linux

  • Prerequisites: Oracle Linux 8, 8 GB RAM, 20 GB disk space.

  • Steps:

    1. Download Oracle Database 23c RPM from oracle.com.

    2. Install dependencies:

      yum install oracle-database-preinstall-23c
    3. Run the RPM installer:

      rpm -ivh oracle-database-free-23c-1.0-1.el8.x86_64.rpm
    4. Configure the database:

      /etc/init.d/oracledb_ORCL configure
    5. Verify with sqlplus.

Cloud Installation (OCI)

  • Prerequisites: Oracle Cloud account, Free Tier or paid subscription.

  • Steps:

    1. Log in to cloud.oracle.com.

    2. Create an Autonomous Database Free instance.

    3. Configure with default settings and download credentials.

    4. Connect using SQL Developer or wallet-based authentication.

Pros, Cons, and Alternatives for Installation

Pros

  • Windows:

    • User-Friendly: GUI installer simplifies setup.

    • Familiarity: Ideal for Windows-based developers.

  • Linux:

    • Performance: Optimized for server environments.

    • Stability: Preferred for production deployments.

  • Cloud:

    • Automation: Autonomous Database reduces manual tasks.

    • Scalability: Elastic resources on OCI.

Cons

  • Windows:

    • Resource Usage: Higher overhead than Linux.

    • Support: Less common for production.

  • Linux:

    • Complexity: Requires command-line expertise.

    • Dependencies: Manual setup of prerequisites.

  • Cloud:

    • Cost: Paid tiers can be expensive.

    • Learning Curve: Cloud-specific configurations.

Alternatives

  • Docker: Use Oracle Database container images for quick setups.

  • VirtualBox: Oracle Developer Days VM for pre-configured environments.

  • AWS RDS Oracle: Managed Oracle on AWS.

  • Azure Database for Oracle: Oracle on Microsoft Azure.

Example: Installing Oracle Database 23c on Windows

Step 1: Download

  • Visit oracle.com and download Oracle Database 23c Free.

Step 2: Install

  • Run setup.exe, select Desktop Class.

  • Set database name to ORCL and password to P@ssw0rd2025.

  • Complete installation (approx. 15 minutes).

Step 3: Verify

  • Open Command Prompt:

    sqlplus / as sysdba
    SELECT name FROM v$database;
  • Output:

    NAME
    ---------
    ORCL

This example demonstrates a straightforward Oracle 23c installation on Windows.


Oracle SQL Developer & Other Tools

Oracle SQL Developer

SQL Developer is a free, graphical tool for database development and administration, supporting SQL and PL/SQL.

Features

  • Query Editor: Syntax highlighting and auto-completion.

  • Schema Browser: Visualize tables, views, and objects.

  • Connections: Manage multiple database connections.

  • Reports: Built-in and custom reporting tools.

  • Cloud Support: Connects to OCI, Azure, and AWS.

Other Tools: SQL*Plus, Oracle Enterprise Manager

  • SQL*Plus: Command-line tool for SQL and PL/SQL execution.

  • Oracle Enterprise Manager (OEM): Web-based tool for monitoring and managing databases, instances, and performance.

Pros, Cons, and Alternatives for Oracle Tools

Pros

  • SQL Developer:

    • Free: No cost for full functionality.

    • User-Friendly: Intuitive GUI for beginners.

    • Cross-Platform: Runs on Windows, Linux, macOS.

  • SQL*Plus:

    • Lightweight: Minimal resource usage.

    • Scripting: Ideal for automation and batch jobs.

  • OEM:

    • Comprehensive: Manages instances, performance, and backups.

    • Cloud Integration: Supports OCI and hybrid setups.

Cons

  • SQL Developer:

    • Performance: Slower for large datasets.

    • Memory: Higher memory usage than SQL*Plus.

  • SQL*Plus:

    • No GUI: Steep learning curve for beginners.

    • Limited Features: Lacks visual tools.

  • OEM:

    • Complexity: Requires setup and expertise.

    • Resource Usage: Heavy for small environments.

Alternatives

  • DBeaver: Open-source, multi-database GUI tool.

  • Toad for Oracle: Commercial tool with advanced features.

  • pgAdmin: For PostgreSQL users transitioning to Oracle.

  • Visual Studio Code: With Oracle extensions for lightweight querying.

Example: Querying with SQL Developer

Step 1: Install SQL Developer

  • Download from oracle.com.

  • Install and launch (no database required).

Step 2: Connect to Database

  • Create a connection:

    • Host: localhost

    • SID: orclpdb

    • User: sys, Password: P@ssw0rd2025, Role: SYSDBA.

Step 3: Create and Query a Table

  • Run:

    CREATE TABLE employees (
        emp_id NUMBER PRIMARY KEY,
        emp_name VARCHAR2(100) NOT NULL,
        salary NUMBER(10,2) NOT NULL
    );
    INSERT INTO employees (emp_id, emp_name, salary) VALUES (1, 'Alice', 50000);
    SELECT * FROM employees;
  • Output:

    EMP_ID  EMP_NAME  SALARY
    ------  --------  ------
    1       Alice     50000

This example demonstrates SQL Developer’s ease of use for database tasks.


Best Practices for Oracle Database Development

Security Best Practices

  • Use Strong Passwords: Enforce complex passwords for SYS and SYSTEM.

  • Least Privilege: Grant minimal permissions to users and roles.

  • Encryption: Enable Transparent Data Encryption (TDE) for sensitive data.

  • Auditing: Configure Unified Auditing for tracking access.

  • Network Security: Use Oracle Net Listener with SSL/TLS.

Performance Best Practices

  • SGA Tuning: Adjust buffer cache and shared pool sizes.

  • Indexing: Create indexes on frequently queried columns.

  • Partitioning: Use table partitioning for large datasets.

  • Query Optimization: Analyze execution plans with SQL Developer.

  • Caching: Leverage In-Memory Column Store for analytics.

Error Handling Best Practices

  • Exception Blocks: Use PL/SQL EXCEPTION for robust error handling.

  • Logging: Store errors in a dedicated table for auditing.

  • Validation: Check inputs to prevent SQL injection.

  • Transaction Control: Use COMMIT and ROLLBACK for data integrity.

  • Custom Errors: Raise user-defined exceptions for clarity.


Real-Life Example: Building an Inventory Management Database

Let’s apply Module 1 concepts to create an inventory management database using Oracle 23c, SQL Developer, and best practices.

Step 1: Set Up Database

  • Install Oracle Database 23c Free on Windows (as shown earlier).

  • Create a PDB named inventorypdb:

    CREATE PLUGGABLE DATABASE inventorypdb
    ADMIN USER inv_admin IDENTIFIED BY P@ssw0rd2025
    FILE_NAME_CONVERT = ('/pdbseed/', '/inventorypdb/');
    ALTER PLUGGABLE DATABASE inventorypdb OPEN;

Step 2: Create Schema

  • In SQL Developer, connect to inventorypdb as inv_admin.

  • Create tables:

    CREATE TABLE products (
        product_id NUMBER PRIMARY KEY,
        product_name VARCHAR2(100) NOT NULL,
        price NUMBER(10,2) NOT NULL,
        stock NUMBER NOT NULL,
        CONSTRAINT chk_price CHECK (price > 0),
        CONSTRAINT chk_stock CHECK (stock >= 0)
    );
    
    CREATE TABLE orders (
        order_id NUMBER PRIMARY KEY,
        product_id NUMBER NOT NULL,
        quantity NUMBER NOT NULL,
        order_date DATE DEFAULT SYSDATE,
        FOREIGN KEY (product_id) REFERENCES products(product_id),
        CONSTRAINT chk_quantity CHECK (quantity > 0)
    );
    
    CREATE TABLE error_log (
        log_id NUMBER PRIMARY KEY,
        error_message VARCHAR2(4000),
        error_time DATE DEFAULT SYSDATE
    );

Step 3: Create a PL/SQL Procedure

  • Add a procedure for order processing:

    CREATE OR REPLACE PROCEDURE add_order (
        p_product_id IN NUMBER,
        p_quantity IN NUMBER
    ) AS
        v_stock NUMBER;
    BEGIN
        -- Validate inputs
        IF p_product_id IS NULL THEN
            RAISE_APPLICATION_ERROR(-20001, 'Product ID cannot be null.');
        END IF;
        IF p_quantity <= 0 THEN
            RAISE_APPLICATION_ERROR(-20002, 'Quantity must be positive.');
        END IF;
    
        -- Check stock
        SELECT stock INTO v_stock FROM products WHERE product_id = p_product_id;
        IF v_stock < p_quantity THEN
            RAISE_APPLICATION_ERROR(-20003, 'Insufficient stock.');
        END IF;
    
        -- Process order
        INSERT INTO orders (order_id, product_id, quantity)
        VALUES (orders_seq.NEXTVAL, p_product_id, p_quantity);
        UPDATE products SET stock = stock - p_quantity WHERE product_id = p_product_id;
        COMMIT;
        DBMS_OUTPUT.PUT_LINE('Order added successfully.');
    EXCEPTION
        WHEN NO_DATA_FOUND THEN
            INSERT INTO error_log (log_id, error_message) VALUES (log_seq.NEXTVAL, 'Invalid Product ID.');
            RAISE_APPLICATION_ERROR(-20004, 'Invalid Product ID.');
        WHEN OTHERS THEN
            INSERT INTO error_log (log_id, error_message) VALUES (log_seq.NEXTVAL, SQLERRM);
            ROLLBACK;
            RAISE;
    END;
    /

Step 4: Test the Procedure

  • Insert sample data:

    INSERT INTO products (product_id, product_name, price, stock) VALUES (1, 'Laptop', 999.99, 50);
    INSERT INTO products (product_id, product_name, price, stock) VALUES (2, 'Phone', 499.99, 100);
  • Run the procedure:

    EXEC add_order(1, 10); -- Success
    EXEC add_order(1, 100); -- Fails (insufficient stock)
  • Output:

    Order added successfully.
    ORA-20003: Insufficient stock.

Step 5: Query Results

  • Check orders and errors:

    SELECT * FROM orders;
    SELECT * FROM error_log;
  • Output:

    ORDER_ID  PRODUCT_ID  QUANTITY  ORDER_DATE
    --------  ----------  --------  ----------
    1         1           10        20-AUG-25
    
    LOG_ID  ERROR_MESSAGE         ERROR_TIME
    ------  --------------------  ----------
    1       ORA-20003: Insufficient stock.  20-AUG-25

Real-Life Scenario: This inventory system demonstrates:

  • Architecture: Uses CDB/PDB, SGA/PGA for performance.

  • Editions: Leverages Oracle Database Free for development.

  • Tools: SQL Developer for schema creation and querying.

  • Features: PL/SQL for procedural logic, 23c’s error handling.

  • Best Practices: Security (constraints), performance (indexes), and error handling (logging).


Conclusion

In Module 1 of our Complete Oracle Database Course, we explored the fundamentals of Oracle Database, including its definition, architecture, editions, 21c/23c features, installation processes, and tools like SQL Developer. Through practical examples and a real-world inventory management database, you’ve learned how to set up Oracle, create schemas, and apply best practices for security, performance, and error handling. This foundation prepares you for advanced topics like PL/SQL and database administration in future modules. Stay tuned for Module 2, where we’ll dive into SQL and PL/SQL programming!


FAQs

Q1: Why choose Oracle Database over other RDBMS?

  • Oracle excels in enterprise-grade scalability, security, and multi-model support, ideal for mission-critical applications.

Q2: Which Oracle edition is best for beginners?

  • Oracle Database Free or Express Edition is free and suitable for learning.

Q3: What’s new in Oracle 23c?

  • AI Vector Search, JSON-relational duality, and JavaScript stored procedures enhance developer productivity and AI integration.

Q4: Why use SQL Developer over SQL*Plus?

  • SQL Developer offers a user-friendly GUI, while SQL*Plus is lightweight for scripting.

Q5: How does Oracle’s architecture improve performance?

  • SGA caches data, PGA isolates sessions, and background processes automate tasks like recovery and logging.

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam

Post Bottom Ad

Responsive Ads Here