Database Systems Lecture 2

DATABASE SYSTEMS

Lecture 2


Oracle Demonstration Database

Database Tables
  • JOB HISTORY

    • employee_id

    • start_date

    • end_date

    • job_id

    • department_id

  • EMPLOYEES

    • employee_id

    • first_name

    • last_name

    • email

    • phone_number

  • DEPARTMENTS

    • department_id

    • department_name

    • hire_date

    • job_id

  • JOBS

    • job_id

    • job_title

    • min_salary

    • max_salary

    • manager_id

    • location_id

    • salary

    • commission_pct

    • manager_id

    • department_id

  • LOCATIONS

    • location_id

    • street_address

    • postal_code

    • city

    • state_province

    • country_id

  • COUNTRIES

    • country_id

    • country_name

    • region_id

  • REGIONS

    • region_id

    • region_name


Type Conformity in SQL

  • NULL Values

    • The NVL function must return a value of the same type as the field.

    • Example:

      • SELECT NVL(salary,'secret') fails if salary field is of type number.

      • Correct usage: SELECT NVL(TO_CHAR(salary),'secret').

  • CASE Statement

    • Each branch must have the same type of value.

      • Example:

      • SELECT last_name AS surname, CASE WHEN salary IS NULL THEN 'secret' ELSE TO_CHAR(salary) END AS salary.


Formatting Numbers and Texts

  • Number Formatting

    • Use the TO_CHAR function with a defined mask:

      • Example: SELECT TO_CHAR(salary,'9999990.999').

  • Text Conversion

    • Convert text to uppercase and lowercase, and trim unnecessary spaces if required:

      • Example:

      • SELECT INITCAP(last_name);

      • SELECT * FROM employees WHERE UPPER(job) LIKE '%PRESIDENT%';

      • SELECT TRIM(last_name) AS last_name.


JOIN Operations

  • Types of JOIN

    • INNER, LEFT, RIGHT, FULL JOIN use usual syntax.

    • The keyword USING can be used when the field names to be joined are identical in both tables.

  • Example of JOIN

    • SELECT last_name, job_title, salary FROM employees INNER JOIN jobs USING(job_id) WHERE last_name LIKE 'K%';


Pseudonyms in SQL

  • Table Aliases

    • A space is required between the physical name and the alias (without the AS keyword).

  • Field Aliases

    • Can be introduced with or without the AS keyword.

  • Aggregate Field Aliases

    • Cannot be used in the HAVING clause but can be used in the ORDER BY clause.

  • ORDER BY Clause

    • Fields can be referenced by their order number in the SELECT statement.


Examples of Pseudonyms

  • Example with alias and HAVING:

    • SELECT department_id, COUNT(*) AS principal FROM employees GROUP BY department_id HAVING COUNT(*) < 12 ORDER BY principal;

    • Another example using ORDER BY clause with order number:

    • SELECT department_id, COUNT(*) AS main FROM employees GROUP BY department_id HAVING COUNT(*) < 12 ORDER BY 2;


Hierarchical Queries

  • Show Hierarchy:

    • SELECT LEVEL AS level, last_name AS last_name, department_id AS department FROM employees CONNECT BY manager_id = PRIOR employee_id START WITH UPPER(last_name) = 'KING' ORDER BY 3,1;

  • Hierarchical Reverse Traversal:

    • SELECT LEVEL AS level, last_name AS last_name, department_id AS department FROM employees CONNECT BY PRIOR manager_id = employee_id START WITH UPPER(last_name) = 'CHEN' ORDER BY 3,1;


View Tables

  • Definition:

    • View tables do not store physical data but can be used like real tables.

    • Stores a SELECT statement; referencing a view re-runs the SELECT statement.

  • Advantages:

    • Store frequent queries for shorter instructions in the application layer.

    • Simplify complex queries.

    • Restrict access to data.

    • Suitable for controlled data entry.


Creating View Tables

  • Syntax for creation:
    ```sql
    CREATE [OR REPLACE] [FORCE | NOFORCE] VIEW view_name [(secondary_name1, secondary_name2, …)] AS query [WITH READ ONLY | WITH CHECK OPTION];

- **Options**:  
  - **OR REPLACE**: Overwrites the definition if a view with this name exists.  
  - **FORCE**: Creates view even if referenced physical tables are not all present.  
  - **NOFORCE** (default): View is created only if all referenced physical tables exist.

---

## View Restrictions and Usage
- **Subqueries**:  
  - Query can be complex and include sub-queries, grouping, etc.  
- **Modifications**:  
  - If not defined as **WITH READ ONLY**, can modify values in the original table through the view if:  
    - Built on a single table.  
    - Does not contain **GROUP BY** or **DISTINCT**.  
    - Does not involve an aggregation function.  
- **Sorting**:  
  - Usually avoided in view definitions except for **TOP-N analysis**.  
- **Deleting Views**:  
  - To delete a view: `DROP VIEW view_table_name;`  

---

## TOP-N Analysis
- **Definition**:  
  - A common task that lists the first `n` records based on certain criteria.  
- **ROWNUM**:  
  - A pseudo-column that assigns the row number to selected rows.  
- **Incorrect Example**:  
  - Listing top salary records:  

sql
SELECT last_name, job_id, salary FROM employees WHERE ROWNUM <= 5 ORDER BY salary DESC;

  - This will select the first five records and then sort them, which is incorrect.
- **Correct Example**:  
  - Correct way to list top `n` paid employees:  

sql
SELECT * FROM (SELECT last_name, job_id, salary FROM employees ORDER BY salary DESC) emp_temp WHERE ROWNUM <= 5;

---

## Using Scripts for TOP-N Analysis
- **Script Example**:  

sql
ACCEPT piece PROMPT 'How many elements do you want?';
CREATE VIEW paidList AS SELECT emp_temp.* FROM (SELECT last_name, job_id, salary FROM employees ORDER BY salary DESC) emp_temp WHERE ROWNUM <= &piece;
SELECT * FROM paidList;
DROP VIEW paidList;
UNDEFINE piece;

---

## About PL/SQL Language
- **Overview**:  
  - PL/SQL allows variables, control structures, and reference data types to facilitate procedural programming.  
- **Difference from SQL**:  
  - SQL SELECT does not include variables, conditional statements, or loops. PL/SQL is a procedural extension developed by Oracle.

---

## Execution of PL/SQL Elements
- **Execution Process**:  
  - PL/SQL elements run on a separate engine from the SQL compiler.  
  - PL/SQL compiler detects SQL commands and forwards to SQL compiler.  
  - Translates to intermediate pseudo-code for optimization before execution.

---

## Roles in PL/SQL Language
- **Web Server**:  
  - Provides GUI and data transfer to application layers.
- **Application Server**:  
  - Supports object and database integration and structured-procedural processing.
- **Database Server**:  
  - Manages storage, query translation, and transaction management.

---

## Statement Blocks in PL/SQL
- **Block Structure**:  
  - Fundamental element includes:  
    - Declaration Part (`DECLARE`): Variable names and types.  
    - Body: Contains executable commands.  
    - Exception Handling (`EXCEPTION`): Handles errors.  
  - Structure:  

sql
[DECLARE declarations]
BEGIN
commands to be executed
[EXCEPTION exception handling]
END;

- **Example** of data input and output:  

sql
DECLARE
c INTEGER;
BEGIN
c := &a + &b;
DBMS_OUTPUT.PUT_LINE(c);
END;

---

## Data Types in PL/SQL
- **Numbers**:  
  - `NUMBER(x,y)`: Max number with `x` digits, `y` decimal places.  
  - `NUMBER(x)`: Max number with `x` digits, no decimals.  
  - `INT` = `INTEGER` = `NUMBER(38)`.  
- **Texts**:  
  - `VARCHAR2(n)`: Variable-length string of up to `n` characters (n ≤ 255).  
  - `VARCHAR(n)`: Similar to `VARCHAR2`; recommended to use `VARCHAR2`.  
  - `CHAR(n)`: Fixed-length string; errors occur for strings that exceed length.  
- **Comparison Behavior**:  
  - **CHAR**: Ignores trailing spaces on comparison.  
  - **VARCHAR/VARCHAR2**: Trailing spaces count.
- **Date and Time**:  
  - `DATE`: Represents date and time.
  - Set default date format:  

sql
ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD';

---

## Control Statements (Branching)
- **IF Statements**:  
  - Structure:  

sql
IF condition THEN
commands-instructions
[ELSIF condition THEN commands-instructions … [ELSE commands-instructions]]
END IF;

- **Logical Expression**:  
  - Conditions evaluate to three logical values.  
  - Nested IFs can occur in the instructions section, and ELSIF evaluated only if preceding conditions are false.

---

## LOOps in PL/SQL
- **General LOOP**:  
  - Structure:  

sql
LOOP
instruction;
[EXIT;]
[EXIT WHEN condition;]
END LOOP;

  - Exit conditions can be placed anywhere.
- **Counter Loop (FOR)**:  
  - Structure:  

sql
FOR loop_variable IN [REVERSE] lower_limit..upper_limit LOOP
instruction;
END LOOP;

  - Increments or decrements loop variable automatically.
- **Pretest Loop (WHILE)**:  
  - Structure:  

sql
WHILE condition LOOP
instruction;
END LOOP;

  - Executes core while the condition is true.

---

## Writing Data to User
- **DBMS Output**:  
  - **SQL Developer**: Use the DBMS Output window to simulate user screen.  
  - Activate via **VIEW** menu > **Dbms Output**.  
  - Example of output:  

sql
dbms_output.put_line('fruits: ' || fruit || ' pieces: ' || pieces);

---

## Example of Statement Block in PL/SQL
- Illustrates Fibonacci sequence.  

sql
DECLARE
v1 NUMBER(3);
v2 NUMBER(3);
v3 NUMBER(3);
BEGIN
v1 := 1;
v2 := 1;
DBMS_OUTPUT.PUT_LINE(v1);
DBMS_OUTPUT.PUT_LINE(v2);
FOR i IN 1..10 LOOP
v3 := v1 + v2;
DBMS_OUTPUT.PUT_LINE(v3);
v1 := v2;
v2 := v3;
END LOOP;
END;

---

## Record Data Types
- **Definition**:  
  - Unites different types of variables; akin to struct in C.  
  - Declaration:  

sql
DECLARE
TYPE record_type_name IS RECORD (
columnname1 type1,
[, columnname2 type2]
);
variable_name record_type_name;

---

## Reference Data Types
- **Purpose**:  
  - Allows variable types to match another variable, table field type, or record type of a table.  
  - Example for flexible programming:  

sql
DECLARE
variable1 variable8%TYPE;
variable2 tablename.fieldname%TYPE;
variable3 table_name%ROWTYPE;

---

## Cursors for Line-by-Line Processing
- **Definition**:  
  - Cursors store results from SELECT, allowing one-row processing.  
  - SQL operates globally, affecting all rows matching conditions in a single command.
- **Implicit Cursors**:  
  - Automatically managed by PL/SQL for DML and DDL statements.

---

## Using Explicit Cursors
- **Example (Basic)**:  

sql
DECLARE
department employees.department_id%TYPE;
f NUMBER(5);
CURSOR department_cur IS
SELECT department_id, COUNT(*) FROM employees GROUP BY department_id;
BEGIN
…
END;

- **Advanced**:  

sql
DECLARE
…
BEGIN
OPEN department_cur;
FETCH department_cur INTO department, f;
WHILE department_cur%FOUND LOOP
DBMS_OUTPUT.PUT_LINE('departmentID: ' || department || ' staff: ' || f);
FETCH department_cur INTO department, f;
END LOOP;
END;

---

## Differences in Cursor Modes
- **Explicit Cursors**:  
  - Requires separate variables for each field.  
  - Named record fields mandatory; no need to open or fetch beforehand for records.  
- **Cursor Attributes**:  
  - `%FOUND`: true if the last FETCH found a record.  
  - `%NOTFOUND`: true if no record processed.  
  - `%ROWCOUNT`: count of fetched rows.  
  - `%ISOPEN`: true if the cursor is open (false for implicit cursors).

---

## FOR UPDATE Cursors
- **Locking Rows**:  
  - Cursors created with **FOR UPDATE** allow modifying/deleting examined records.  
  - **NOWAIT** specifies no waiting for locked lines.
- **Example**:  

sql
CREATE TABLE worker AS SELECT * FROM employees;
DECLARE
CURSOR worker_cur IS
SELECT employee_id, last_name, salary FROM worker WHERE job_id='IT_PROG' FOR UPDATE NOWAIT;
id worker.employee_id%TYPE;
name worker.last_name%TYPE;
pay worker.salary%TYPE;
BEGIN
OPEN worker_cur;
LOOP
FETCH worker_cur INTO id, name, pay;
EXIT WHEN worker_cur%NOTFOUND;
pay := pay * 1.2;
UPDATE worker SET salary = pay WHERE CURRENT OF worker_cur;
DBMS_OUTPUT.PUT_LINE(name || ': ' || pay);
END LOOP;
CLOSE worker_cur;
END;

---

## Exception Handling in PL/SQL
- **Definition**:  
  - An error event that halts execution of the block.  
  - Custom exceptions can be declared by the user.  
- **System Exceptions**:  
  - Triggered by the runtime system naturally.  
- **Declaring Exceptions**:  

sql
DECLARE
exception_name EXCEPTION;
IF boolean_expression THEN
RAISE exception_name;
END;

- **Handling Errors**:  

sql
BEGIN
…
EXCEPTION
WHEN No_Data_Found THEN
message;
WHEN Too_Many_Rows THEN
message;
WHEN Others THEN
message;
END;
```

  • Access error code and message through SQLCODE and SQLEERRM variables.


Conclusion

  • Database Systems:

    • Focus on the use of SQL, subprograms, packages, triggers, and exception handling in PL/SQL to effectively interact with databases.