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, andMINUS) to merge distinct query result sets.Advanced data extraction across relational tables using specialized
JOINoperators.Implementation of diverse subquery styles within the
SELECTstatement 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 () 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, T2ANSI SQL Syntax:
SELECT * FROM T1 CROSS JOIN T2Operational Description: Evaluates and returns the Cartesian product of table
T1and tableT2.Old-Style Join:
Classification: Inner join
Syntax:
SELECT * FROM T1, T2 WHERE T1.C1 = T2.C1Operational Description: Returns strictly those rows satisfying the equality condition specified in the
WHEREclause.Natural Join:
Classification: Inner join
ANSI SQL Syntax:
SELECT * FROM T1 NATURAL JOIN T2Operational 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
USINGclause.Join On:
Classification: Inner join
ANSI SQL Syntax:
SELECT * FROM T1 JOIN T2 ON T1.C1 = T2.C1Operational Description: Returns rows meeting the explicit join condition declared within the
ONclause.Left Outer Join:
Classification: Outer join
ANSI SQL Syntax:
SELECT * FROM T1 LEFT OUTER JOIN T2 ON T1.C1 = T2.C1Operational 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.C1Operational 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.C1Operational Description: Returns all matching rows alongside all unmatched rows from both tables (
T1andT2).
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 (.
Standard Syntax:
sql SELECT column-list FROM table1 CROSS JOIN table2
Execution Example on Relational Database:
sql SELECT * FROM INVOICE CROSS JOIN LINE; When the
INVOICEtable contains rows and theLINEtable contains rows, the Cartesian product yields exactly rows.
Attribute Projection Example:
sql SELECT INVOICE.INV_NUMBER, CUS_CODE, INV_DATE, P_CODE FROM INVOICE CROSS JOIN LINE; Legacy Comma-Separated Alternative:
sql SELECT INVOICE.INV_NUMBER, CUS_CODE, INV_DATE, P_CODE FROM INVOICE, LINE; Old-Style Inner Join:
Structural Mechanism: Lists joined tables inside the
FROMclause and places relational linking conditions entirely inside theWHEREclause.Standard Syntax:
sql SELECT column-list FROM table1, table2 WHERE join-condition
Execution Example:
sql SELECT P_CODE, P_DESCRIPT, P_PRICE, V_NAME FROM PRODUCT, VENDOR WHERE PRODUCT.V_CODE = VENDOR.V_CODE; 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., ) is subsequently joined with the third table ().
Join Condition Cardinality: For tables participating in an old-style join, exactly join conditions are required.
Logical Operator Chaining: Multiple join conditions must be connected using the
ANDlogical 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
Two-Table Execution Example:
sql SELECT CUS_CODE, CUS_LNAME, INV_NUMBER, INV_DATE FROM CUSTOMER NATURAL JOIN INVOICE; Output: Produces rows matching customers Dunne (), Smith (), Orlando (), O'Brian (), and Farriss ().
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; Output: Produces detailed invoice line rows.
Elimination of Table Qualifiers: In a
NATURAL JOIN, common attributes (such asCUS_CODEorINV_NUMBER) must not include table qualifiers or prefixes (e.g., writingCUSTOMER.CUS_CODEwill cause an error).

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
USINGclause must exist in both joining tables with compatible data types.Standard Syntax:
sql SELECT column-list FROM table1 JOIN table2 USING (common-column)
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); Qualifier Rule: Columns declared inside the
USINGclause cannot be prefixed with table qualifiers in theSELECTprojection list.

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
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; Ambiguity Resolution Rule: Unlike
NATURAL JOINorJOIN USING, theJOIN ONclause requires explicit table qualifiers for any attribute appearing in more than one table. Omitting qualifiers yields a"column ambiguously defined"DBMS runtime error.

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
FROMclause 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
Comprehensive Execution Query:
sql SELECT P_CODE, VENDOR.V_CODE, V_NAME FROM VENDOR LEFT JOIN PRODUCT ON VENDOR.V_CODE = PRODUCT.V_CODE; Result Characteristics:
Generates 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 (), SuperLoo, Inc. (), Brackman Bros. (), Damal Supplies (), and B&K, Inc. ().

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
Comprehensive Execution Query:
sql SELECT P_CODE, VENDOR.V_CODE, V_NAME FROM VENDOR RIGHT JOIN PRODUCT ON VENDOR.V_CODE = PRODUCT.V_CODE; Result Characteristics:
Generates total rows.
Preserves inventory products lacking associated vendor records (
V_CODE = NULL,V_NAME = NULL): product codesPVC23DRTand23114-AA.

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
Comprehensive Execution Query:
sql SELECT P_CODE, VENDOR.V_CODE, V_NAME FROM VENDOR FULL JOIN PRODUCT ON VENDOR.V_CODE = PRODUCT.V_CODE; Result Characteristics:
Generates total rows.
Preserves both the unmatched vendor records ( vendors without products) and unmatched product records ( products without vendors).

SQL Subqueries and Nested Query Structures
Fundamental Principles of Subqueries:
Definition: A
SELECTstatement 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
WHEREclause.Scalar Output Constraint: When paired with standard comparison operators (, , , , , , the subquery must evaluate to a single scalar value (.
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); Identifies inventory items priced at or above the computed product average price: product codes
11QER/31(),2232/QTY(),2232/QWE(),89-WRE-Q(), andWR3/TT3().
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'); Identifies customers who purchased a claw hammer: customer (Leona Dunne) and customer (Myron Orlando).

FROM Clause Subqueries (Inline Views / Virtual Tables):
Relational Underpinning: Because any valid
SELECTstatement produces a relational table structure, a subquery can be placed inside theFROMclause 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;
Execution Mechanics:
Subquery
CP1isolates all customer codes purchasing product13-Q2/P2.Subquery
CP2isolates all customer codes purchasing product23109-HB.The outer query joins the base table
CUSTOMERwith virtual tablesCP1andCP2, matching records onCUS_CODE.Output: Resolves to customer (Orlando).

Attribute List Subqueries (Inline Subqueries):
Structural Positioning: Placed directly within the
SELECTcolumn 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
SELECTlist (such asAS AVGPRICE) cannot be referenced inside mathematical expressions within the sameSELECTclause.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;
Quantitative Output Structure:
Evaluates the global average product price as .
Computes the individual price variance (
DIFF) for every item: e.g., product11QER/31() yields a positive difference of , whereas product13-Q2/P2() yields a negative variance of .

Practical Implementation Assessment Requirements
Entity and Attribute Naming Conventions:
Entity (Table) Naming Rule: Every declared entity name must begin with the first three () 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 () 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 () 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 () 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 (), Portrait orientation.
Margins: Exactly () on all four sides.
Typography: Arial typeface, font size , 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, orPNGimages.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.