Unit 1: Introduction to an Oracle Database [12 Hours]
An Oracle Database is a relational database system designed to store, organize, retrieve, and protect large amounts of data while supporting many users at the same time. This unit explains how Oracle is organized internally through its memory, process, and storage structures, how a Database Administrator (DBA) manages the system, and how users interact with Oracle through SQL*Plus. It also covers the main Structured Query Language (SQL) concepts used to define database objects, manipulate data, combine tables, and retrieve related information.
Tested Topics
- Oracle database memory structure, SGA, PGA and Oracle Instance — 4x (2025, 2023, 2021, 2021)
- Oracle database architecture: memory, process and storage structures — 2x (2025, 2021)
- DBA roles and responsibilities — 2x (2023, 2021)
- Table creation — 2x (2026, 2021)
- Primary key constraints — 2x (2026, 2021)
- Check constraints — 2x (2026, 2021)
- Table renaming — 2x (2026, 2021)
- INSERT and DELETE operations — 2x (2026, 2021)
- Foreign key constraints — 2x (2026, 2021)
- Column modification and renaming — 2x (2026, 2021)
- Indexing and index creation guidelines — 1x (2023)
- Table partitioning — 1x (2023)
- Sequence — 1x (2025)
- Synonym — 1x (2021)
1.1 Oracle Database Architecture
Definition
Oracle Database architecture is the organized arrangement of memory areas, operating-system processes, and storage files that work together to store data and process user requests.
A user does not directly open an Oracle datafile and search for a record. The request passes through Oracle's running programs and memory first. Those components locate or modify the required information and communicate with the files stored on disk.
Detailed Explanation
An Oracle database system can be understood through three major structures:
- Memory structure: temporary working memory used while Oracle is running.
- Process structure: programs that perform database work such as executing SQL, writing changed data, and recovering from failures.
- Storage structure: physical files and logical storage units in which database information is permanently organized.

Oracle Database and Oracle Instance
Two terms must be separated clearly:
- Oracle database: the collection of physical files containing permanent database information.
- Oracle instance: the memory structures and Oracle background processes that are currently running and managing the database.
The basic relationship is:
User request → Oracle instance processes the request → instance reads or changes the Oracle database files → result is returned to the user.
| Part | Main Purpose | Examples |
|---|---|---|
| Memory | Holds frequently used data, SQL information, session information, and work areas. | System Global Area, Program Global Area |
| Processes | Execute SQL and perform database maintenance. | Server process, DBWn, LGWR, CKPT, SMON |
| Storage | Permanently stores data and database control information. | Datafiles, control files, online redo log files |
How a Request Moves Through Oracle
Consider the following query:
SELECT name, balance
FROM bank
WHERE acc_no = 101;The general flow is:
- The client sends the SQL statement to Oracle.
- A server process receives and processes the request.
- Oracle examines the Shared Pool to determine whether the SQL statement has already been parsed.
- Required data blocks are searched for in the Database Buffer Cache.
- If the blocks are not already in memory, Oracle reads them from the datafiles.
- The server process obtains the required row and prepares the result.
- The result is returned to the client application.
For a modification such as an UPDATE, additional structures participate. The changed block remains in the buffer cache for a period, redo information is generated, Log Writer (LGWR) writes redo to the online redo log, and Database Writer (DBWn) eventually writes changed blocks to datafiles.
Let's Clarify
A busy bank branch has customers, service counters, working desks, and permanent record rooms. Customers give requests to staff rather than entering the record room themselves. Staff use information already available on their desks when possible and retrieve records from storage when necessary.
Oracle follows a similar arrangement. Users send requests to processes, memory provides fast working space, and database files provide permanent storage.
Summary
- Oracle architecture combines memory, processes, and storage into one database system.
- The database contains persistent files, while an instance contains running memory structures and processes.
- Server and background processes use memory to reduce slow disk access.
- Datafiles provide permanent storage, while memory holds temporary working copies of information.
- Oracle coordinates these structures to support concurrent, secure, and recoverable database operations.
Test Yourself
- Differentiate between an Oracle database and an Oracle instance.
- Explain oracle database architecture in detail including memory, process, and storage structure of oracle database. (2025)
- What do you mean by database management system? Mention the clear architecture of oracle database management system including different files, process and memory structure. (2021)
Hints:
- Database = permanent physical files. Instance = System Global Area plus Oracle background processes that access and manage those files.
- Organize the answer under memory structure, process structure, and storage structure, then explain how they interact during SQL processing.
- Define a Database Management System as software for managing databases, then explain Oracle memory, user/server/background processes, and physical database files.
1.2 Oracle Instance and Memory Structure
Definition
An Oracle instance is the combination of Oracle's shared memory structures and background processes that are started to access and manage an Oracle database.
The database files may remain on disk even when Oracle is shut down. When Oracle starts, it allocates memory and starts background processes. Together, these running components form the instance.
Detailed Explanation
The two main Oracle memory structures are:
- System Global Area (SGA): shared memory used by the instance and accessible to Oracle processes.
- Program Global Area (PGA): private memory associated with an individual server or background process.

System Global Area (SGA)
The System Global Area (SGA) is a shared memory region allocated when an Oracle instance starts. Multiple server and background processes use information stored in it.
The major SGA components are:
Database Buffer Cache
The Database Buffer Cache stores copies of data blocks read from database datafiles.
When a user requests a row, Oracle first checks whether the required block is already in the buffer cache. If it exists there, Oracle can use the memory copy rather than perform another physical disk read.
When a block is modified, the changed copy in memory becomes a dirty buffer. DBWn later writes dirty buffers back to datafiles.
Shared Pool
The Shared Pool stores information that can be reused by multiple sessions. Two major areas within it are:
- Library Cache: stores parsed SQL statements, execution information, and executable forms of SQL and Procedural Language/Structured Query Language (PL/SQL) code.
- Data Dictionary Cache: stores frequently accessed metadata about database objects, users, privileges, tables, columns, and other database definitions.
If equivalent SQL already exists in the library cache, Oracle may reuse the existing parsed representation. This is called a soft parse. When Oracle must perform full parsing and optimization, the operation is called a hard parse.
Redo Log Buffer
The Redo Log Buffer temporarily holds information describing changes made to the database.
Change occurs → redo information enters the Redo Log Buffer → LGWR writes redo records to online redo log files.
Redo information is essential for database recovery because it records changes that can be reapplied after a failure.
Large Pool
The Large Pool is an optional memory area used for large memory allocations that should not compete heavily with the Shared Pool. It can support operations such as shared server session memory, backup and recovery operations, and some parallel execution activities.
Java Pool
The Java Pool provides memory for Java code and Java Virtual Machine-related activity inside the Oracle database when database-side Java is used.
Streams Pool
The Streams Pool is a memory area used by certain Oracle data movement, replication, and related features that require shared memory.
Program Global Area (PGA)
The Program Global Area (PGA) is a private memory region belonging to an individual Oracle process. Unlike the SGA, it is not generally shared among processes.
A PGA can contain:
- Private SQL area: information related to the SQL statement being handled by that process.
- Session memory: information associated with the user's session.
- SQL work areas: temporary memory used for operations such as sorting, hashing, and joining data.
For example, an ORDER BY operation may use a PGA work area to sort rows. If the operation is larger than the available memory, Oracle may use temporary storage on disk.
SGA and PGA Comparison
| Basis | System Global Area (SGA) | Program Global Area (PGA) |
|---|---|---|
| Sharing | Shared among Oracle processes. | Private to an individual process. |
| Creation | Allocated when the Oracle instance starts. | Allocated for a server or background process as required. |
| Main purpose | Caches shared database information and coordinates instance activity. | Stores process-specific session and work information. |
| Examples | Buffer Cache, Shared Pool, Redo Log Buffer. | Sort areas, hash areas, private SQL area. |
| Visibility | Used by multiple participating Oracle processes. | Associated with one process. |
Instance Startup Relationship
At a high level, Oracle startup establishes the instance and then gives that instance access to the database:
Allocate SGA → start background processes → locate database control information → open the database files → database becomes available to users.
Let's Clarify
A group project may have one shared whiteboard and several students' private notebooks. Everyone can use information written on the whiteboard, while each student keeps personal calculations in their own notebook.
The SGA is the shared whiteboard. The PGA is each process's private notebook.
Common Mistake
The SGA is not the whole Oracle instance. An Oracle instance consists of the SGA together with Oracle background processes. The PGA is process-specific memory and is not normally included in the basic definition of an instance as SGA plus background processes.
Summary
- An Oracle instance consists primarily of the SGA and Oracle background processes.
- The SGA is shared memory, while the PGA is private process memory.
- The Database Buffer Cache keeps copies of database blocks to reduce disk access.
- The Shared Pool caches SQL and metadata, while the Redo Log Buffer holds change information.
- PGA work areas support process-specific operations such as sorting, hashing, and joins.
Test Yourself
- Explain the relationship between the Oracle instance, SGA, and background processes.
- Describe the memory structure of oracle database. Explain how PGA differs from SGA. Also explain about oracle instance and different components of SGA. (2023)
- What do you mean by oracle Instance? Explain about the different data structures used in SGA. (2021)
Hints:
- Instance = SGA + background processes. The SGA provides shared working memory while processes perform database operations.
- Explain SGA and PGA first, compare them, define the instance, then describe Buffer Cache, Shared Pool, Redo Log Buffer, Large Pool, Java Pool, and Streams Pool.
- Define Oracle instance as shared memory plus background processes. Describe SGA components and their purposes.
1.3 Oracle Process Structure
Definition
Oracle process structure consists of user processes, server processes, and background processes that cooperate to execute SQL statements and maintain the database.
Memory stores information, but processes perform the actual work. They receive requests, search memory, access database files, write changes, maintain checkpoints, and recover database information when necessary.
Detailed Explanation

User Process
A user process is created when a database user runs an application or client program that communicates with Oracle.
Examples include:
- SQL*Plus
- A Java application
- A web application connected to Oracle
- A database administration tool
The user process sends SQL requests but normally does not directly manipulate Oracle database files.
Server Process
A server process performs work on behalf of a user's session. Its responsibilities can include:
- Parsing SQL statements.
- Checking permissions.
- Creating execution plans.
- Reading blocks from datafiles into memory.
- Changing data in memory.
- Returning query results to the client.
Background Processes
Background processes perform database-wide maintenance and coordination. Important Oracle background processes include the following.
| Process | Full Name | Main Function |
|---|---|---|
| DBWn | Database Writer | Writes modified database blocks from the buffer cache to datafiles. |
| LGWR | Log Writer | Writes redo entries from the Redo Log Buffer to online redo log files. |
| CKPT | Checkpoint Process | Coordinates checkpoints and updates checkpoint information in control files and datafile headers. |
| SMON | System Monitor | Performs instance recovery and certain system-level cleanup operations. |
| PMON | Process Monitor | Detects failed user or server processes and assists with releasing resources associated with failed sessions. |
| ARCn | Archiver | Copies filled online redo log files to archived redo logs when the database operates in ARCHIVELOG mode. |
| MMON | Manageability Monitor | Performs database manageability and monitoring-related tasks. |
| MMAN | Memory Manager | Coordinates automatic management of memory components when automatic memory management features are used. |
How Processes Cooperate During an UPDATE
Suppose the following statement is executed:
UPDATE bank
SET balance = balance + 1000
WHERE acc_no = 101;The general sequence is:
- The user process submits the UPDATE statement.
- The server process parses and executes the statement.
- The relevant data block is located in the Database Buffer Cache or read from a datafile.
- The server process modifies the block in memory.
- Redo describing the change is placed in the Redo Log Buffer.
- LGWR writes redo information to an online redo log at the required time.
- DBWn later writes the modified block from memory to the corresponding datafile.
The separation between redo writing and datafile writing helps Oracle provide transaction durability and efficient disk operations.
Summary
- User processes originate database requests.
- Server processes parse SQL, access data, perform operations, and return results.
- DBWn writes changed database blocks to datafiles.
- LGWR protects change information by writing redo to online redo logs.
- Processes such as CKPT, SMON, PMON, ARCn, MMON, and MMAN perform maintenance and recovery-related work.
Test Yourself
- Differentiate user processes, server processes, and Oracle background processes.
- Explain the functions of DBWn, LGWR, CKPT, SMON, and PMON.
- Describe what happens at the process level when an UPDATE statement changes a row.
Hints:
- User process sends requests; server process handles requests; background processes maintain the whole instance and database.
- DBWn writes data blocks, LGWR writes redo, CKPT coordinates checkpoints, SMON performs instance recovery, and PMON handles failed-process cleanup.
- User request → server process → modify block in buffer cache → generate redo → LGWR writes redo → DBWn eventually writes changed block.
1.4 Oracle Storage Structure
Definition
Oracle storage structure describes how database information is organized both physically in operating-system files and logically inside the Oracle database.
Physical storage answers, “Which files are stored on disk?” Logical storage answers, “How does Oracle organize the information inside those files?”
Detailed Explanation
Physical Database Files
The three principal physical file types of an Oracle database are:
Datafiles
Datafiles contain the actual stored database data, including table and index blocks. Every tablespace is associated with one or more datafiles.
Control Files
Control files contain critical structural information about the database, including information about database files, redo logs, checkpoints, and database state.
Oracle needs valid control-file information to identify and manage the database structure.
Online Redo Log Files
Online redo log files store redo records describing changes made to database data. They are used during recovery to reconstruct changes that had occurred before a failure.
Supporting Files
Oracle also uses supporting files such as:
- Server Parameter File (SPFILE) or text initialization parameter file for instance configuration.
- Password file for certain privileged administrative authentication.
- Archived redo log files when redo logs are archived for recovery purposes.
- Backup files maintained as part of a backup and recovery strategy.
Logical Storage Structure
Oracle's logical storage hierarchy is commonly represented as:
Database → Tablespaces → Segments → Extents → Data Blocks
Tablespace
A tablespace is a logical storage container in an Oracle database. It groups related logical objects and is physically represented by one or more datafiles.
Segment
A segment is storage allocated for a particular database object or storage purpose. Examples include table segments and index segments.
Extent
An extent is a set of contiguous database blocks allocated to a segment. As an object requires more storage, Oracle can allocate additional extents.
Data Block
An Oracle data block is the smallest logical unit of database storage used by Oracle for reading and writing database information.
| Logical Unit | Meaning | Relationship |
|---|---|---|
| Tablespace | Logical container for database storage. | Contains segments and maps to datafiles. |
| Segment | Space allocated to an object or storage structure. | Contains one or more extents. |
| Extent | Group of contiguous Oracle blocks. | Allocated to a segment. |
| Data Block | Smallest logical storage unit handled by Oracle. | Blocks combine to form extents. |
Connection Between Physical and Logical Storage
A tablespace is logical, but its information must ultimately exist in physical datafiles.
Table row → stored in Oracle data block → block belongs to extent → extent belongs to table segment → segment belongs to tablespace → tablespace uses one or more datafiles.
Common Mistake
A tablespace and a datafile are not the same object. A tablespace is a logical Oracle storage unit. A datafile is a physical file on disk associated with a tablespace.
Summary
- Oracle storage is divided into physical and logical structures.
- The principal physical database files are datafiles, control files, and online redo log files.
- Datafiles store database data, control files describe database structure, and redo logs record changes.
- The logical hierarchy is tablespace → segment → extent → data block.
- Logical storage structures ultimately map to physical datafiles.
Test Yourself
- Explain the physical storage structure of an Oracle database.
- Describe the logical storage hierarchy from tablespace to data block.
- Differentiate a tablespace and a datafile.
Hints:
- Cover datafiles, control files, and online redo logs, then mention supporting parameter, password, archive, and backup files.
- Tablespace contains segments; segments consist of extents; extents consist of data blocks.
- Tablespace = logical storage container. Datafile = physical operating-system file used by a tablespace.
1.5 Database Administration and DBA Roles
Definition
Database administration is the management, maintenance, protection, monitoring, and operation of a database system so that data remains available, secure, correct, and recoverable.
A Database Administrator (DBA) is the person responsible for performing or coordinating these database management activities.
Detailed Explanation
A database serves applications continuously and contains valuable organizational information. The DBA manages both technical resources and operational policies needed to keep that database reliable.
Major Roles and Responsibilities of a DBA
| Responsibility | Description |
|---|---|
| Installation and configuration | Installs Oracle software and configures the database environment and required parameters. |
| Database creation | Creates databases and configures logical and physical storage structures. |
| User administration | Creates users, manages authentication, and controls user accounts. |
| Security management | Grants appropriate privileges and protects sensitive database objects. |
| Storage management | Monitors tablespaces and datafiles and provides storage as data grows. |
| Backup and recovery | Creates backups and establishes procedures for recovering data after failures. |
| Performance monitoring | Investigates slow SQL, memory pressure, disk activity, and other performance problems. |
| Availability management | Works to keep database services accessible and reduces unnecessary downtime. |
| Integrity management | Supports rules and controls that keep stored data valid and consistent. |
| Monitoring and troubleshooting | Monitors database health, logs, errors, sessions, space usage, and failed operations. |
| Upgrade and maintenance | Plans software patches, database upgrades, and maintenance operations. |
| Documentation | Maintains records of configurations, backup procedures, security rules, changes, and recovery processes. |
Common DBA Specializations
In a small organization, one person may perform most DBA responsibilities. Larger organizations can divide them into specialized roles.
- System DBA: focuses on installation, configuration, availability, storage, and infrastructure.
- Application DBA: supports databases used by particular applications and works closely with developers.
- Security DBA: concentrates on users, privileges, auditing, and database protection.
- Performance DBA: investigates SQL and database performance problems.
- Backup and recovery DBA: concentrates on backup, restore, disaster recovery, and data protection.
Example of DBA Work
Suppose a university database is running out of storage and student result queries have become slow. The DBA may:
Check tablespace usage → identify storage shortage → add or resize storage → examine expensive SQL → inspect indexes and execution plans → correct the cause → continue monitoring.
Summary
- Database administration keeps a database secure, available, efficient, and recoverable.
- A DBA manages installation, configuration, users, security, storage, and database availability.
- Backup and recovery protect the organization from data loss and system failure.
- Performance monitoring identifies inefficient SQL and resource problems.
- Large organizations may divide administration into system, application, security, performance, and recovery roles.
Test Yourself
- How do the security and recovery responsibilities of a DBA differ?
- What is database administration? Explain the roles and responsibilities of DBA. (2023)
- Explain the term database administrator (DBA) and describe the different roles of DBA. (2021)
Hints:
- Security controls who can access data; recovery ensures data can be restored after damage, failure, or loss.
- Define database administration, then explain installation, configuration, users, security, storage, backup, recovery, performance, availability, and maintenance.
- Define DBA as the person responsible for database operation and management, then describe administrative and specialized DBA roles.
1.6 SQL*Plus
Definition
SQL*Plus is an Oracle command-line tool used to enter SQL statements, execute Procedural Language/Structured Query Language programs, run scripts, format query output, and perform database-related tasks.
It provides a text-based environment where a user connects to an Oracle database, enters commands, receives results, and can save repeated commands inside script files.
Detailed Explanation
SQL*Plus accepts two broad kinds of commands:
- SQL and PL/SQL statements: commands executed by the Oracle database.
- SQL*Plus commands: commands interpreted by SQL*Plus itself to control the session, variables, display, scripts, and output.
Connecting to Oracle
sqlplus username/password@service_nameAfter a connection is established, SQL statements can be entered at the SQL prompt.
SELECT * FROM employees;Common SQL*Plus Commands
| Command | Purpose |
|---|---|
| DESCRIBE or DESC | Displays the structure of a table, view, or other supported object. |
| SET | Changes SQL*Plus environment settings. |
| SPOOL | Sends displayed output to a file. |
| @ | Runs commands stored in a script file. |
| / | Executes the SQL or PL/SQL statement currently held in the SQL buffer. |
| HOST | Invokes an operating-system command where supported. |
| EXIT | Ends the SQL*Plus session. |
SQL Statement and SQL*Plus Command Difference
| SQL Statement | SQL*Plus Command |
|---|---|
| Executed by the Oracle database engine. | Processed by the SQL*Plus client. |
| Works with database data or database objects. | Controls the SQL*Plus environment or script execution. |
| Examples: SELECT, INSERT, CREATE TABLE. | Examples: DESCRIBE, SET, SPOOL, ACCEPT. |
Running a Script
If a file named report.sql contains SQL statements, it can be executed with:
@report.sqlScripts become especially useful when substitution variables and ACCEPT commands are added, because the same script can process different user-supplied values.
Summary
- SQL*Plus is Oracle's text-based environment for executing SQL, PL/SQL, and SQL*Plus commands.
- SQL statements are executed by Oracle, while SQL*Plus commands control the client environment.
- DESCRIBE displays object definitions, SET controls settings, and SPOOL captures output.
- The @ command executes saved SQL*Plus scripts.
Test Yourself
- What is SQL*Plus, and how is it different from the Oracle database itself?
- Differentiate SQL commands and SQL*Plus commands with examples.
Hints:
- SQL*Plus is a client tool used to communicate with Oracle. The database is the system that stores and processes the data.
- SQL commands operate on database data or objects; SQL*Plus commands control the client session, formatting, variables, and scripts.
1.7 Accepting Values at Runtime
Definition
Accepting values at runtime means allowing a SQL*Plus script to receive input from the user while the script is executing instead of fixing every value inside the SQL statement beforehand.
One script can therefore be reused for different account numbers, department numbers, names, dates, or other input values.
Detailed Explanation
SQL*Plus supports runtime input mainly through substitution variables and the ACCEPT command.
Single Ampersand Substitution Variable
A variable beginning with a single ampersand prompts for a value when the variable has not already been defined.
SELECT *
FROM employees
WHERE department_id = &dept_no;If the user enters:
20SQL*Plus substitutes the supplied value into the statement before sending it to the database.
Character Values
Character substitution values usually need SQL quotation marks in the statement:
SELECT *
FROM employees
WHERE job_id = '&job';If the user enters IT_PROG, the resulting condition becomes:
WHERE job_id = 'IT_PROG'Double Ampersand
A double ampersand can define a substitution variable so that the supplied value can be reused in later references during the SQL*Plus session.
SELECT *
FROM employees
WHERE department_id = &&dept_no;
SELECT COUNT(*)
FROM employees
WHERE department_id = &dept_no;The first reference requests the value and defines it. The second reference can reuse the stored value.
ACCEPT Command
The SQL*Plus ACCEPT command gives more control over prompting and input.
ACCEPT dept_no NUMBER PROMPT 'Enter department number: '
SELECT employee_id, first_name, salary
FROM employees
WHERE department_id = &dept_no;The command can specify the expected input type and a meaningful prompt.
PROMPT Command
The PROMPT command displays a message in SQL*Plus.
PROMPT Employee Search ReportUNDEFINE Command
UNDEFINE removes a substitution variable so that a later reference can request a new value.
UNDEFINE dept_noRuntime Input Flow
Script encounters variable → SQL*Plus requests input → user supplies value → SQL*Plus substitutes value → completed SQL statement is sent to Oracle → Oracle returns the result.
Common Mistake
An ampersand variable is processed by SQL*Plus before the SQL statement reaches Oracle. It is a client-side substitution mechanism, not a database column or PL/SQL variable.
Summary
- Runtime values make SQL*Plus scripts reusable for different input data.
- &variable requests substitution when the variable is undefined.
- &&variable can define a value for later reuse in the session.
- ACCEPT provides controlled input prompts, while PROMPT displays messages.
- UNDEFINE removes a substitution variable.
Test Yourself
- How does SQL*Plus accept a value at runtime using a substitution variable?
- Differentiate &variable and &&variable in SQL*Plus.
- Write a SQL*Plus script that asks for a department number and displays employees from that department.
Hints:
- Place &name in the SQL statement; SQL*Plus prompts for the value and substitutes it before execution.
- Single ampersand performs substitution; double ampersand can define and retain the supplied value for reuse.
- Use ACCEPT dept_no NUMBER PROMPT followed by a SELECT containing department_id = &dept_no.
1.8 Overview of SQL Commands
Definition
Structured Query Language (SQL) is the standard language used with relational databases to define database objects, manipulate stored rows, and retrieve information.
In this unit, SQL is used for two broad purposes: building database structures and working with the data stored inside those structures.
Detailed Explanation
The syllabus focuses on Data Definition Language (DDL), Data Manipulation Language (DML), joins, and subqueries.
| Category | Purpose | Common Examples |
|---|---|---|
| DDL | Creates, changes, or removes database structures. | CREATE, ALTER, DROP, TRUNCATE, RENAME |
| DML | Adds, changes, or removes rows of data. | INSERT, UPDATE, DELETE, MERGE |
| Querying | Retrieves required information. | SELECT |
| Join | Combines related rows from multiple table sources. | INNER JOIN, LEFT JOIN, SELF JOIN |
| Subquery | Uses the result of one query inside another SQL statement. | IN, EXISTS, scalar and correlated subqueries |
Data Definition Language
DDL works with database object definitions. Major object types covered in this unit include:
- Tables
- Constraints
- Indexes
- Views
- Synonyms
- Sequences
- Partitioned tables
- Materialized views
Common DDL Statements
| Statement | Purpose |
|---|---|
| CREATE | Creates a new database object. |
| ALTER | Changes an existing object's definition. |
| DROP | Removes an object definition. |
| TRUNCATE | Removes all rows from a table while retaining the table structure. |
| RENAME | Changes the name of an object where supported. |
DDL and DML Difference
| Basis | DDL | DML |
|---|---|---|
| Target | Database structure. | Rows stored in database objects. |
| Examples | CREATE, ALTER, DROP. | INSERT, UPDATE, DELETE. |
| Example task | Create an EMPLOYEE table. | Insert an employee into EMPLOYEE. |
| Main effect | Changes schema definitions. | Changes table data. |
Summary
- SQL is used to define database objects and work with relational data.
- DDL changes database structures such as tables and indexes.
- DML adds, modifies, and removes rows.
- SELECT retrieves data, while joins combine table sources and subqueries nest one query inside another.
Test Yourself
- Differentiate DDL and DML with suitable examples.
- Classify CREATE TABLE, INSERT, ALTER TABLE, DELETE, and DROP TABLE as DDL or DML.
Hints:
- DDL works on structure; DML works on stored rows. CREATE is DDL, while INSERT is DML.
- CREATE, ALTER, DROP = DDL. INSERT and DELETE = DML.
1.9 Tables and Constraints
Definition
A table is a relational database object that stores data in rows and columns. A constraint is a rule applied to table data to prevent invalid or inconsistent values from being stored.
The table provides the structure, while constraints protect the quality of the information placed inside that structure.

Detailed Explanation
Creating a Table
The general Oracle syntax is:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype
);Example:
CREATE TABLE student (
student_id NUMBER,
name VARCHAR2(50),
address VARCHAR2(100),
dob DATE
);Oracle commonly uses VARCHAR2 for variable-length character data, NUMBER for numeric data, and DATE for date and time information.
Types of Constraints
| Constraint | Purpose | Example |
|---|---|---|
| NOT NULL | Requires a column to contain a value. | name VARCHAR2(50) NOT NULL |
| UNIQUE | Prevents duplicate values in the constrained column or column combination. | email VARCHAR2(100) UNIQUE |
| PRIMARY KEY | Uniquely identifies each row and does not allow null key values. | PRIMARY KEY (student_id) |
| FOREIGN KEY | Links a child table to a key in another or the same table and enforces referential integrity. | FOREIGN KEY (department_id) REFERENCES department(department_id) |
| CHECK | Requires values to satisfy a stated condition. | CHECK (salary > 10000) |
Primary Key
A primary key identifies each row uniquely. A table can have only one primary-key constraint, although that key can contain more than one column.
ALTER TABLE student
ADD CONSTRAINT pk_student
PRIMARY KEY (student_id);A primary-key value cannot be NULL, and duplicate primary-key values are not permitted.
Foreign Key
A foreign key creates a relationship between tables. Values in the child foreign-key column normally reference existing values in a primary key or unique key of the parent table.
ALTER TABLE employee
ADD department_id NUMBER;
ALTER TABLE employee
ADD CONSTRAINT fk_employee_department
FOREIGN KEY (department_id)
REFERENCES department(department_id);The referenced department(department_id) column must satisfy the requirements for a referenced key, normally through a PRIMARY KEY or UNIQUE constraint.
Check Constraint
A CHECK constraint restricts values according to a condition.
ALTER TABLE employee
ADD CONSTRAINT chk_employee_salary
CHECK (salary > 10000);Oracle rejects a new or modified row when the CHECK condition is violated.
Adding a Column
ALTER TABLE employee
ADD email VARCHAR2(100);Modifying a Column
The size or selected properties of an existing column can be changed with ALTER TABLE.
ALTER TABLE employee
MODIFY (name VARCHAR2(100));Renaming a Column
ALTER TABLE employee
RENAME COLUMN name TO ename;Renaming a Table
ALTER TABLE emp
RENAME TO employee;Worked Example: Bank Table
The following sequence demonstrates table creation, constraints, table renaming, row insertion and deletion, a foreign key, column modification, and column renaming.
Column names such as Acc-no and ph-no contain hyphens, which would require quoted identifiers in Oracle. The example uses conventional identifiers acc_no and ph_no to avoid quoted-name complications.
Step 1: Create the Table
CREATE TABLE blank (
acc_no NUMBER,
name VARCHAR2(50),
address VARCHAR2(100),
ph_no VARCHAR2(20),
balance NUMBER(12,2)
);Step 2: Add Primary Key
ALTER TABLE blank
ADD CONSTRAINT pk_blank
PRIMARY KEY (acc_no);Step 3: Add Check Constraint
ALTER TABLE blank
ADD CONSTRAINT chk_blank_balance
CHECK (balance > 300);Step 4: Rename the Table
ALTER TABLE blank
RENAME TO bank;Step 5: Insert Rows
INSERT INTO bank
VALUES (101, 'Asha', 'Kathmandu', '9800000001', 5000);
INSERT INTO bank
VALUES (102, 'Bikash', 'Pokhara', '9800000002', 8500);Step 6: Delete a Row
DELETE FROM bank
WHERE acc_no = 102;Step 7: Add loan_id and Foreign Key
ALTER TABLE bank
ADD loan_id NUMBER;
ALTER TABLE bank
ADD CONSTRAINT fk_bank_loan
FOREIGN KEY (loan_id)
REFERENCES loan(loan_id);This assumes that the loan table already exists and loan_id is an appropriate referenced key.
Step 8: Increase Name Length
ALTER TABLE bank
MODIFY (name VARCHAR2(100));Step 9: Rename Name Column
ALTER TABLE bank
RENAME COLUMN name TO cname;Worked Example: Employee Table
CREATE TABLE emp (
emp_id NUMBER,
name VARCHAR2(50),
address VARCHAR2(100),
dob DATE,
salary NUMBER(10,2)
);
ALTER TABLE emp
ADD CONSTRAINT pk_emp PRIMARY KEY (emp_id);
ALTER TABLE emp
ADD CONSTRAINT chk_emp_salary
CHECK (salary > 10000);
ALTER TABLE emp
RENAME TO employee;
INSERT INTO employee
VALUES (1, 'Ram', 'Kathmandu', DATE '2000-05-20', 25000);
INSERT INTO employee
VALUES (2, 'Sita', 'Bhaktapur', DATE '2001-08-10', 30000);
DELETE FROM employee
WHERE emp_id = 2;
ALTER TABLE employee
ADD department_id NUMBER;
ALTER TABLE employee
ADD CONSTRAINT fk_emp_department
FOREIGN KEY (department_id)
REFERENCES department(department_id);
ALTER TABLE employee
MODIFY (name VARCHAR2(100));
ALTER TABLE employee
RENAME COLUMN name TO ename;Common Mistake
A primary key identifies rows inside its own table. A foreign key stores values that refer to a key in a parent table. They serve different purposes even when both columns contain the same type of identifier.
Summary
- A table stores related data in rows and columns.
- Constraints enforce rules such as uniqueness, required values, valid ranges, and relationships.
- A primary key uniquely identifies rows, while a foreign key enforces referential relationships.
- ALTER TABLE can add constraints and columns, modify column definitions, and rename columns or tables.
- CHECK constraints prevent data that violates a specified condition from being accepted.
Test Yourself
- Differentiate primary key, foreign key, and check constraints with examples.
- Write SQL commands for following:
i. Create the table named blank having fields (Acc-no, name, address, ph-no, Balance)
ii. Add primary key in above table
iii. Add check constraints in the balance field, value of balance > 300.
iv. Rename the table blank to Bank.
v. Insert some rows and delete one of the record from the table Bank.
viii. Add loan_id field as foreign key referencing to the loan.
ix. Modify the name field to increase the character length.
x. Rename the name field to cname. (2026) - Write SQL commands for following
i. Create the table named emp having fields (emp-id, name, address DOB, Salary)
ii. Add primary key in above table
iii. Add check constraints in the salary fields, value of salary> 10000
iv. Rename the table emp to employee
v. V Insert some rows and delete one of the record from the table employee
viii.Add department_id field as foreign key referencing the table department.
ix. Modify the name field to increase the character length
x. Rename the name field to ename. (2021)
Hints:
- Primary key = unique row identity; foreign key = relationship to parent key; CHECK = Boolean condition that accepted rows must satisfy.
- Use CREATE TABLE → ALTER TABLE ADD PRIMARY KEY → ADD CHECK → RENAME → INSERT/DELETE → ADD loan_id → ADD FOREIGN KEY → MODIFY name → RENAME COLUMN.
- Use the same DDL sequence with EMP, salary > 10000, DEPARTMENT_ID referencing DEPARTMENT, and finally rename NAME to ENAME.
1.10 Indexes
Definition
An index is a database structure that provides a faster access path to rows by storing selected column values together with information that allows Oracle to locate the corresponding table rows efficiently.
Without a useful index, Oracle may need to examine many table rows to find a small result. An appropriate index can narrow the search much earlier.
Detailed Explanation
Indexes are especially useful when a large table is frequently searched through particular columns.
For example:
SELECT *
FROM employee
WHERE employee_id = 5001;If employee_id has a suitable index, Oracle may use that index to locate the required row rather than scanning every employee row.
Creating an Index
CREATE INDEX idx_employee_name
ON employee(ename);Composite Index
An index can contain more than one column:
CREATE INDEX idx_emp_dept_salary
ON employee(department_id, salary);The order of columns in a composite index affects how the index can support different predicates.
Major Oracle Index Types
B-tree Index
A B-tree index is Oracle's common general-purpose index structure. It is suitable for columns with many distinct values and for equality or range searches.
Bitmap Index
A bitmap index represents indexed values through bitmaps. It can be effective for low-cardinality columns in read-heavy analytical environments, such as columns containing a small number of status categories.
Bitmap indexes are generally unsuitable for tables undergoing heavy concurrent row-by-row modifications because DML can cause greater locking and maintenance effects.
Function-Based Index
A function-based index stores the result of an expression or function.
CREATE INDEX idx_emp_upper_name
ON employee(UPPER(ename));This can support a query such as:
SELECT *
FROM employee
WHERE UPPER(ename) = 'RAM';Index Types Comparison
| Index Type | Best General Use | Main Characteristic |
|---|---|---|
| B-tree | Typical transactional tables and selective searches. | Efficient for many equality and range conditions. |
| Bitmap | Low-cardinality analytical columns with limited concurrent DML. | Represents values using bitmaps. |
| Function-based | Queries repeatedly using the same expression. | Indexes calculated expression values. |
Why Indexing Is Important
- Faster searching: can reduce the number of table blocks Oracle must examine.
- Improved joins: indexes on useful join columns can make table matching more efficient.
- Efficient sorting and access paths: some queries can benefit from index ordering.
- Constraint support: Oracle can use indexes to enforce PRIMARY KEY and UNIQUE constraints.
Guidelines for Creating Indexes
- Index columns frequently used in selective WHERE conditions. An index is most helpful when a condition normally returns a relatively small portion of a large table.
- Consider columns used frequently in joins. Foreign-key and relationship columns are common index candidates depending on workload.
- Avoid unnecessary indexes on very small tables. A full table scan can be cheaper when the table contains little data.
- Avoid creating many indexes on heavily modified tables. INSERT, UPDATE, and DELETE operations must also maintain affected indexes.
- Choose index type according to data and workload. B-tree indexes suit many transactional searches, while bitmap indexes fit selected analytical workloads.
- Consider column selectivity. A column with many distinct values is often a stronger B-tree index candidate than one having very few values.
- Consider expressions used by queries. If queries consistently use a function such as UPPER(column), a matching function-based index may help.
- Do not duplicate an index without a reason. Existing primary-key, unique, or composite indexes may already provide the required access path.
Cost of Indexes
An index is not free. It consumes storage and must be maintained when indexed data changes.
More indexes → potentially faster selected reads → more index storage and additional DML maintenance.
Common Mistake
Creating an index does not guarantee that Oracle will use it. The optimizer compares available access paths and may choose a full table scan when that path is estimated to be more efficient.
Summary
- An index provides an alternative access path that can reduce row-search work.
- B-tree indexes are common for selective transactional searches.
- Bitmap indexes suit selected low-cardinality analytical workloads, while function-based indexes support indexed expressions.
- Good index candidates commonly appear in selective search and join conditions.
- Indexes consume storage and create additional work during data modification.
Test Yourself
- Why can excessive indexing reduce DML performance?
- What is indexing? Why it is important in database? Explain the different guidelines to create index in database. (2023)
Hints:
- Every relevant INSERT, UPDATE, or DELETE may require Oracle to modify table data plus associated index entries.
- Define index, explain faster access and join support, then discuss selectivity, table size, query conditions, DML frequency, existing indexes, and index type.
1.11 Views
Definition
A view is a named SQL query stored in the database and presented to users like a virtual table.
A view can show selected rows or columns from one or more base tables without requiring users to write the full underlying query each time.
Detailed Explanation
A normal Oracle view primarily stores its query definition rather than storing a separate permanent copy of all query result rows.
Creating a View
CREATE VIEW emp_public AS
SELECT employee_id, ename, department_id
FROM employee;The view can then be queried like a table:
SELECT *
FROM emp_public;Why Views Are Used
- Simplification: hides complicated joins and calculations behind a reusable object.
- Controlled exposure: presents selected columns rather than exposing every table column.
- Logical independence: provides users with a stable logical representation of data.
- Reusable queries: a commonly used query receives a database object name.
Simple and Complex Views
| Feature | Simple View | Complex View |
|---|---|---|
| Base tables | Usually based on one table. | Can involve multiple tables. |
| Grouping/functions | Usually does not contain grouping or aggregate calculations. | Can contain joins, grouping, and calculations. |
| DML through view | May be updatable when Oracle's requirements are satisfied. | Often restricted or non-updatable depending on definition. |
WITH CHECK OPTION
WITH CHECK OPTION can prevent DML through a view from producing rows that no longer satisfy the view's defining condition.
CREATE VIEW high_salary_emp AS
SELECT employee_id, ename, salary
FROM employee
WHERE salary > 50000
WITH CHECK OPTION;WITH READ ONLY
A view can be explicitly made read-only:
CREATE VIEW emp_readonly AS
SELECT employee_id, ename, salary
FROM employee
WITH READ ONLY;Summary
- A view is a stored query that presents data like a virtual table.
- Views can hide complexity and restrict the columns or rows presented to users.
- Simple views may be updatable when Oracle's rules permit it.
- Complex views frequently contain joins, grouping, or calculations.
- WITH CHECK OPTION and WITH READ ONLY can restrict data modification through a view.
Test Yourself
- What is a view, and why is it called a virtual table?
- Differentiate a simple view and a complex view.
- What is the purpose of WITH CHECK OPTION?
Hints:
- A view is a stored query presented as a table; an ordinary view does not maintain an independent stored copy of all result rows.
- Simple view commonly uses one table and limited calculations; complex view may contain joins, aggregates, or grouping.
- It prevents permitted DML through the view from creating rows outside the view's defining condition.
1.12 Synonyms
Definition
A synonym is an alternative name for another Oracle database object such as a table, view, sequence, or stored program unit.
Instead of repeatedly writing a long owner-qualified object name, users can refer to a shorter synonym.
Detailed Explanation
Suppose a table is owned by the HR user:
HR.EMPLOYEESA synonym can provide a shorter name:
CREATE SYNONYM emp
FOR hr.employees;The object can then be referenced through the synonym where privileges allow:
SELECT *
FROM emp;Why Synonyms Are Useful
- Simpler names: removes repeated schema qualification from object references.
- Location transparency: applications can reference a stable synonym while the underlying qualified object reference is managed separately.
- Convenience: shortens frequently used object names.
- Application independence: can reduce the need to place owner names throughout application SQL.
Private Synonym
A private synonym belongs to a particular schema.
CREATE SYNONYM staff
FOR hr.employees;Public Synonym
A public synonym is available for name resolution to database users, subject to the required object privileges.
CREATE PUBLIC SYNONYM staff
FOR hr.employees;Creating a public synonym requires the appropriate Oracle privilege.
Private and Public Synonyms
| Basis | Private Synonym | Public Synonym |
|---|---|---|
| Ownership | Belongs to a schema. | Created as a public database synonym. |
| Name availability | Primarily used within the owning schema's namespace. | Can be resolved by users database-wide, subject to Oracle's name resolution rules. |
| Creation syntax | CREATE SYNONYM | CREATE PUBLIC SYNONYM |
Common Mistake
A synonym does not grant permission to use the underlying object. It provides another name. The user still requires the necessary privileges on the referenced object.
Summary
- A synonym is an alternative name for another database object.
- It reduces dependency on long schema-qualified object names.
- Oracle supports private and public synonyms.
- A public synonym makes a name broadly resolvable but does not itself grant object privileges.
Test Yourself
- Differentiate a synonym from an object privilege.
- What is synonym? why it is important? explain it with example. (2021)
Hints:
- A synonym supplies another object name; a privilege authorizes operations on the object.
- Define synonym, explain naming convenience and location transparency, then show CREATE SYNONYM emp FOR hr.employees.
1.13 Sequences
Definition
A sequence is an Oracle database object that generates numeric values according to specified rules.
It is commonly used to generate identifiers without manually calculating the next number each time a new row is inserted.
Detailed Explanation
Creating a Sequence
CREATE SEQUENCE emp_seq
START WITH 1
INCREMENT BY 1;NEXTVAL
The NEXTVAL pseudocolumn obtains the next sequence value and advances the sequence.
SELECT emp_seq.NEXTVAL
FROM dual;It can be used during INSERT:
INSERT INTO employee(employee_id, ename, salary)
VALUES (emp_seq.NEXTVAL, 'Anita', 35000);CURRVAL
The CURRVAL pseudocolumn returns the current sequence value for the session after NEXTVAL has already been referenced for that sequence in the session.
SELECT emp_seq.CURRVAL
FROM dual;Sequence Options
| Option | Purpose |
|---|---|
| START WITH | Sets the first generated value. |
| INCREMENT BY | Specifies the difference between successive values. |
| MINVALUE | Defines a minimum sequence value. |
| MAXVALUE | Defines a maximum sequence value. |
| CYCLE | Allows generation to continue from the opposite boundary after reaching a defined limit. |
| NOCYCLE | Prevents automatic cycling after a limit is reached. |
| CACHE | Preallocates sequence values in memory for efficient generation. |
| NOCACHE | Disables sequence value caching. |
Complete Example
CREATE SEQUENCE order_seq
START WITH 1001
INCREMENT BY 1
NOCYCLE
CACHE 20;
INSERT INTO orders(order_id, customer_name)
VALUES (order_seq.NEXTVAL, 'Ramesh');
INSERT INTO orders(order_id, customer_name)
VALUES (order_seq.NEXTVAL, 'Sita');The generated values can be 1001 and 1002 respectively.
Why Sequences Are Used
- Generate unique numeric candidates efficiently.
- Avoid manually searching for the current maximum identifier.
- Allow multiple sessions to obtain values without serializing the application around MAX(column) calculations.
- Can be reused independently of one particular table unless the application restricts their use.
Common Mistake
A sequence does not guarantee a gap-free number series. A generated value can remain unused because of rollback, caching, failed operations, or application behavior. Sequences are designed for efficient number generation, not gapless numbering.
Summary
- A sequence generates numeric values independently of table rows.
- NEXTVAL obtains and advances the sequence value.
- CURRVAL returns the current session value after NEXTVAL has been used.
- START WITH and INCREMENT BY control the basic generation pattern.
- Sequence numbers can contain gaps and should not be assumed to be gapless.
Test Yourself
- Differentiate NEXTVAL and CURRVAL.
- Explain the use of sequence in oracle database with example. (2025)
Hints:
- NEXTVAL generates the next value; CURRVAL returns the current sequence value for the session after NEXTVAL has initialized it.
- Define sequence, explain automatic numeric generation, show CREATE SEQUENCE, then use sequence_name.NEXTVAL in an INSERT.
1.14 Table Partitioning
Definition
Table partitioning divides one logical table into smaller physical storage pieces called partitions according to a partitioning rule.
Applications can still query the object as one table, while Oracle can manage and access selected portions separately.
Detailed Explanation
Large tables can contain millions or billions of rows. Treating the whole object as one storage unit can make data management more difficult. Partitioning allows data to be divided according to values such as date, region, category, or a hash function.
Benefits of Partitioning
- Partition pruning: Oracle can avoid reading unrelated partitions when query conditions identify the required partition range or key.
- Manageability: selected partitions can be maintained separately.
- Availability: some maintenance operations can be limited to specific partitions.
- Data lifecycle management: older or newer data can be managed by partition.
- Performance opportunities: appropriate partitioning can reduce the data that some operations need to process.
Range Partitioning
Range partitioning assigns rows to partitions according to ordered value ranges. Dates are a common example.
CREATE TABLE sales (
sale_id NUMBER,
sale_date DATE,
amount NUMBER
)
PARTITION BY RANGE (sale_date) (
PARTITION sales_2025 VALUES LESS THAN (DATE '2026-01-01'),
PARTITION sales_2026 VALUES LESS THAN (DATE '2027-01-01'),
PARTITION sales_future VALUES LESS THAN (MAXVALUE)
);Rows from 2025 can go into sales_2025, 2026 rows into sales_2026, and later values into the MAXVALUE partition.
List Partitioning
List partitioning places rows according to explicitly listed values.
CREATE TABLE customers (
customer_id NUMBER,
name VARCHAR2(50),
region VARCHAR2(20)
)
PARTITION BY LIST (region) (
PARTITION p_bagmati VALUES ('BAGMATI'),
PARTITION p_gandaki VALUES ('GANDAKI'),
PARTITION p_other VALUES (DEFAULT)
);Hash Partitioning
Hash partitioning uses a hashing algorithm to distribute rows among a specified number of partitions.
CREATE TABLE transactions (
transaction_id NUMBER,
account_id NUMBER,
amount NUMBER
)
PARTITION BY HASH (account_id)
PARTITIONS 4;Hash partitioning is useful when even distribution is preferred and there is no natural range or list boundary.
Composite Partitioning
Composite partitioning combines partitioning methods. A table can first be partitioned using one method and then subpartitioned using another.
Examples include:
- Range-hash partitioning.
- Range-list partitioning.
- List-hash partitioning.
Partitioning Methods Comparison
| Method | Partition Rule | Typical Use |
|---|---|---|
| Range | Ordered ranges of values. | Dates, years, numeric ranges. |
| List | Explicit sets of values. | Region, category, branch type. |
| Hash | Oracle hash calculation. | Balanced distribution without natural boundaries. |
| Composite | Combination of partitioning methods. | Large data requiring more than one distribution dimension. |
Partition Pruning Example
For the partitioned SALES table:
SELECT SUM(amount)
FROM sales
WHERE sale_date >= DATE '2026-01-01'
AND sale_date < DATE '2027-01-01';When the partitioning conditions allow it, Oracle can restrict access to relevant partition data instead of examining every partition.
Let's Clarify
A university may keep examination records in separate cabinets by academic year while still treating them as one examination archive. A request for 2025 records does not require opening every cabinet.
A partitioned table follows the same idea: one logical table, multiple separately organized partitions.
Summary
- Partitioning divides one logical table into smaller physical partitions.
- Range partitioning uses ordered boundaries, while list partitioning uses specified values.
- Hash partitioning distributes rows with a hash function.
- Composite partitioning combines two partitioning approaches.
- Partition pruning can reduce unnecessary data access when query conditions match the partitioning scheme.
Test Yourself
- Compare range, list, hash, and composite partitioning.
- What is partitioning? Explain the different method of table partitioning. (2023)
Hints:
- Range = intervals; list = named value groups; hash = algorithmic distribution; composite = combined methods.
- Define partitioning as division of one logical table into partitions, then explain range, list, hash, and composite methods with examples.
1.15 Materialized Views
Definition
A materialized view is a database object that stores the result of a query physically and can refresh that stored result when underlying data changes.
A normal view stores a query definition and obtains current results when queried. A materialized view maintains stored query-result data that can be reused without recomputing the complete query every time.
Detailed Explanation
Materialized views are useful when a query is expensive and its result is repeatedly needed, especially in reporting and analytical systems.
Creating a Materialized View
CREATE MATERIALIZED VIEW dept_salary_summary
BUILD IMMEDIATE
REFRESH COMPLETE ON DEMAND
AS
SELECT department_id,
COUNT(*) AS employee_count,
SUM(salary) AS total_salary
FROM employee
GROUP BY department_id;The result of the GROUP BY query is physically stored as part of the materialized view.
Refresh Methods
Complete Refresh
A complete refresh recomputes the materialized view's defining query and replaces the stored result.
Fast Refresh
A fast refresh attempts to apply relevant incremental changes rather than recomputing the entire result. Fast refresh has additional requirements, and materialized view logs are commonly required depending on the materialized view definition.
Force Refresh
A force refresh allows Oracle to attempt a fast refresh when possible and use a complete refresh when the fast method cannot be performed.
Refresh Timing
- ON COMMIT: refresh is associated with transactions committing changes to relevant base tables when supported.
- ON DEMAND: refresh occurs when explicitly requested or scheduled through an appropriate mechanism.
View and Materialized View Comparison
| Feature | View | Materialized View |
|---|---|---|
| Stored query result | No separate persistent copy of the complete result in a normal view. | Yes, query result is physically stored. |
| Freshness | Query reflects underlying data when executed. | Depends on refresh state. |
| Refresh operation | Not required. | Required to synchronize stored result as appropriate. |
| Typical purpose | Simplification and controlled presentation. | Faster reuse of expensive query results and summaries. |
Common Mistake
A materialized view can contain older data if it has not been refreshed after changes to its base tables. Physical storage improves reuse of results, but freshness depends on the configured refresh method and timing.
Summary
- A materialized view physically stores the result of a query.
- It can reduce repeated processing of expensive joins, aggregates, and reporting queries.
- Common refresh methods include COMPLETE, FAST, and FORCE.
- Refresh timing can include ON COMMIT or ON DEMAND where supported.
- A materialized view differs from a normal view because its stored result can become stale between refreshes.
Test Yourself
- Differentiate a normal view and a materialized view.
- Explain complete, fast, and force refresh methods.
Hints:
- A normal view stores a query definition; a materialized view also stores query-result data and needs refreshing.
- Complete recomputes all data; fast applies eligible changes incrementally; force attempts fast and can fall back to complete.
1.16 Data Manipulation Language Operations
Definition
Data Manipulation Language (DML) consists of SQL statements used to add, change, and remove rows stored in database tables.
DDL creates the table structure. DML works with the actual records inside that structure.
Detailed Explanation
Major Oracle DML statements include INSERT, UPDATE, DELETE, and MERGE. SELECT is the principal statement used to retrieve data and is often studied alongside these operations.
INSERT
INSERT adds new rows.
INSERT INTO employee (
employee_id,
ename,
salary
)
VALUES (
101,
'Rita',
32000
);When all table columns are supplied in their table order, the column list can be omitted, but explicitly listing the target columns usually makes the statement clearer and safer.
UPDATE
UPDATE changes values in existing rows.
UPDATE employee
SET salary = 35000
WHERE employee_id = 101;DELETE
DELETE removes rows satisfying its condition.
DELETE FROM employee
WHERE employee_id = 101;MERGE
MERGE can combine conditional update and insert behavior, often called an upsert pattern.
MERGE INTO employee e
USING new_employee n
ON (e.employee_id = n.employee_id)
WHEN MATCHED THEN
UPDATE SET e.salary = n.salary
WHEN NOT MATCHED THEN
INSERT (employee_id, ename, salary)
VALUES (n.employee_id, n.ename, n.salary);DELETE and TRUNCATE Difference
| Basis | DELETE | TRUNCATE |
|---|---|---|
| Category | DML | DDL |
| Row selection | Can use WHERE to remove selected rows. | Removes all rows from the table. |
| Table structure | Retained. | Retained. |
| Normal rollback behavior | Can be rolled back before transaction commit. | DDL performs implicit transaction control and is not used like a normal rollback-capable DELETE. |
Importance of the WHERE Clause
The WHERE clause determines which rows UPDATE or DELETE affects.
DELETE FROM employee;The statement above targets every row because no WHERE condition is present.
DELETE FROM employee
WHERE employee_id = 101;This version targets only matching rows.
Common Mistake
Forgetting the WHERE condition in UPDATE or DELETE changes the scope from selected rows to every row in the table. The SQL statement may still be syntactically valid even though its effect is much broader.
Summary
- DML changes rows stored in tables.
- INSERT adds rows, UPDATE modifies rows, and DELETE removes rows.
- MERGE can perform conditional update-or-insert processing.
- WHERE controls which rows an UPDATE or DELETE affects.
- DELETE is DML, while TRUNCATE is a DDL operation that removes all rows.
Test Yourself
- Write INSERT, UPDATE, and DELETE statements for an EMPLOYEE table.
- Why is the WHERE clause critical in UPDATE and DELETE operations?
- Differentiate DELETE and TRUNCATE.
Hints:
- INSERT uses INTO and VALUES; UPDATE uses SET; DELETE uses FROM. Add a WHERE condition when targeting selected existing rows.
- Without WHERE, every row becomes part of the operation's target set.
- DELETE is DML and can remove selected rows; TRUNCATE is DDL and removes all rows while retaining table structure.
1.17 Joins
Definition
A join combines rows from two or more table sources by comparing related column values or another specified join condition.
Relational databases normally separate different subjects into different tables. Joins reconnect those related tables when a query needs information from more than one of them.
Detailed Explanation
Consider two tables:
EMPLOYEE
| employee_id | ename | department_id |
|---|---|---|
| 1 | Asha | 10 |
| 2 | Binod | 20 |
| 3 | Chandra | NULL |
DEPARTMENT
| department_id | department_name |
|---|---|
| 10 | IT |
| 20 | Finance |
| 30 | Administration |
Inner Join
An INNER JOIN returns rows for which the specified join condition matches.
SELECT e.employee_id,
e.ename,
d.department_name
FROM employee e
INNER JOIN department d
ON e.department_id = d.department_id;Asha matches department 10 and Binod matches department 20. Chandra has no matching department value, so that row is not returned by this inner join.
Equijoin
An equijoin is a join in which the join condition uses equality.
ON e.department_id = d.department_idThe previous INNER JOIN is therefore also an equijoin.
Non-Equijoin
A non-equijoin uses a condition other than simple equality, often to match values to ranges.
SELECT e.ename, e.salary, g.grade
FROM employee e
JOIN salary_grade g
ON e.salary BETWEEN g.min_salary AND g.max_salary;Left Outer Join
A LEFT OUTER JOIN returns every row from the left table plus matching rows from the right table. When no match exists, right-table columns contain NULL values.
SELECT e.ename, d.department_name
FROM employee e
LEFT JOIN department d
ON e.department_id = d.department_id;This can include Chandra even though no matching department exists.
Right Outer Join
A RIGHT OUTER JOIN returns every row from the right table plus matching rows from the left table.
SELECT e.ename, d.department_name
FROM employee e
RIGHT JOIN department d
ON e.department_id = d.department_id;This can include Administration even when no employee belongs to that department.
Full Outer Join
A FULL OUTER JOIN returns matching rows plus unmatched rows from both sides.
SELECT e.ename, d.department_name
FROM employee e
FULL OUTER JOIN department d
ON e.department_id = d.department_id;Self Join
A self join joins a table to another logical reference to the same table. Aliases distinguish the two roles.
SELECT e.ename AS employee_name,
m.ename AS manager_name
FROM employee e
LEFT JOIN employee m
ON e.manager_id = m.employee_id;Cross Join
A CROSS JOIN returns the Cartesian product: every row from one table paired with every row from the other table.
SELECT e.ename, s.shift_name
FROM employee e
CROSS JOIN shift s;If EMPLOYEE has 5 rows and SHIFT has 3 rows, the cross join produces 15 row combinations.
Join Comparison
| Join | Rows Returned | Typical Purpose |
|---|---|---|
| INNER JOIN | Only matching rows. | Retrieve records having relationships on both sides. |
| LEFT OUTER JOIN | All left rows plus right matches. | Keep all rows from the left source. |
| RIGHT OUTER JOIN | All right rows plus left matches. | Keep all rows from the right source. |
| FULL OUTER JOIN | Matches plus unmatched rows from both sides. | Preserve both complete source sets. |
| SELF JOIN | Depends on condition. | Compare related rows within the same table. |
| CROSS JOIN | Every possible row combination. | Produce a Cartesian product deliberately. |
Let's Clarify
A student table may store faculty_id, while the faculty name is stored only in a FACULTY table. The student row knows the faculty identifier, but it does not repeat the complete faculty information.
A join follows the matching identifier and returns information from both tables in one result.
Summary
- A join combines related rows from multiple table sources.
- INNER JOIN returns matches; outer joins preserve unmatched rows from one or both sides.
- Equijoins use equality, while non-equijoins use conditions such as ranges.
- A self join compares different logical instances of the same table.
- A cross join returns every possible pair of rows between its table sources.
Test Yourself
- Differentiate INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN.
- What is a self join? Give one situation where it is useful.
- What happens when a CROSS JOIN combines a table containing 8 rows with another containing 5 rows?
Hints:
- Inner keeps matches; left keeps every left row; right keeps every right row; full keeps unmatched rows from both sides.
- The same table is joined using two aliases, such as EMPLOYEE joined to itself for employee-manager relationships.
- 8 × 5 = 40 row combinations.
1.18 Subqueries
Definition
A subquery is a SQL query placed inside another SQL statement so that the result produced by the inner query can be used by the outer statement.
One query can first discover a value or set of values, and another query can use those results to decide which rows to return or modify.
Detailed Explanation
A basic subquery contains an inner query and an outer query.
SELECT ename, salary
FROM employee
WHERE salary > (
SELECT AVG(salary)
FROM employee
);The logical idea is:
Inner query calculates average salary → result is passed to outer query → outer query returns employees whose salaries exceed that value.
Single-Row Subquery
A single-row subquery returns one row. Operators such as =, >, <, >=, and <= can be used when one comparable value is expected.
SELECT ename
FROM employee
WHERE department_id = (
SELECT department_id
FROM department
WHERE department_name = 'IT'
);Multiple-Row Subquery
A multiple-row subquery returns more than one row. Operators such as IN, ANY, or ALL can be used depending on the required comparison.
SELECT ename
FROM employee
WHERE department_id IN (
SELECT department_id
FROM department
WHERE location_id = 100
);IN Operator
IN tests whether a value equals any value returned by the subquery.
ANY Operator
ANY compares a value with the values returned by a subquery and succeeds when the comparison is true for at least one returned value.
ALL Operator
ALL requires the comparison to be true for every value returned by the subquery.
Correlated Subquery
A correlated subquery refers to a column from the outer query. Its evaluation is logically associated with rows considered by the outer query.
SELECT e1.ename, e1.salary
FROM employee e1
WHERE e1.salary > (
SELECT AVG(e2.salary)
FROM employee e2
WHERE e2.department_id = e1.department_id
);This query finds employees whose salaries are above the average salary of their own departments.
EXISTS
EXISTS tests whether a subquery returns at least one row.
SELECT d.department_id, d.department_name
FROM department d
WHERE EXISTS (
SELECT 1
FROM employee e
WHERE e.department_id = d.department_id
);The department is returned when at least one matching employee exists.
Scalar Subquery
A scalar subquery returns exactly one value and can be used where a single expression is valid.
SELECT ename,
salary,
(SELECT AVG(salary) FROM employee) AS company_average
FROM employee;Subquery Types Comparison
| Type | Main Characteristic | Typical Operators |
|---|---|---|
| Single-row | Returns one row. | =, >, <, >=, <= |
| Multiple-row | Returns several rows. | IN, ANY, ALL |
| Correlated | References values from the outer query. | Often EXISTS or comparison operators |
| Scalar | Returns one value. | Used where an expression is valid |
Join and Subquery Relationship
Joins and subqueries can sometimes express similar information requests, but their structures differ.
- A join directly combines row sources.
- A subquery uses the result of one query inside another statement.
- The Oracle optimizer can transform some logically equivalent query forms internally, so SQL should be selected primarily for correct logic and clear expression of the requirement.
Common Mistake
Using = with a subquery that returns multiple rows can raise an error because = expects one comparable value. When several values are expected, operators such as IN, ANY, ALL, or an appropriate join are normally required.
Summary
- A subquery places one query inside another SQL statement.
- Single-row subqueries return one row, while multiple-row subqueries can return several.
- IN, ANY, and ALL support comparisons against multiple-row results.
- A correlated subquery refers to columns from the surrounding query.
- EXISTS tests whether the inner query produces at least one row.
Test Yourself
- Differentiate single-row and multiple-row subqueries.
- Explain a correlated subquery with an example.
- What is the difference between IN and EXISTS?
Hints:
- Single-row returns one row and can use operators such as =; multiple-row returns several and commonly uses IN, ANY, or ALL.
- A correlated subquery references a column from the outer query, such as comparing an employee's salary with the average salary of that employee's department.
- IN compares a value with a returned set; EXISTS checks whether the correlated or independent subquery produces at least one row.
Exam Questions
- Write SQL commands for following:
i. Create the table named blank having fields (Acc-no, name, address, ph-no, Balance)
ii. Add primary key in above table
iii. Add check constraints in the balance field, value of balance > 300.
iv. Rename the table blank to Bank.
v. Insert some rows and delete one of the record from the table Bank.
viii. Add loan_id field as foreign key referencing to the loan.
ix. Modify the name field to increase the character length.
x. Rename the name field to cname. (2026) - Explain oracle database architecture in detail including memory, process, and storage structure of oracle database. (2025)
- Explain the use of sequence in oracle database with example. (2025)
- What is partitioning? Explain the different method of table partitioning. (2023)
- What is indexing? Why it is important in database? Explain the different guidelines to create index in database. (2023)
- What is database administration? Explain the roles and responsibilities of DBA. (2023)
- Describe the memory structure of oracle database. Explain how PGA differs from SGA. Also explain about oracle instance and different components of SGA. (2023)
- What do you mean by oracle Instance? Explain about the different data structures used in SGA. (2021)
- What is synonym? why it is important? explain it with example. (2021)
- Explain the term database administrator (DBA) and describe the different roles of DBA. (2021)
- What do you mean by database management system? Mention the clear architecture of oracle database management system including different files, process and memory structure. (2021)
- Write SQL commands for following
i. Create the table named emp having fields (emp-id, name, address DOB, Salary)
ii. Add primary key in above table
iii. Add check constraints in the salary fields, value of salary> 10000
iv. Rename the table emp to employee
v. V Insert some rows and delete one of the record from the table employee
viii.Add department_id field as foreign key referencing the table department.
ix. Modify the name field to increase the character length
x. Rename the name field to ename. (2021)
Whole Chapter Summary
Oracle Database Architecture
Oracle combines memory structures, processes, and storage structures. Users communicate with an Oracle instance, and the instance accesses the physical database files to execute requests.
Oracle Instance and Memory Structure
An instance consists primarily of the System Global Area (SGA) and background processes. The SGA is shared, while the Program Global Area (PGA) contains private process memory.
Oracle Process Structure
User processes originate requests, server processes perform work for sessions, and background processes maintain the database. DBWn handles dirty database blocks, while LGWR writes redo information.
Oracle Storage Structure
The principal physical structures are datafiles, control files, and online redo log files. The logical hierarchy is tablespace → segment → extent → data block.
Database Administration
A DBA manages database installation, users, security, storage, backup, recovery, performance, availability, and maintenance so that the database remains reliable and protected.
SQL*Plus
SQL*Plus is an Oracle client environment for SQL, PL/SQL, scripts, variables, and formatted output. SQL statements are processed by Oracle, while SQL*Plus commands control the client environment.
Accepting Values at Runtime
Substitution variables allow scripts to accept changing values during execution. & requests substitution, && can retain a value, and ACCEPT provides controlled input prompting.
SQL Commands
DDL defines database structures, while DML manipulates stored rows. SELECT retrieves data, joins combine row sources, and subqueries use one query's result inside another statement.
Tables and Constraints
Tables store rows and columns. PRIMARY KEY identifies rows, FOREIGN KEY connects related tables, CHECK restricts values, and ALTER TABLE changes table definitions.
Indexes
Indexes provide alternative access paths to data and can accelerate selective searches. They must be designed according to table size, selectivity, query patterns, and DML workload.
Views
A view is a stored query presented like a virtual table. It simplifies SQL and controls the representation of base-table data without normally storing a separate copy of every result row.
Synonyms
A synonym is an alternative object name. It reduces dependence on long schema-qualified names but does not provide privileges on the underlying object.
Sequences
A sequence independently generates numeric values. NEXTVAL generates the next number and CURRVAL returns the current session value after NEXTVAL has been used.
Table Partitioning
Partitioning divides a logical table into smaller partitions. Major methods include range, list, hash, and composite partitioning, with partition pruning providing potential access benefits.
Materialized Views
A materialized view physically stores a query result and periodically refreshes it. COMPLETE, FAST, and FORCE are major refresh approaches.
Data Manipulation Language
INSERT adds rows, UPDATE changes rows, DELETE removes rows, and MERGE can combine update and insert behavior. WHERE controls the rows targeted by UPDATE and DELETE.
Joins
Joins combine related table sources. Inner joins retain matches, outer joins preserve selected unmatched rows, self joins relate rows within one table, and cross joins produce all combinations.
Subqueries
A subquery places one SQL query inside another. Subqueries can return single or multiple rows, reference outer-query rows through correlation, or be tested using operators such as IN and EXISTS.
Key Formulas and Points Sheet
| Rule or Pattern | Meaning |
|---|---|
| Oracle Instance = SGA + Background Processes | Running Oracle environment that accesses and manages database files. |
| Database → Tablespace → Segment → Extent → Block | Oracle logical storage hierarchy. |
| User Process → Server Process → Memory/Files → Result | Basic request-processing flow. |
| Change → Redo Log Buffer → LGWR → Online Redo Log | Basic redo-writing path. |
| Dirty Buffer → DBWn → Datafile | Modified database blocks are eventually written to physical storage. |
| PRIMARY KEY | Unique row identifier; key values cannot be NULL. |
| FOREIGN KEY | References a qualifying key in another or the same table. |
| CHECK (condition) | Requires inserted or modified data to satisfy the stated rule. |
| sequence.NEXTVAL | Generates and returns the next sequence value. |
| sequence.CURRVAL | Returns the sequence's current session value after NEXTVAL initialization. |
| Range / List / Hash / Composite | Main table-partitioning approaches covered in this unit. |
| INNER / LEFT / RIGHT / FULL | Core join families based on how matching and unmatched rows are retained. |
| Single-row subquery | Returns one row; commonly used with single-value comparison operators. |
| Multiple-row subquery | Returns several rows; commonly paired with IN, ANY, or ALL. |
Last-Minute Revision Sheet
| Concept | Trigger Phrase | Recall Cue |
|---|---|---|
| Oracle architecture | Three structures | Memory + processes + storage |
| Oracle database | Permanent part | Physical files on storage |
| Oracle instance | Running part | SGA + background processes |
| SGA | Shared memory | Buffer Cache + Shared Pool + Redo Log Buffer |
| PGA | Private memory | Session + SQL work areas |
| Buffer Cache | Data blocks in memory | Reduce physical disk reads |
| Shared Pool | Reusable SQL + metadata | Library Cache + Data Dictionary Cache |
| Redo Log Buffer | Change records | LGWR writes redo |
| DBWn | Dirty buffers | Memory → datafiles |
| LGWR | Redo | Redo buffer → online redo logs |
| CKPT | Checkpoint | Checkpoint metadata |
| SMON | System recovery | Instance recovery |
| PMON | Failed process | Process cleanup |
| Datafile | Actual stored data | Tablespace's physical storage |
| Control file | Database structure metadata | Files + checkpoints + state |
| Redo log | Database changes | Recovery information |
| Logical storage | Hierarchy | Tablespace → segment → extent → block |
| DBA | Database management | Security + storage + backup + performance |
| SQL*Plus | Oracle client | SQL + scripts + commands |
| &variable | Runtime input | Substitute supplied value |
| &&variable | Reusable substitution | Define and reuse value |
| DDL | Structure | CREATE + ALTER + DROP |
| DML | Rows | INSERT + UPDATE + DELETE + MERGE |
| Primary key | Row identity | Unique + not null |
| Foreign key | Relationship | Child references parent key |
| Check constraint | Value rule | CHECK(condition) |
| Index | Faster access path | Read gain + DML/storage cost |
| View | Virtual table | Stored query definition |
| Synonym | Alternative name | Name convenience, not privilege |
| Sequence | Number generator | NEXTVAL / CURRVAL |
| Range partition | Intervals | Date/numeric boundaries |
| List partition | Named values | Region/category groups |
| Hash partition | Distribution | Hash-based balancing |
| Materialized view | Stored query result | Refresh required |
| INNER JOIN | Matches only | Both sides match |
| LEFT JOIN | Preserve left | All left + matches |
| FULL JOIN | Preserve both | Matches + unmatched both sides |
| Self join | Same table twice | Aliases |
| Cross join | Every combination | Rows A × rows B |
| Single-row subquery | One result row | =, >, < |
| Multiple-row subquery | Several result rows | IN + ANY + ALL |
| Correlated subquery | Outer-row dependency | Inner query references outer query |
| EXISTS | Row existence | True when subquery returns a row |


