(Slide 5)
Before diving into SQL logic, the lecture briefly reviews Foreign Key constraints using a CUSTOMER and ORDER table relationship.
Business Rule: A customer ID can only be deleted from the CUSTOMER table if it is not found in the ORDER table.
ER Diagram: CUSTOMER to ORDER (1:M Relationship)
Defining the Constraints (SQL Examples):
When defining a Foreign Key, you can specify what happens to the ORDER table if the related CustomerID in the CUSTOMER table is updated or deleted:
ON UPDATE RESTRICT: The update is blocked. A Customer ID can only be changed if there are no matching records in the ORDER table.
ON UPDATE CASCADE: The update flows through. If you change CustomerID 1 to 50 in CUSTOMER, every row in the ORDER table with CustomerID 1 automatically updates to 50.
ON UPDATE SET NULL: The update sets the foreign key to NULL. If you change CustomerID 1, all matching rows in ORDER have their CustomerID set to NULL.
ON UPDATE SET DEFAULT: The update sets the foreign key to a predefined default value (e.g., 999).
A View is a logical table based on one or more underlying tables (or other views).
It does not contain data of its own. Think of it as a window through which you can view or change data from the physical base tables.
The view is stored in the database's data dictionary as a SELECT statement.
Base Table: The actual physical table where raw data is inserted and stored.
Virtual Table: A table constructed automatically by the DBMS as needed. It is not maintained as real data.
Dynamic View: A virtual table that is created dynamically upon request. Its definition is stored in the catalog, and its contents are generated every time a user runs a query that uses the view.
Materialized View: A copy or replica of data based on an SQL query. This exists as a physical table on the disk. Care must be taken to keep it synchronized with its base tables.
OR REPLACE: Recreates the view if it already exists.
FORCE: Creates the view even if the base tables do not exist yet (useful for scripting).
NOFORCE: (Default) Only creates the view if the base tables exist.
alias: Column names for the expressions selected by the view.
WITH CHECK OPTION: Ensures that inserted or updated rows meet the view's WHERE condition.
WITH READ ONLY: Prevents any DML operations on the view.
Rules for Creating a View:
The subquery cannot contain an ORDER BY clause.
The subquery can contain complex joins, groups, and subqueries.
Example 1: Creating a Simple View
Create a view empvu10 that only shows employees in department 10.
CREATE VIEW empvu10AS SELECT empno, ename, job FROM emp WHERE deptno = 10;
(Note: The DESCRIBE command can be used to view the structure of this view).
Example 2: Creating a Complex View
Create a view dept_sum_vu that displays summarized salary data (MIN, MAX, AVG) grouped by department name from two tables (emp and dept).
CREATE VIEW dept_sum_vu (name, minsal, maxsal, avgsal) AS SELECT d.dname, MIN(e.sal), MAX(e.sal), AVG(e.sal) FROM emp e, dept d WHERE e.deptno = d.deptnoGROUP BY d.dname;
To change the definition of a view without dropping it and regranting privileges, use CREATE OR REPLACE VIEW.
CREATE OR REPLACE VIEW empvu10 (employee_number, employee_name, job_title) AS SELECT empno, ename, job FROM emp WHERE deptno = 10;
(Note: The aliases employee_number, employee_name, job_title are defined in the CREATE VIEW clause and must match the order of columns in the SELECT subquery).
WITH CHECK OPTION:
This clause ensures that INSERT and UPDATE operations performed through the view do not create rows that the view cannot select. It enforces integrity and validation.
Example: We create a view empvu20 that only selects employees in department 20.
CREATE OR REPLACE VIEW empvu20AS SELECT * FROM emp WHERE deptno = 20WITH CHECK OPTION CONSTRAINT empvu20_ck;
Behavior: If we try to update the department of an employee in this view from 20 to 10, the database rejects it with an error: ORA-01402: view WITH CHECK OPTION where-clause violation. This is because if the department changed to 10, the employee would disappear from the view, which violates the check option.
WITH READ ONLY:
This option denies ALL DML operations (INSERT, UPDATE, DELETE) on the view. It is extremely useful for security.
CREATE OR REPLACE VIEW empvu10(employee_number, employee_name, job_title) AS SELECT empno, ename, job FROM emp WHERE deptno = 10WITH READ ONLY;
(Note: Any attempt to perform an update on this view will result in an Oracle Server error).
The CASE statement allows you to perform IF-THEN-ELSE logic directly inside your SQL query to generate conditional results.
Syntax:
CASE [expression] WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 ... ELSE result_nEND case_name
(Note: expression is optional, condition and result are mandatory, case_name is optional).
Example 1: Replacing Product Description with #### for a specific ProductLine
SELECT CASE WHEN ProductLine = 1 THEN ProductDescription ELSE '####' END AS ProductDescription FROM Product_T;
Example 2: Categorizing Salaries
SELECT salary, CASE WHEN salary < 2000 THEN 'Category 1' WHEN salary < 3000 THEN 'Category 2' WHEN salary < 4000 THEN 'Category 3' ELSE 'Category 4' END as CategoryFROM employees;
Inside a stored procedure, the RETURN keyword is used to exit the subprogram immediately and pass control back to the calling statement. Any code written after RETURN in the procedure is skipped.
CREATE OR REPLACE TRIGGER orders_after_updateAFTER UPDATEON ordersFOR EACH ROWDECLARE v_username varchar2(10);BEGIN -- Find username of the person performing the UPDATE SELECT user INTO v_username FROM dual; -- Insert an audit record into an audit table INSERT INTO orders_audit ( order_id, quantity_before, quantity_after, username ) VALUES ( :new.order_id, :old.quantity, :new.quantity, v_username );END;
(Note: :OLD and :NEW are special trigger keywords allowing you to access data before and after the update occurs).
Views are created on base tables to improve data integrity, secure data, and simplify queries. They are virtual windows to data.
Advanced SQL Operations like the CASE statement allow you to perform IF-THEN-ELSE logic right inside your SQL queries, while UNION allows combining results from different queries.
Triggers and Routines (like Stored Procedures) are programmable extensions to SQL. They allow you to enforce business rules, validate data, and automate complex logic directly at the database level, saving application programmers from having to write this logic in their code.
Stored Procedures are stored and executed upon manual request, while Triggers are fire automatically based on INSERT, UPDATE, or DELETE events.