Database Foreign Key Constraints, Joins, and SQL Operators

Entity-Relationship Diagrams and Relational Schema Conversion

  • Entity-Relationship Diagram (ERD) Fundamentals:
    • ERDs are graphical representations created based on organization business rules.
    • They model the specific data an organization needs to store and document structural relationships between entities.
    • Entity: Represents real-world objects or concepts (e.g., SUBJECT, LECTURER).
    • Attribute: Represents a specific property or characteristic of an entity (e.g., SubjectCode, Title, CreditPoints, LecId, LecName, Age, LecOffice).
    • Relationship: Defines logical associations between entities (e.g., Convened by).

Entity Relationship Diagram showing SUBJECT, LECTURER, and attributes

  • Rules for Converting an ERD to a Relational Model:
    • Step 1: Convert each individual Entity into a Relation (Database Table).
    • Step 2: Add all entity attributes as Columns (Fields) within the newly formed table.
    • Step 3: Designate the entity's primary identifiers as Primary Keys (PK) in the matching table schema.
    • Step 4: Map relationships by placing a Foreign Key (FK) in the table located at the "Many" end of a M:1M:1 (Many-to-One) relationship.
      • The Foreign Key values must match existing Primary Key values in the referenced parent table, or contain a NULL value.

ERD mapping to relational tables with foreign key reference

  • Relational Schema Definitions:

    • LECTURER Relation Schema: LECTURER (LecId, LecName, Age) where LecId is the Primary Key.
    • SUBJECT Relation Schema: SUBJECT (SubjectCode, Title, CreditPoints, LecId) where SubjectCode is the Primary Key, and LecId is a Foreign Key referencing LECTURER.
  • SQL DDL Create Table Implementation:

    • The relational schema serves as the specification for database physical design using Data Definition Language (DDL) statements.
Create Table LECTURER (
  LecId number,
  LecName varchar(50),
  Age number,
  Primary Key (LecId)
);

Create Table SUBJECT (
  SubjectCode varchar(10),
  Title varchar(100),
  CreditPoints number,
  LecId number,
  Primary Key (SubjectCode),
  Foreign Key (LecId) References LECTURER
);

Foreign Key Constraints and Referential Integrity

  • Parent and Child Relationships:
    • In a Foreign Key to Primary Key (FK−PKFK - PK) relationship:
      • Parent: The table containing the Primary Key column at the "One" end of a M:1M:1 relationship. A child has exactly one parent.
      • Child: The table containing the Foreign Key column at the "Many" end of a M:1M:1 relationship. A parent may be linked to many children.

Foreign Key validation example in SUBJECT table

  • Foreign Key Constraint Enforcement:
    • The Foreign Key constraint forces the Relational Database Management System (RDBMS) to validate all data entered into a Foreign Key column.
    • If a value entered in a Foreign Key column does not match an existing Primary Key in the referenced parent table, the database rejects the operation and throws an error.
    • Successful Insertion Example:
INSERT INTO SUBJECT (SubjectCode, Title, CreditPoints, LecId)
VALUES ('INF11007', 'EBIS', 12.5, 345);
-- Returns: OK. 1 rows (1 row added successfully)
*   **Failed Insertion Example (Parent Key Violation)**:
INSERT INTO SUBJECT (SubjectCode, Title, CreditPoints, LecId)
VALUES ('AST80016', 'Astrophysics', 12.5, 222);
-- Returns Error: ORA-02291: integrity constraint (s1234567.SYS_C002969703) violated - parent key not found
*   **Explanation of `ORA-02291`**: This error occurs because the Foreign Key value `222` does not exist as a Primary Key (`LecId`) in the parent table `LECTURER`.
  • Parent/Child Deletion Rules and Referential Integrity:
    • Default Oracle Behavior: A parent row cannot be deleted if active child records reference it. This prevents child rows from becoming "orphaned".
    • A parent record can only be deleted once all associated child records are deleted or modified.
    • Deletion Error Scenario:
-- Add lecturer record
INSERT INTO LECTURER (LecId, LecName, Age)
VALUES (345, 'Carol Kent', 34);

-- Add subject record pointing to lecturer 345
INSERT INTO SUBJECT (SubjectCode, Title, CreditPoints, LecId)
VALUES ('INF11007', 'EBIS', 12.5, 345);

-- Attempt to delete lecturer record
DELETE FROM LECTURER WHERE LecId = 345;
-- Returns Error: ORA-02292: integrity constraint (s1234567.SYS_C002969703) violated - child record found
*   **Explanation of `ORA-02292`**: This error indicates that deleting the parent record would orphan child records currently referencing `LecId = 345`.

Handling NULL Values and NOT NULL Constraints

  • Null Foreign Keys:
    • By default, Foreign Key columns accept NULL values unless explicit constraints are defined.
    • NULL foreign keys accommodate business scenarios where a relationship is optional or currently unassigned (e.g., creating a new unit INF21009 'Advanced Facebook' before a convener is allocated).

Table showing NULL Foreign Key in SUBJECT entity

INSERT INTO SUBJECT (SubjectCode, Title, CreditPoints, LecId)
VALUES ('INF21009', 'Advanced Facebook', 12.5, Null);
-- Insertion succeeds because LecId permits NULL values by default.
  • Enforcing NOT NULL Constraints:
    • If business rules dictate that every record must have a relationship (e.g., "Every subject MUST have a convener"), a NOT NULL constraint must be applied to the Foreign Key column.
    • Constraints are defined during initial table creation or added later via ALTER TABLE DDL queries.
Create Table SUBJECT (
  SubjectCode varchar(10),
  Title varchar(100),
  CreditPoints number,
  LecId number Not Null,
  Primary Key (SubjectCode),
  Foreign Key (LecId) References LECTURER
);
  • Violating NOT NULL Constraints:
    • Attempting to insert a NULL value into a column protected by a NOT NULL constraint produces an RDBMS error:
INSERT INTO SUBJECT (SubjectCode, Title, CreditPoints, LecId)
VALUES ('INF21009', 'Advanced Facebook', 12.5, Null);
-- Returns Error: ORA-01400: cannot insert NULL into (s1234567.SUBJECT.LECID)
  • Primary Key vs. Column Constraints:
    • Multiple columns within a table can enforce NOT NULL constraints.
    • Primary Keys implicitly require non-null unique values and do not require explicit NOT NULL declarations.

ERD Participation Constraints vs. Cardinality

  • Participation Symbols in ERDs:
    • Mandatory Participation (MUST): Drawn as a vertical line | on the relationship line. Indicates that an entity instance must participate in the relationship.
    • Optional Participation (MAY): Drawn as a circle O on the relationship line. Indicates that participation in the relationship is optional.

Participation constraint notations in ERDs

  • Comparison Between Cardinality and Participation Constraints:

    • Cardinality Constraints: Critical to structural design. They directly dictate the total number of tables developed in the relational database model and determine foreign key placements.
    • Participation Constraints: Do not alter the total number of tables or columns in the relational schema. They strictly define whether columns require NOT NULL constraints during physical database implementation.
  • Participation Rules and Operational Insertion Dilemmas:

    • The "Many" end of a relationship should generally feature optional participation (MAY). For example, a parent may have many children.
    • Mandatory Participation Deadlock: Enforcing mandatory participation at both ends of a relationship creates database insertion deadlocks:
      • If an ERD asserts that a child must have a parent AND a parent must have a child, inserting initial records becomes mathematically cyclical and impossible under standard constraint checks.
      • Parent records cannot be inserted without pre-existing child records, and child records cannot be inserted without pre-existing parent records.
      • Database developers temporarily disable double mandatory constraints when populating initial data sets and re-enable them afterwards, though this is not recommended for standard daily database operations.

SQL Select Expressions, Calculations, Aliases, and Table Qualification

  • Calculations and Arithmetic Expressions in SELECT:
    • The SELECT statement can contain computed expressions and arithmetic calculations alongside standard attribute names.
SELECT Name, Test1, Test2, Test1+Test2
FROM StudentResults;
  • Sorting Query Results by Column Position:
    • Results can be sorted by specifying the positional column number in the ORDER BY clause.
SELECT Name, Test1, Test2, Test1+Test2
FROM StudentResults
ORDER BY 4 DESC;
-- Sorts the result set by the 4th expression (Test1+Test2) in descending order.
  • Column Headings and Aliases:
    • Alternative column headers apply strictly to the returned result set without altering underlying physical schemas.
    • The AS keyword is optional.
    • Aliases containing spaces or special characters must be enclosed in double quotation marks "".
    • Unquoted single-word aliases convert to default formatting.

```sql -- Examples of column aliasing SELECT Name, Test1, Test2, Test1+Test2 As