This guide is derived from the earlier outline (edition not confirmed) for CACS405 (Database Administration). All units and topics follow the outlined sequence; wording and examples are original student study material, not official TU text.

How to use this guide

Database Administration covers Oracle database concepts, administration, and tuning. The exam rewards knowledge of database architecture, SQL commands, user management, backup/recovery, and the Scheduler. Practice writing SQL DDL/DML, designing backup strategies, and configuring the Oracle Network environment. Marks are awarded for correct syntax, explaining command functionality, and describing security best practices.

Learning Outcomes

By the end of this course, a student should be able to:

  1. Describe the Oracle Database Architecture including memory and storage structures.
  2. Write DDL commands to create tables, constraints, indexes, views, and sequences.
  3. Manage database instances including startup/shutdown, parameter files, and network configuration.
  4. Create and manage users, roles, profiles, and apply the principle of least privilege.
  5. Explain the Multitenant Architecture and perform PDB creation and management.
  6. Configure Oracle Net Listener and client connectivity using TNSPING and Enterprise Manager.
  7. Design and implement backup and recovery strategies using RMAN and user-managed methods.
  8. Automate database tasks using the Oracle Scheduler including job creation and event-based schedules.

Unit 1: Introduction to an Oracle database

Teaching hours: 12

Topics in outline order

  1. Overview of the Oracle Database Architecture. The Oracle Database Architecture consists of three major components: the instance (processes and memory), the database (data files, control files, redo log files, and online redo logs), and the background processes (DBWR, LGWR, CKPT, PMON, SMON, etc.). The memory structure includes the System Global Area (SGA) and Program Global Areas (PGA). The SGA contains the Database Buffer Cache, Redo Log Buffer, Shared Pool, Large Pool, Java Pool, and Streams Pool. The storage structure includes data files (permanent data), control files (database metadata), and redo log files (change recording). Understanding the architecture is critical for performance tuning, troubleshooting, and capacity planning. Every DBA must know how memory is allocated, how data is stored on disk, and how the background processes coordinate to ensure data integrity and concurrency.

  2. DBA roles and responsibilities. A Database Administrator (DBA) is responsible for the installation, configuration, upgrading, monitoring, and maintenance of the Oracle Database server. Key responsibilities include: security (user account management, role assignment, privilege granting/revoking), backup and recovery ( designing and testing backup strategies, performing recovery when data is lost), performance tuning (monitoring resource usage, identifying bottlenecks, optimizing SQL and database parameters), storage management (adding data files, managing tablespaces, ensuring adequate disk space), software updates (applying patches and upgrades), and documentation (maintaining configuration records, change logs, and standard operating procedures). Common DBA roles include DBA (full administration), Application DBA (focused on application databases), and Security DBA (focused on database security).

  3. Familiarity with SQL Plus.* SQL* Plus is the command-line interface for interacting with Oracle Database. It allows users to enter SQL and PL/SQL commands, execute scripts, and perform administrative tasks. Basic SQL* Plus commands include: SQL> prompt, EXIT or QUIT (exit SQL* Plus), CONNECT (connect to the database using username/password), DISCONNECT (disconnect from the current session), SET (set system variables like PAGESIZE, LINESIZE, NULL), DESCRIBE (display table structure), EDIT (edit the current command buffer), and RUN (run the contents of the buffer). Connection syntax: sqlplus username/password@db_service_name. Output formatting can be controlled with commands like COLUMN, BREAK, COMPUTE, and system parameters set via SET.

  4. Accepting Values at Runtime. The & and && substitution variables in SQL* Plus allow users to prompt for values at runtime. &variable prompts the user once and requires a value each time the script runs. &&variable prompts the user once and stores the value so it doesn't prompt again in the same session. Example: SELECT * FROM employees WHERE department_id = &dept_id; prompts for the department ID. The UNDEFINE command undoes a previous DEFINE or & substitution. This feature is essential for creating flexible, reusable scripts that adapt to different inputs without modifying the script code.

  5. Overview of SQL Command (DDL: Tables, Constraints, Indexes, Views, Synonyms, Sequences). Data Definition Language (DDL) commands define the database structure. Key DDL commands:

    • CREATE TABLE creates a new table with columns, data types, and constraints. Syntax: CREATE TABLE table_name (column1 datatype [constraint], column2 datatype [constraint], ...);
    • Constraints enforce data integrity: NOT NULL (must have a value), UNIQUE (all values must be distinct), PRIMARY KEY (unique and not null, identifies each row), FOREIGN KEY (establishes referential integrity between tables), CHECK (validates values against a logical expression), and DEFAULT (provides a default value if none is given).
    • CREATE INDEX creates an index on one or more columns to improve query performance. Syntax: CREATE INDEX index_name ON table_name (column1, column2 ...);. Index types include B-tree (default, equality and range queries), Bitmap (low cardinality columns, data warehousing), and Function-based (expressions on columns).
    • CREATE VIEW creates a virtual table based on a SELECT query. Syntax: CREATE VIEW view_name AS SELECT column1, column2, ... FROM table_name WHERE condition; Views do not store data; they reflect changes to the underlying tables. Useful for simplifying complex queries, securing data (restricting column/row access), and presenting a consistent interface.
    • CREATE SYNONYM creates an alias for a database object. Syntax: CREATE SYNONYM syn_name FOR object_name; Synonyms hide the owner name, provide location transparency (for database links), and simplify SQL statements.
    • CREATE SEQUENCE generates unique numeric values. Syntax: CREATE SEQUENCE seq_name START WITH 1 INCREMENT BY 1 MAXVALUE 1000 NOCYCLE NOCACHE; Sequences are commonly used for primary key values. Commands: NEXTVAL (next value), CURRVAL (current value), INCREMENT BY, MAXVALUE, MINVALUE, NOCYCLE (no wrap-around), NOCACHE (no pre-allocation in memory).
  6. Partitioning and Materialized Views. Table partitioning divides large tables into smaller, manageable pieces called partitions, each containing a subset of data. Partitioning improves query performance (partition pruning), simplifies maintenance (partition-level operations), and supports large data volumes. Common partition types: Range (partitions based on a range of values, e.g., by date), List (partitions based in a discrete list of values, e.g., by region), Hash (partitions based on a hash function, distributes data evenly), and Composite (combination of above, e.g., range-hash). Materialized Views are database objects that contain the results of a query and can be refreshed periodically. Unlike regular views, materialized views store data physically and are used for data warehousing to improve query performance on aggregated data. Refresh methods: Complete (requery from source), Fast (using materialized view logs), and Force (attempt fast, fall back to complete).

  7. DML (Insert, Update, Delete). Data Manipulation Language (DML) commands manipulate data within tables. Key commands:

    • INSERT adds new rows: INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...); or INSERT INTO table_name SELECT ... FROM ...; (from another table). The INSERT ALL syntax allows multiple rows in one statement: INSERT ALL WHEN condition1 THEN INTO t1 VALUES (...) WHEN condition2 THEN INTO t2 VALUES (...) SELECT ... FROM ...;
    • UPDATE modifies existing rows: UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition; The WHERE clause is critical; omitting it updates ALL rows. The RETURNING INTO clause can return updated values: UPDATE employees SET salary = 5000 WHERE emp_id = 100 RETURNING INTO :salary_out;
    • DELETE removes rows: DELETE FROM table_name WHERE condition; Omitting the WHERE clause deletes all rows. Use TRUNCATE TABLE to quickly remove all rows (commits immediately, cannot be rolled back, resets high-water mark). DELETE is a DML operation (can be rolled back); TRUNCATE is a DDL operation (cannot be rolled back).
  8. Join and Subquery. A Join combines rows from two or more tables based on a related column. Common join types:

    • INNER JOIN: Returns rows when there is a match in both tables. Syntax: SELECT columns FROM table1 INNER JOIN table2 ON table1.col = table2.col;
    • LEFT (OUTER) JOIN: Returns all rows from the left table and matched rows from the right. Unmatched right rows contain NULL. Syntax: SELECT columns FROM table1 LEFT JOIN table2 ON table1.col = table2.col;
    • RIGHT (OUTER) JOIN: Returns all rows from the right table and matched rows from the left. Unmatched left rows contain NULL.
    • FULL (OUTER) JOIN: Returns rows when there is a match in one or both tables. Unmatched sides contain NULL.
    • CROSS JOIN: Returns the Cartesian product of all rows from both tables. A Subquery is a SELECT query nested within another SQL statement. Types include: Scalar subquery (returns a single value, used in WHERE or SELECT), Column subquery (returns a single column), Row subquery (returns a single row), Table subquery (returns a full result set, used with IN, EXISTS, ANY, ALL). Correlated subqueries reference columns from the outer query and are evaluated once per row. The EXISTS operator checks for the existence of rows; NOT EXISTS excludes rows. The ANY operator compares a value to any value in a list; ALL compares to all values.

Explanation

  1. Oracle Database Architecture. The architecture separates the physical storage (data files, control files, redo logs) from the logical structure (tablespaces, segments, extents, blocks). The SGA stores shared data structures (buffer cache for data blocks, shared pool for SQL statements, redo log buffer for changes). Background processes (DBWR writes dirty buffers to disk, LGWR writes redo entries, CKPT checkpoints, PMON process recovery, SMON system monitoring) ensure consistent and reliable operation. The Program Global Area (PGA) stores session-specific data like sort areas and hash join areas. Understanding the architecture enables the DBA to allocate appropriate memory, diagnose performance issues, and plan storage growth.

  2. DBA roles and responsibilities. The DBA role is multifaceted. Security involves creating strong password policies, assigning least-privilege roles, and auditing user activity. Backup and recovery require designing a strategy aligned with business requirements (Recovery Time Objective, Recovery Point Objective) and regularly testing restores. Performance tuning involves monitoring wait events, identifying high-load SQL, and optimizing execution plans. Storage management includes adding data files, resizing data files, managing auto-extensible data files, and monitoring tablespace usage. Software updates require testing patches in a non-production environment before applying to production. Documentation ensures knowledge transfer and compliance with organizational policies.

  3. SQL Plus.* SQL* Plus is the foundational tool for Oracle DBAs. Beyond executing SQL, it supports scripting with variables, substitution parameters (&, &&), command buffers, and output formatting. Mastery of SQL* Plus enables efficient ad-hoc queries, automated maintenance tasks via OS scheduling, and troubleshooting when graphical tools are unavailable. The SET command customizes the environment (e.g., SET PAGESIZE 100, SET LINESIZE 132, SET COL sep |).

  4. Accepting Values at Runtime. Substitution variables make SQL* Plus scripts dynamic and reusable. & prompts every time; && prompts once per session. This is essential for parameterized reports, migration scripts, and automated jobs. Example script: SELECT &column_name FROM &table_name WHERE &condition = &value; prompts the user for each substitution. Note that & is case-sensitive for the variable name. The UNDEFINE command removes a substitution variable definition, and DEFINE sets a variable to a default value without prompting.

  5. DDL Commands. DDL defines the database schema. CREATE TABLE is the most fundamental DDL command. Constraints ensure data integrity at the database level, reducing application-level validation needs. CREATE INDEX improves query performance significantly for large tables; however, indexes incur overhead during INSERT/UPDATE/DELETE operations, so they must be designed judiciously. CREATE VIEW provides a layer of abstraction; views can restrict user access to sensitive columns while exposing others. CREATE SYNONYM simplifies object referencing, especially across database links. CREATE SEQUENCE guarantees unique primary key values without relying on application logic or database triggers.

  6. Partitioning and Materialized Views. Partitioning is essential for tables with billions of rows. Range partitioning is common for time-series data (e.g., sales by quarter). Hash partitioning ensures even distribution for even workload distribution. Materialized Views pre-compute expensive aggregations (e.g., total sales by region per month) and refresh periodically. Fast refresh requires a materialized view log on the source table, which captures changes for incremental updates. Materialized Views are named in the DBA_MATERIALIZED_VIEWS view and can be queried like regular tables.

  7. DML Operations. INSERT, UPDATE, and DELETE are the core data manipulation operations. Always use a WHERE clause with UPDATE and DELETE to avoid unintended data modification. TRUNCATE TABLE is faster than DELETE FROM table for removing all rows but cannot be rolled back and does not trigger DELETE triggers. The RETURNING INTO clause is useful for getting generated keys or updated values without a separate SELECT after the DML. Batch inserts using INSERT ALL or INSERT ... SELECT are more efficient than individual INSERT statements.

  8. Join and Subquery. Joins are fundamental for querying data across related tables. Understanding join types and their performance implications is critical; for example, a CROSS JOIN on large tables produces an enormous result set. Subqueries offer alternative ways to filter or derive data. Correlated subqueries are powerful but can be inefficient if not optimized; converting them to JOINs with proper indexes often improves performance. The EXISTS operator is particularly useful for checking row existence (e.g., "find employees who have no assigned department"). The ANY and ALL operators enable comparisons against a list (e.g., "find salaries greater than the average salary in each department").

Worked Example 1: Creating a Table with Constraints

Problem: Create an employees table with the following requirements:

  • Employee ID as primary key (not null, unique)
  • First name and last name must not be null
  • Email must be unique
  • Hire date defaults to current date
  • Salary must be positive (check constraint)

Solution:

CREATE TABLE employees (
    employee_id NUMBER PRIMARY KEY,
    first_name VARCHAR2(50) NOT NULL,
    last_name VARCHAR2(50) NOT NULL,
    email VARCHAR2(100) UNIQUE,
    hire_date DATE DEFAULT SYSDATE,
    salary NUMBER CHECK (salary > 0),
    department_id NUMBER
);

Intermediate steps:

  1. CREATE TABLE employees ( starts the table creation.
  2. employee_id NUMBER PRIMARY KEY defines the first column with a primary key constraint (implicitly NOT NULL and UNIQUE).
  3. first_name VARCHAR2(50) NOT NULL ensures the first name cannot be empty.
  4. last_name VARCHAR2(50) NOT NULL ensures the last name cannot be empty.
  5. email VARCHAR2(100) UNIQUE ensures no two employees have the same email.
  6. hire_date DATE DEFAULT SYSDATE sets the hire date to the current system date if not provided.
  7. salary NUMBER CHECK (salary > 0) validates that salary must be positive.
  8. department_id NUMBER creates a column without constraints (can be null).
  9. ); terminates the CREATE TABLE statement.

Expected result: The employees table is created with all specified constraints. The table is owned by the current user and appears in USER_TABLES. Constraints appear in USER_CONSTRAINTS.

Verification: DESCRIBE employees shows column definitions and constraints. SELECT constraint_name, constraint_type FROM user_constraints WHERE table_name = 'EMPLOYEES'; displays the constraints.

Worked Example 2: Creating and Using a Sequence

Problem: Create a sequence for generating employee IDs and use it to insert a new employee.

Solution:

CREATE SEQUENCE emp_seq
    START WITH 1
    INCREMENT BY 1
    MAXVALUE 999999999999999999999999999
    NOCYCLE
    NOCACHE;
INSERT INTO employees (employee_id, first_name, last_name, email, hire_date, salary, department_id)
VALUES (emp_seq.NEXTVAL, 'John', 'Doe', 'john.doe@example.com', SYSDATE, 5000, 10);
SELECT emp_seq.CURRVAL FROM dual;

Intermediate steps:

  1. CREATE SEQUENCE emp_seq starts the sequence creation.
  2. START WITH 1 sets the initial value (first call to NEXTVAL returns 1).
  3. INCREMENT BY 1 increases the value by 1 for each subsequent call.
  4. MAXVALUE 999999999999999999999999999 sets the maximum value (cycle or no cycle).
  5. NOCYCLE means the sequence stops at MAXVALUE; no wrapping to MINVALUE.
  6. NOCACHE means values are not pre-allocated in memory; each NEXTVAL incurs a disk read.
  7. emp_seq.NEXTVAL in the INSERT statement retrieves the next sequence value.
  8. emp_seq.CURRVAL returns the current (most recently assigned) sequence value (must call NEXTVAL first in the session).

Expected result: The sequence emp_seq is created. The INSERT statement inserts a new employee with ID 1. The SELECT returns 1 (the current value in this session).

Verification: SELECT sequence_name, min_value, max_value, increment_by, last_number FROM user_sequences WHERE sequence_name = 'EMP_SEQ'; shows sequence properties. SELECT emp_seq.NEXTVAL FROM dual; returns 2 on the second call.

Worked Example 3: Creating an Index

Problem: Create an index on the email column of the employees table to speed up lookups by email.

Solution:

CREATE INDEX idx_employees_email ON employees (email);
-- Verify the index was created
SELECT index_name, table_name, uniqueness FROM user_indexes WHERE table_name = 'EMPLOYEES';

Intermediate steps:

  1. CREATE INDEX idx_employees_email ON employees (email) creates a B-tree index named idx_employees_email on the email column of the employees table.
  2. The index is stored as a separate object in the data dictionary.
  3. Oracle automatically maintains the index during DML operations (INSERT, UPDATE, DELETE).
  4. Querying user_indexes confirms the index exists and shows its uniqueness (NONUNIQUE for a regular B-tree index on a non-unique column).

Expected result: The index idx_employees_email is created. Future queries SELECT * FROM employees WHERE email = 'john.doe@example.com' will use the index for faster row lookup.

Verification: EXPLAIN PLAN FOR SELECT * FROM employees WHERE email = 'john.doe@example.com'; followed by SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY); shows the execution plan using the index.

Worked Example 4: Creating a View

Problem: Create a view that shows only employee names and salaries for the HR department.

Solution:

CREATE VIEW hr_employees AS
    SELECT first_name, last_name, salary
    FROM employees
    WHERE department_id = 10;
-- Query the view as if it were a table
SELECT * FROM hr_employees;
-- Update the underlying table; the view reflects the change
UPDATE employees SET salary = 5500 WHERE first_name = 'John' AND last_name = 'Doe';
SELECT * FROM hr_employees WHERE first_name = 'John';

Intermediate steps:

  1. CREATE VIEW hr_employees AS starts the view creation and names it hr_employees.
  2. The SELECT statement defines the columns and rows included in the view.
  3. WHERE department_id = 10 filters to only employees in department 10 (HR).
  4. The view is stored as a SELECT query in the data dictionary; it does not store data physically.
  5. Querying the view executes the SELECT query against the underlying table.
  6. DML on the underlying table is reflected in the view (depending on view type: simple views allow DML, complex views may not).

Expected result: The view hr_employees is created. Querying it returns first name, last name, and salary for employees in department 10. When the underlying employees table is updated, the view reflects the change immediately.

Verification: SELECT view_name, text FROM user_views WHERE view_name = 'HR_EMPLOYEES'; displays the view's defining SELECT query.

Worked Example 5: Creating a Synonym

Problem: Create a synonym emp for the employees table owned by user hr.

Solution:

CREATE SYNONYM emp FOR hr.employees;
-- Use the synonym without specifying the owner
SELECT * FROM emp WHERE salary > 5000;
-- Drop the synonym
DROP SYNONYM emp;

Intermediate steps:

  1. CREATE SYNONYM emp FOR hr.employees creates a public synonym emp that references hr.employees.
  2. The synonym stores only the alias; it does not create a new object or data.
  3. Queries can now use emp instead of hr.employees, providing location transparency.
  4. DROP SYNONYM emp removes the synonym without affecting the underlying table.

Expected result: The synonym emp is created. Any user can query SELECT * FROM emp (if public) or the current user can use the synonym without prefixing hr.. This simplifies SQL and provides abstraction from the actual owner name.

Verification: SELECT synonym_name, table_owner, table_name FROM user_synonyms WHERE synonym_name = 'EMP'; displays the synonym definition.

Worked Example 6: Using JOIN to Combine Tables

Problem: List employee names and their department names from the employees and departments tables.

Solution:

SELECT e.employee_id, e.first_name, e.last_name, d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;
-- Left include all employees even if no department assigned
SELECT e.employee_id, e.first_name, e.last_name, d.department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;

Intermediate steps:

  1. The FROM employees e aliases the employees table as e for brevity.
  2. INNER JOIN departments d ON e.department_id = d.department_id joins on the matching department ID. Only employees with a valid department ID in the departments table are included.
  3. LEFT JOIN includes all employees from the left table, even if no matching department exists; department_name will be NULL for such employees.
  4. The SELECT list chooses specific columns from both tables using table aliases.
  5. The result set contains one row per employee-department combination.

Expected result: The INNER JOIN query returns employee names along with their department names, excluding employees without a valid department. The LEFT JOIN query returns all employees, with NULL for department_name where no match exists.

Verification: SELECT * FROM departments; confirms the department data. SELECT COUNT(*) FROM employees; and SELECT COUNT(*) FROM employees WHERE department_id IS NULL; check for employees without departments.

Common Mistakes, Limitations, and Security Concerns

  1. Omitting the WHERE clause in UPDATE/DELETE can modify/delete all rows in a table. Always double-check the WHERE clause, and consider using a SELECT first to verify: SELECT * FROM employees WHERE employee_id = 100; before running the UPDATE.

  2. Forgetting to create indexes on frequently queried columns leads to full table scans and poor performance. Index columns used in JOIN conditions, WHERE clauses, and ORDER BY.

  3. Using DEFAULT SYSDATE without timezone consideration can cause issues in distributed databases. Consider using SYSTIMESTAMP for timezone-aware timestamps.

  4. Primary key violations when inserting duplicate values cause errors. Sequences (emp_seq.NEXTVAL) prevent accidental duplicates.

  5. Check constraint errors when data does not satisfy the constraint (e.g., negative salary with CHECK (salary > 0)) cause the statement to fail. Validate data before inserting.

  6. View limitations: Complex views (involving GROUP BY, JOINs, aggregate functions) do not support INSERT/UPDATE/DELETE. Simple views (based on a single table) do support DML.

  7. Synonym overuse: Public synonyms can cause ambiguity if the same name exists in multiple schemas. Prefix with the owner name in production environments.

  8. Security concern: Never grant DBA or unrestricted privileges to application users. Use role-based privilege assignment and the principle of least privilege (grant only the minimum privileges needed for the task).

  9. Backup oversight: Regularly test backup and recovery procedures. A backup that cannot be restored is useless. Document the recovery procedure and verify it periodically.

  10. Scheduler misuse: The Oracle Scheduler automates jobs but misconfigured jobs can cause resource exhaustion. Always test jobs in a development environment and monitor execution in production.

Exam Practice: Likely Question Patterns

  1. Describe the Oracle Database Architecture. Explain the instance, database, and background processes. Mention SGA components (buffer cache, shared pool, redo log buffer) and storage components (data files, control files, redo logs).

  2. Write a CREATE TABLE statement with appropriate constraints (PRIMARY KEY, NOT NULL, UNIQUE, CHECK, FOREIGN KEY) for a given scenario.

  3. DML operations: Write INSERT, UPDATE, and DELETE statements for a given table. Include a TRUNCATE comparison question.

  4. Join types: Differentiate between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN with examples. When would you use each?

  5. Subqueries: Write a query using a correlated subquery and rewrite it as a JOIN. Explain the performance implications.

  6. DDL commands: Create an index, a view, a synonym, and a sequence. Explain the purpose and usage of each.

  7. Backup and Recovery: Differentiate between user-managed backup and RMAN backup. When would you use each? What are the steps to restore a data file from RMAN?

  8. User management: Create a user, assign a tablespace, grant roles and system privileges. Explain the difference between role and system privilege.

  9. Multitenant Architecture: Explain the CDB/PDB architecture. How do you create a PDB? How do you switch between PDBs?

  10. Scheduler: Create a simple scheduled job using DBMS_SCHEDULER. What are the differences between time-based and event-based schedules?

Self-Check Questions (with Answers)

  1. Question: What are the three major components of the Oracle Database Architecture? Answer: The three major components are the instance, the database, and the background processes.

  2. Question: What constraint ensures that a column must contain a unique value and cannot be null? Answer: PRIMARY KEY constraint.

  3. Question: What is the difference between &variable and &&variable in SQL* Plus? Answer: &variable prompts the user for a value each time the script runs. &&variable prompts once and stores the value for the session, so it does not prompt again.

  4. Question: Which DDL command creates a virtual table based on a SELECT query? Answer: CREATE VIEW.

  5. Question: What is the purpose of a sequence in Oracle? Answer: A sequence generates unique numeric values, commonly used for primary key values.

  6. Question: What is the difference between TRUNCATE TABLE and DELETE FROM table? Answer: TRUNCATE TABLE is a DDL operation that quickly removes all rows, commits immediately, cannot be rolled back, and resets the high-water mark. DELETE FROM table is a DML operation that can be rolled back, fires triggers, and preserves the high-water mark.

  7. Question: Which join type returns all rows from the left table and matched rows from the right, with NULL for unmatched right rows? Answer: LEFT (OUTER) JOIN.

  8. Question: What does the CHECK constraint validate? Answer: The CHECK constraint validates that column values satisfy a logical expression (e.g., CHECK (salary > 0)).

  9. Question: What is a materialized view and how does it differ from a regular view? Answer: A materialized view stores the query results physically and can be refreshed periodically. A regular view does not store data; it reflects changes to the underlying tables in real-time.

  10. Question: What are the key security practices for Oracle Database? Answer: Change default passwords, apply the principle of least privilege, use TLS/SSL for encryption, keep firmware updated, implement audit policies, and regularly test backup and recovery.


Detailed Practice Questions and Answer Keys

Question 1: Write a CREATE TABLE statement for a products table with columns: product_id (NUMBER, primary key), product_name (VARCHAR2(100), not null), price (NUMBER with check price > 0), category_id (NUMBER, foreign key referencing departments table), and description (CLOB, default empty string).

Answer Key:

CREATE TABLE products (
    product_id NUMBER PRIMARY KEY,
    product_name VARCHAR2(100) NOT NULL,
    price NUMBER CHECK (price > 0),
    category_id NUMBER REFERENCES departments(department_id),
    description CLOB DEFAULT EMPTY_CLOB()
);

Question 2: Write a query using an INNER JOIN to list employee names and their department names. Then rewrite it using a LEFT JOIN to include employees without assigned departments.

Answer Key:

-- INNER JOIN
SELECT e.first_name, e.last_name, d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;

-- LEFT JOIN
SELECT e.first_name, e.last_name, d.department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;

Question 3: Create a sequence seq_dept starting at 100, incrementing by 10, with no maximum value, and cycle back to the minimum value when the maximum is reached.

Answer Key:

CREATE SEQUENCE seq_dept
    START WITH 100
    INCREMENT BY 10
    NOMINVALUE
    NOCYCLE;

Note: With NOCYCLE, the sequence stops at MAXVALUE. With CYCLE, it wraps around. NOMINVALUE uses the default minimum of 1.

Question 4: A user reports they cannot connect to the Oracle Database. List at least three possible causes and how you would diagnose each.

Answer Key:

  1. Incorrect password: Try connecting with SQL* Plus using the username and password. Reset the password if needed via ALTER USER.
  2. Network connectivity: Ping the database server, check Oracle Listener status (lsnrctl status), and verify the service name with SELECT * FROM v$database.
  3. Listener not running: Start the listener with lsnrctl start and verify with lsnrctl status.
  4. Invalid service name: Use TNSPING to test connectivity and verify the tnsnames.ora entry.
  5. Account locked: The user account may be locked; unlock with ALTER USER username ACCOUNT UNLOCK.

Question 5: Explain the difference between RMAN backup and user-managed backup. When would you prefer one over the other?

Answer Key:

  • RMAN backup: Uses the Recovery Manager utility, provides incremental backups, integrates with Oracle for consistent backups, supports compression and encryption, and can perform point-in-time recovery. Preferred for most environments due to feature richness and reliability.
  • User-managed backup: Involves shutting down the database or copying data files while the database is cold, or using OS commands to copy files. Simpler but requires the database to be offline for consistent backups. Used when RMAN is unavailable or for simple file-level copies.

Question 6: Create a view vw_high_salary_employees that shows employees with a salary greater than 7000, including their first name, last name, salary, and department name.

Answer Key:

CREATE VIEW vw_high_salary_employees AS
    SELECT e.first_name, e.last_name, e.salary, d.department_name
    FROM employees e
    JOIN departments d ON e.department_id = d.department_id
    WHERE e.salary > 7000;

Question 7: Explain the Oracle Scheduler. How do you create a job that runs every day at 2 AM?

Answer Key: The Oracle Scheduler (DBMS_SCHEDULER) automates database operations on a schedule. To create a daily job at 2 AM:

BEGIN
    DBMS_SCHEDULER.CREATE_JOB (
        job_name => 'daily_job_2am',
        job_type => 'PL/SQL_BLOCK',
        job_action => 'BEGIN null; END;',
        start_date => SYSTIMESTAMP,
        repeat_interval => 'FREQ=DAILY; BYHOUR=2',
        enabled => TRUE
    );
END;
/

Question 8: What are the differences between a role and a system privilege? Provide an example of each.

Answer Key:

  • System privilege allows a user to perform a specific action regardless of the object owner (e.g., CREATE TABLE, CREATE VIEW, SELECT ANY TABLE). System privileges are globally assigned and affect the entire database.
  • Role is a named group of system privileges and/or object privileges that can be granted to users. Roles simplify privilege management; granting one role grants all associated privileges. Example system privilege: CREATE TABLE. Example role: CONNECT (allows session creation), RESOURCE (allows table creation, sequences, triggers).

Question 9: How do you create a Pluggable Database (PDB) in a Container Database (CDB)?

Answer Key:

CREATE PLUGGABLE DATABASE pdb_name
    ADMIN USER admin_id IDENTIFIED BY password
    FILE_NAME_CONVERT = ('/path/to/source/', '/path/to/target/');

Alternatively, use the CREATE PLUGGABLE DATABASE ... FROM clause to clone from an existing PDB or use CREATE PLUGGABLE DATABASE ... AS SEED.

Question 10: Write a PL/SQL block to create a table, insert a row, and handle the primary key violation exception.

Answer Key:

BEGIN
    CREATE TABLE test (id NUMBER PRIMARY KEY, name VARCHAR2(10));
    INSERT INTO test VALUES (1, 'Test');
EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
        DBMS_OUTPUT.PUT_LINE('Primary key violation: duplicate value');
        ROLLBACK;
END;
/

References from the Source Syllabus

  • CACS405 Database Administration course outline (2018), TU FOHSS PDF pp. 119-121
  • Oracle Database Documentation: https://docs.oracle.com/
  • Robert J. Freeman, "Sams Teach Yourself Oracle8 in 24 Hours", 1999
  • Mark L. Gurry, "Oracle Database 12c: SQL Fundamentals", 2013

End of Guide