Module 03: Lesson 05 - Advanced SQL Commands

Course Curriculum & Learning Objectives

  • Course Identification:

    • Course Code: IS311 (Information Management)

    • Term: First Semester, Academic Year 2021–2022

    • Institution: Davao del Norte State College, Institute of Computing

    • Module: Module 03 (Database Development and Implementation)

    • Lesson: Lesson 05 (Advanced SQL Commands)

    • Instructional Time Frame: Week 14

  • Lesson Learning Outcomes:

    • Differentiate between single-table and multiple-table queries using standard SQL commands.

    • Define the three fundamental types of join commands and write syntactically correct SQL statements for each.

    • Differentiate between non-correlated and correlated subqueries, identifying the specific operational conditions under which each must be written.

    • Demonstrate the implementation of referential integrity constraints using SQL commands.

    • Practice advanced SQL commands and multi-table queries within realistic project development scenarios.

  • Scope of Advanced Topics:

    • Utilization of SQL relational set operators (UNION, INTERSECT, and MINUS) to merge distinct query result sets.

    • Advanced data extraction across relational tables using specialized JOIN operators.

    • Implementation of diverse subquery styles within the SELECT statement structure.

    • Application of built-in SQL functions for complex data manipulation.

Practical Analysis Activity: Data Consolidation

  • Context and Operational Scenario:

    • Role: Data encoder operating within an enterprise Human Resources (HR) department.

    • Assignment: Compile an annual report to calculate the thirteenth (13th13^{\text{th}}) month pay for all company employees.

    • Challenge: Annual operational data is dispersed across voluminous, accumulated files, requiring programmatic consolidation and extraction across distinct data structures.

  • Procedural Requirements:

    • Formulate systematic operational workflows to organize, select, and merge disparate records while optimizing computational runtime and organizational resources.

    • Construct an end-to-end flowchart visually depicting every process step required to consolidate the employee records into a unified dataset.

Relational Join Foundations & ANSI Standards

  • Definition and Relational Mechanism:

    • A relational join operation merges rows from two or more tables based on common attributes, generating a composite result set based on designated criteria.

    • Join operations yield results satisfying one of three core conditions:

    • Rows possessing common values across common columns (NATURAL JOIN).

    • Rows satisfying an explicitly defined condition based on equality or inequality.

    • Rows possessing common values across common columns combined with rows containing unmatched attribute values (OUTER JOIN).

  • Primary Join Classifications:

    • Inner Joins: Traditional join operations selecting exclusively those rows that satisfy a specified criterion.

    • Equijoin (Natural Join): The join condition is defined by an equality comparison (==.

    • Theta Join: The join condition is defined using an inequality operator (<<, >>, <=<=, >=>=, or <><>.

    • Outer Joins: Specialized join operations that return all matching rows plus unmatched rows with null-filled attributes for one or both joined tables.

  • ANSI SQL Standard Join Syntax (Table 3.7):

    • Cross Join:

    • Classification: Cross join

    • Legacy Syntax: SELECT * FROM T1, T2

    • ANSI SQL Syntax: SELECT * FROM T1 CROSS JOIN T2

    • Operational Description: Evaluates and returns the Cartesian product of table T1 and table T2.

    • Old-Style Join:

    • Classification: Inner join

    • Syntax: SELECT * FROM T1, T2 WHERE T1.C1 = T2.C1

    • Operational Description: Returns strictly those rows satisfying the equality condition specified in the WHERE clause.

    • Natural Join:

    • Classification: Inner join

    • ANSI SQL Syntax: SELECT * FROM T1 NATURAL JOIN T2

    • Operational Description: Returns rows matching across common columns sharing identical names and compatible data types, automatically eliminating redundant duplicate columns.

    • Join Using:

    • Classification: Inner join

    • ANSI SQL Syntax: SELECT * FROM T1 JOIN T2 USING (C1)

    • Operational Description: Returns rows possessing identical values in the specific column designated in the USING clause.

    • Join On:

    • Classification: Inner join

    • ANSI SQL Syntax: SELECT * FROM T1 JOIN T2 ON T1.C1 = T2.C1

    • Operational Description: Returns rows meeting the explicit join condition declared within the ON clause.

    • Left Outer Join:

    • Classification: Outer join

    • ANSI SQL Syntax: SELECT * FROM T1 LEFT OUTER JOIN T2 ON T1.C1 = T2.C1

    • Operational Description: Returns all matching rows plus all unmatched rows from the left table (T1).

    • Right Outer Join:

    • Classification: Outer join

    • ANSI SQL Syntax: SELECT * FROM T1 RIGHT OUTER JOIN T2 ON T1.C1 = T2.C1

    • Operational Description: Returns all matching rows plus all unmatched rows from the right table (T2).

    • Full Outer Join:

    • Classification: Outer join

    • ANSI SQL Syntax: SELECT * FROM T1 FULL OUTER JOIN T2 ON T1.C1 = T2.C1

    • Operational Description: Returns all matching rows alongside all unmatched rows from both tables (T1 and T2).

  • Vendor Support Caveat:

    • Database Management System (DBMS) vendors do not provide uniform support for all ANSI standard join syntax variations; specific implementations must account for vendor-level dialect limitations.

Detailed Syntax and Execution of Join Types

  • Cross Join (Cartesian Product):

    • Mathematical Relational Product: Evaluates every row in the first table against every row in the second table.

    • Output Row Volume: Total output rows equal the cardinality of the first table multiplied by the cardinality of the second table (RowsTotal=RowsT1×RowsT2\text{Rows}_{\text{Total}} = \text{Rows}_{T1} \times \text{Rows}_{T2}.

    • Standard Syntax: sql SELECT column-list FROM table1 CROSS JOIN table2 &nbsp;&nbsp;&nbsp;&nbsp;

  • Execution Example on Relational Database: sql SELECT * FROM INVOICE CROSS JOIN LINE; &nbsp;&nbsp;&nbsp;&nbsp;

    • When the INVOICE table contains 88 rows and the LINE table contains 1818 rows, the Cartesian product yields exactly 8×18=1448 \times 18 = 144 rows.

  • Attribute Projection Example: sql SELECT INVOICE.INV_NUMBER, CUS_CODE, INV_DATE, P_CODE FROM INVOICE CROSS JOIN LINE; &nbsp;&nbsp;&nbsp;&nbsp;

  • Legacy Comma-Separated Alternative: sql SELECT INVOICE.INV_NUMBER, CUS_CODE, INV_DATE, P_CODE FROM INVOICE, LINE; &nbsp;&nbsp;&nbsp;&nbsp;

  • Old-Style Inner Join:

    • Structural Mechanism: Lists joined tables inside the FROM clause and places relational linking conditions entirely inside the WHERE clause.

    • Standard Syntax: sql SELECT column-list FROM table1, table2 WHERE join-condition &nbsp;&nbsp;&nbsp;&nbsp;

  • Execution Example: sql SELECT P_CODE, P_DESCRIPT, P_PRICE, V_NAME FROM PRODUCT, VENDOR WHERE PRODUCT.V_CODE = VENDOR.V_CODE; &nbsp;&nbsp;&nbsp;&nbsp;

    • Operational Processing Rules:

    • Order of Evaluation: When three or more tables are joined, the DBMS evaluates joins sequentially from left to right, processing two tables at a time. The intermediate result of the first join (e.g., T1⋈T2T1 \Join T2) is subsequently joined with the third table (T3T3).

    • Join Condition Cardinality: For NN tables participating in an old-style join, exactly N−1N - 1 join conditions are required.

    • Logical Operator Chaining: Multiple join conditions must be connected using the AND logical operator.

    • Primary Key to Foreign Key Mapping: Standard join conditions establish an equality comparison between the Primary Key (PK) of one table and the corresponding Foreign Key (FK) of the related table.

  • Natural Join (NATURAL JOIN):

    • Elimination of Redundant Attributes: Compares all columns sharing identical names across both tables, restricts results to matching values, and eliminates duplicate column projections automatically.

    • Relational Processing Tasks:

    • Inspects both tables to detect common attributes possessing identical names and compatible data types.

    • Filters records, returning exclusively rows with identical values in the identified common attributes.

    • If no identical column names exist between tables, the operation degenerates into a Cartesian relational product.

    • Standard Syntax: sql SELECT column-list FROM table1 NATURAL JOIN table2 &nbsp;&nbsp;&nbsp;&nbsp;

  • Two-Table Execution Example: sql SELECT CUS_CODE, CUS_LNAME, INV_NUMBER, INV_DATE FROM CUSTOMER NATURAL JOIN INVOICE; &nbsp;&nbsp;&nbsp;&nbsp;

    • Output: Produces 88 rows matching customers Dunne (1001110011), Smith (1001210012), Orlando (1001410014), O'Brian (1001510015), and Farriss (1001810018).

  • Multi-Table Natural Join Example: sql SELECT INV_NUMBER, P_CODE, P_DESCRIPT, LINE_UNITS, LINE_PRICE FROM INVOICE NATURAL JOIN LINE NATURAL JOIN PRODUCT; &nbsp;&nbsp;&nbsp;&nbsp;

    • Output: Produces 1818 detailed invoice line rows.

  • Elimination of Table Qualifiers: In a NATURAL JOIN, common attributes (such as CUS_CODE or INV_NUMBER) must not include table qualifiers or prefixes (e.g., writing CUSTOMER.CUS_CODE will cause an error).

Result set for Natural Join
  • Join Using Clause (JOIN USING):

    • Explicit Common Column Designation: Explicitly specifies which identical column should be utilized for matching, bypassing other potentially matching column names.

    • Prerequisite: The attribute named in the USING clause must exist in both joining tables with compatible data types.

    • Standard Syntax: sql SELECT column-list FROM table1 JOIN table2 USING (common-column) &nbsp;&nbsp;&nbsp;&nbsp;

  • Execution Example: sql SELECT INV_NUMBER, P_CODE, P_DESCRIPT, LINE_UNITS, LINE_PRICE FROM INVOICE JOIN LINE USING (INV_NUMBER) JOIN PRODUCT USING (P_CODE); &nbsp;&nbsp;&nbsp;&nbsp;

  • Qualifier Rule: Columns declared inside the USING clause cannot be prefixed with table qualifiers in the SELECT projection list.

Join Using results
  • Join On Clause (JOIN ON):

    • Arbitrary Condition Binding: Joins tables regardless of whether they share identical column names by defining explicit comparison expressions.

    • Standard Syntax: sql SELECT column-list FROM table1 JOIN table2 ON join-condition &nbsp;&nbsp;&nbsp;&nbsp;

  • Multi-Table Execution Example: sql SELECT INVOICE.INV_NUMBER, PRODUCT.P_CODE, P_DESCRIPT, LINE_UNITS, LINE_PRICE FROM INVOICE JOIN LINE ON INVOICE.INV_NUMBER = LINE.INV_NUMBER JOIN PRODUCT ON LINE.P_CODE = PRODUCT.P_CODE; &nbsp;&nbsp;&nbsp;&nbsp;

  • Ambiguity Resolution Rule: Unlike NATURAL JOIN or JOIN USING, the JOIN ON clause requires explicit table qualifiers for any attribute appearing in more than one table. Omitting qualifiers yields a "column ambiguously defined" DBMS runtime error.

Join On results

Advanced Outer Joins

  • Architectural Principle of Outer Joins:

    • Designed to preserve non-matching records that standard inner joins exclude.

    • Table Order Sensitivity: The physical order in the FROM clause defines table positioning. The first table is designated as the left table; the second table is designated as the right table.

    • Multi-Table Outer Joins: When evaluating three or more tables, the intermediate relational output from joining the first two tables serves as the left table, while the third table represents the right table.

  • Left Outer Join:

    • Operational Mechanism: Returns all rows satisfying the join condition plus every unmatched record from the left table, populating the attributes of the right table with NULL.

    • Standard Syntax: sql SELECT column-list FROM table1 LEFT [OUTER] JOIN table2 ON join-condition &nbsp;&nbsp;&nbsp;&nbsp;

  • Comprehensive Execution Query: sql SELECT P_CODE, VENDOR.V_CODE, V_NAME FROM VENDOR LEFT JOIN PRODUCT ON VENDOR.V_CODE = PRODUCT.V_CODE; &nbsp;&nbsp;&nbsp;&nbsp;

  • Result Characteristics:

    • Generates 1919 total rows.

    • Retains active vendors with matching products (e.g., Rubicon Systems, Gomez Bros., Randsets Ltd., ORDVA, Inc., Bryson, Inc., D&E Supply).

    • Retains unmatched vendors with null product codes (P_CODE = NULL): Dome Supply (2256722567), SuperLoo, Inc. (2122621226), Brackman Bros. (2400424004), Damal Supplies (2550125501), and B&K, Inc. (2544325443).

Left Join results
  • Right Outer Join:

    • Operational Mechanism: Returns all rows satisfying the join condition plus every unmatched record from the right table, populating the attributes of the left table with NULL.

    • Standard Syntax: sql SELECT column-list FROM table1 RIGHT [OUTER] JOIN table2 ON join-condition &nbsp;&nbsp;&nbsp;&nbsp;

  • Comprehensive Execution Query: sql SELECT P_CODE, VENDOR.V_CODE, V_NAME FROM VENDOR RIGHT JOIN PRODUCT ON VENDOR.V_CODE = PRODUCT.V_CODE; &nbsp;&nbsp;&nbsp;&nbsp;

  • Result Characteristics:

    • Generates 1616 total rows.

    • Preserves inventory products lacking associated vendor records (V_CODE = NULL, V_NAME = NULL): product codes PVC23DRT and 23114-AA.

Right Join results
  • Full Outer Join:

    • Operational Mechanism: Combines the operational effects of both Left and Right outer joins, returning all matching records alongside unmatched records from both tables.

    • Standard Syntax: sql SELECT column-list FROM table1 FULL [OUTER] JOIN table2 ON join-condition &nbsp;&nbsp;&nbsp;&nbsp;

  • Comprehensive Execution Query: sql SELECT P_CODE, VENDOR.V_CODE, V_NAME FROM VENDOR FULL JOIN PRODUCT ON VENDOR.V_CODE = PRODUCT.V_CODE; &nbsp;&nbsp;&nbsp;&nbsp;

  • Result Characteristics:

    • Generates 2121 total rows.

    • Preserves both the unmatched vendor records (55 vendors without products) and unmatched product records (22 products without vendors).

Full Join results

SQL Subqueries and Nested Query Structures

  • Fundamental Principles of Subqueries:

    • Definition: A SELECT statement embedded inside another enclosing SQL statement.

    • Nomenclature: The primary top-level query is the outer query; the nested interior query is the inner query.

    • Syntactic Enclosure: Subqueries are enclosed within parentheses (...).

    • Processing Pipeline: The DBMS executes the inner subquery first; the resulting output acts directly as intermediate input data evaluated by the outer query.

    • Relational Role: Solves multi-stage information requirements where query constraints depend on dynamic data points that are unknown prior to execution.

  • WHERE Clause Subqueries:

    • Structural Positioning: Positioned on the right-hand side of a comparison operator inside the WHERE clause.

    • Scalar Output Constraint: When paired with standard comparison operators (==, >>, <<, >=>=, <=<=, <><>, the subquery must evaluate to a single scalar value (1 column×1 row1\text{ column} \times 1\text{ row}.

    • Data Type Compatibility: The scalar value returned by the inner query must match the data type of the attribute compared on the left-hand side.

    • Runtime Error Hazard: If an inner subquery evaluated against a scalar operator yields multiple rows, the DBMS aborts execution and generates an error.

    • Single-Value Aggregate Example: sql SELECT P_CODE, P_PRICE FROM PRODUCT WHERE P_PRICE >= (SELECT AVG(P_PRICE) FROM PRODUCT); &nbsp;&nbsp;&nbsp;&nbsp;

    • Identifies inventory items priced at or above the computed product average price: product codes 11QER/31 (109.99109.99), 2232/QTY (109.92109.92), 2232/QWE (99.8799.87), 89-WRE-Q (256.99256.99), and WR3/TT3 (119.95119.95).

  • Multi-Table Join Integration Example: sql SELECT DISTINCT CUS_CODE, CUS_LNAME, CUS_FNAME FROM CUSTOMER JOIN INVOICE USING (CUS_CODE) JOIN LINE USING (INV_NUMBER) JOIN PRODUCT USING (P_CODE) WHERE P_CODE = (SELECT P_CODE FROM PRODUCT WHERE P_DESCRIPT = 'Claw hammer'); &nbsp;&nbsp;&nbsp;&nbsp;

  • Identifies customers who purchased a claw hammer: customer 1001110011 (Leona Dunne) and customer 1001410014 (Myron Orlando).

Where subquery examples
  • FROM Clause Subqueries (Inline Views / Virtual Tables):

    • Relational Underpinning: Because any valid SELECT statement produces a relational table structure, a subquery can be placed inside the FROM clause to act as a dynamic virtual table.

    • Application Scenario: Identifying records satisfying multiple simultaneous operational criteria across child tables without creating persistent intermediary structures.

    • Dual-Condition Purchase Execution Example: sql SELECT DISTINCT CUSTOMER.CUS_CODE, CUSTOMER.CUS_LNAME FROM CUSTOMER, (SELECT INVOICE.CUS_CODE FROM INVOICE NATURAL JOIN LINE WHERE P_CODE = '13-Q2/P2') CP1, (SELECT INVOICE.CUS_CODE FROM INVOICE NATURAL JOIN LINE WHERE P_CODE = '23109-HB') CP2 WHERE CUSTOMER.CUS_CODE = CP1.CUS_CODE AND CP1.CUS_CODE = CP2.CUS_CODE; &nbsp;&nbsp;&nbsp;&nbsp;

  • Execution Mechanics:

    • Subquery CP1 isolates all customer codes purchasing product 13-Q2/P2.

    • Subquery CP2 isolates all customer codes purchasing product 23109-HB.

    • The outer query joins the base table CUSTOMER with virtual tables CP1 and CP2, matching records on CUS_CODE.

    • Output: Resolves to customer 1001410014 (Orlando).

From subquery examples
  • Attribute List Subqueries (Inline Subqueries):

    • Structural Positioning: Placed directly within the SELECT column projection list.

    • Strict Scalar Rule: The inline subquery must evaluate to exactly one single scalar value per processed row; multiple returned rows or columns trigger an execution fault.

    • Repeated Scalar Value: The computed scalar value (e.g., an overall table average) is duplicated identically across every returned row.

    • Column Alias Restriction: An alias declared in the SELECT list (such as AS AVGPRICE) cannot be referenced inside mathematical expressions within the same SELECT clause.

    • DBMS Parsing Mechanism: The DBMS compiles and parses the entire attribute projection list simultaneously before establishing alias bindings for the result set.

    • Mandatory Workaround: The full subquery expression must be written out completely within the calculation.

    • Inline Subquery Execution Example: sql SELECT P_CODE, P_PRICE, (SELECT AVG(P_PRICE) FROM PRODUCT) AS AVGPRICE, P_PRICE - (SELECT AVG(P_PRICE) FROM PRODUCT) AS DIFF FROM PRODUCT; &nbsp;&nbsp;&nbsp;&nbsp;

  • Quantitative Output Structure:

    • Evaluates the global average product price as 56.421249210834556.4212492108345.

    • Computes the individual price variance (DIFF) for every item: e.g., product 11QER/31 (109.99109.99) yields a positive difference of +53.56874865293503+53.56874865293503, whereas product 13-Q2/P2 (14.9914.99) yields a negative variance of −41.43124943971634-41.43124943971634.

Inline subquery example

Practical Implementation Assessment Requirements

  • Entity and Attribute Naming Conventions:

    • Entity (Table) Naming Rule: Every declared entity name must begin with the first three (33) characters of the student's First Name followed by an underscore (e.g., a student named John creates tables named joh_ENTITYNAME).

    • Attribute (Column) Naming Rule: Every declared attribute name must begin with the first three (33) characters of the student's Last Name followed by an underscore (e.g., a student with the last name Doe defines columns named doe_AttributeName).

  • Practical Task Deliverables:

    • Baseline Dataset: Utilizes the operational dataset provided in Lesson 04 of Module 03.

    • Database Instantiation: Create a relational database using the student's entire first name as the database identifier.

    • Normalization Implementation: Normalize the baseline data structure up to Third Normal Form (3NF), deploying the fully normalized schema and corresponding data types.

    • Informative Joins: Construct at least three (33) informative multi-table joining statements extracting actionable business data across the normalized tables.

    • Grand Denormalization Join: Author an exhaustive grand joining statement that denormalizes the database structure by linking all tables simultaneously, recreating the comprehensive output displayed in the Application task of Lesson 02.

    • Informative Subquery: Develop at least one (11) complex, informative subquery command returning relevant business metrics.

  • Formal Submission Standards:

    • Submission Method 1 (Digital Simulation & Verification - Awards Grade Participation Points):

    • Document Format: Portable Document Format (PDF) file containing all SQL source code alongside execution screenshots confirming query outputs.

    • File Naming Formula: [Subject Code] [Course-year-set] [Last Name] - Module [number] (Lesson [number]) (e.g., IS311 BSIT3Z Doe - Module 03 (Lesson 05).pdf).

    • Page Specifications: Standard Letter size (8.5×11 inches8.5 \times 11\text{ inches}), Portrait orientation.

    • Margins: Exactly 1 inch1\text{ inch} (25.4 mm25.4\text{ mm}) on all four sides.

    • Typography: Arial typeface, font size 10 pt10\text{ pt}, single-line spacing.

    • Submission Method 2 (Handwritten Submission - Contingency Path):

    • Medium: Written by hand on clear, legible paper.

    • File Format: Scanned or photographed output submitted strictly as JPEG, JPG, or PNG images.

    • Document Header: Student's full name, course, academic year, set, and subject title must appear on the first lines in the upper-left corner of each image.

    • Image Preprocessing: Images must be optimized and cropped strictly to essential assessment work to comply with LMS upload size boundaries.

  • Instructional Transition:

    • Subsequent curriculum advances from multi-table query structures into Transaction Management and Concurrency Control.