Computer Science: Class 12 — Chapter 9: Structured Query Language (SQL)

9.1 & 9.2 Introduction to Relational Databases & SQL

Relational Database Management Systems ( RDBMS ) allow users to create, store, retrieve, and manipulate data organized in relations (tables). Popular RDBMS software includes MySQL , Microsoft SQL Server , PostgreSQL , and Oracle .

Technical Profile: MySQL RDBMS

  • Architecture Layer / Tier: Database Management Layer (Client-Server Architecture)
  • Operational Mechanics & Syntax: Uses SQL to define and manipulate data. Operates via a command-line shell interface using the mysql> prompt.
  • System Trade-offs & Failures: Highly scalable and open-source, but requires careful indexing to prevent performance degradation on large datasets; lacks native support for some advanced analytical functions compared to commercial alternatives.
Core Characteristics of SQL
  • Declarative Language: Users specify what data to retrieve rather than how to retrieve it.
  • Case Insensitivity: SQL statements are case-insensitive (e.g., SELECT is equivalent to select ). However, database and table names can be case-sensitive in Linux environments.
  • Statement Terminator: Every SQL statement must end with a semicolon ( ; ).
  • Multiline Input: Statements can span multiple lines. The prompt changes from mysql> to -> to indicate continuation.
9.3 Data Types and Constraints in MySQL

Every attribute in a relation must have a defined data type and can optionally have constraints to enforce data integrity.

Technical Concept Characterization Matrix: Data Types
Core Computer Science Concept Technical Definition / Operational State Structural Parameters & Specifications Computational Function & System Purpose
CHAR(n) Fixed-length character string. Size $n$ ranges from 0 to 255. Right-padded with spaces if the string is shorter than $n$. Ensures predictable storage size for fixed-length attributes like codes, state abbreviations, or hashes.
VARCHAR(n) Variable-length character string. Size $n$ ranges from 0 to 65535. Allocates only the bytes needed for the actual string. Optimizes storage for variable-length \text fields like names, addresses, and descriptions.
INT Standard integer representation. Occupies 4 bytes of storage. Unsigned range: 0 to 4,294,967,295. Larger values require BIGINT (8 bytes). Used for numeric identifiers, counts, and mathematical calculations.
FLOAT Single-precision floating-point number. Occupies 4 bytes of storage. Represents decimal values. Used for fractional values where absolute precision is not critical (e.g., metrics, ratings).
DATE Calendar date representation. Format: 'YYYY-MM-DD'. Supported range: '1000-01-01' to '9999-12-31'. Enables chronological sorting, date arithmetic, and temporal filtering.
SQL Constraints
  • NOT NULL : Ensures that a column cannot store a NULL (missing/unknown) value.
  • UNIQUE : Guarantees that all values in a column are distinct.
  • DEFAULT : Provides a fallback value when no explicit value is specified during insertion.
  • PRIMARY KEY : Uniquely identifies each record in a table. It implicitly combines NOT NULL and UNIQUE .
  • FOREIGN KEY : Establishes a link between tables by referencing the primary key of another table, enforcing referential integrity.
9.4 SQL for Data Definition Language (DDL)

Data Definition Language ( DDL ) statements are used to define, modify, and destroy database schemas and structures.

Database Management Commands
  
    -- Create a new database
    CREATE DATABASE StudentAttendance;
    -- View existing databases
    SHOW DATABASES;
    -- Select a database for active use
    USE StudentAttendance;
    -- View tables within the active database
    SHOW TABLES;
  
Table Creation and Schema Inspection

The CREATE TABLE statement defines the relation name, attributes, data types, and constraints.

  
    CREATE TABLE STUDENT(
    RollNumber INT,
    SName VARCHAR(20) NOT NULL,
    SDateofBirth DATE,
    GUID CHAR(12),
    PRIMARY KEY (RollNumber)
    );
  

To inspect the schema of an existing table, use the DESCRIBE or DESC command:

  
  DESCRIBE STUDENT;

Schema Modification (ALTER TABLE)

The ALTER TABLE statement allows dynamic modifications to an existing table structure without destroying data.

  1. Add a Primary Key:
        
        ALTER TABLE GUARDIAN ADD PRIMARY KEY (GUID);
      
    
  2. Add a Composite Primary Key:
      
      ALTER TABLE ATTENDANCE ADD PRIMARY KEY (AttendanceDate, RollNumber);
    
    
  3. Add a Foreign Key:
      
      ALTER TABLE STUDENT ADD FOREIGN KEY (GUID) REFERENCES GUARDIAN(GUID);
    
    
  4. Add a UNIQUE Constraint:
      
      ALTER TABLE GUARDIAN ADD UNIQUE (GPhone);
    
    
  5. Add a New Attribute:
      
      ALTER TABLE GUARDIAN ADD income INT;
    
    
  6. Modify Attribute Datatype:
      
      ALTER TABLE GUARDIAN MODIFY GAddress VARCHAR(40);
    
    
  7. Modify Constraint (Add NOT NULL):
      
      ALTER TABLE STUDENT MODIFY SName VARCHAR(20) NOT NULL;
    
    
  8. Add a Default Value:
      
      ALTER TABLE STUDENT MODIFY SDateofBirth DATE DEFAULT '2000-05-15';
    
    
  9. Remove an Attribute:
      
      ALTER TABLE GUARDIAN DROP COLUMN income;
    
    
  10. Remove a Primary Key:
      
      ALTER TABLE GUARDIAN DROP PRIMARY KEY;
    
    
Destructive Schema Commands (DROP)

The DROP statement permanently deletes tables or databases from the system. This operation is non-reversible.

  
    -- Delete a table and all its data
    DROP TABLE STUDENT;
    -- Delete an entire database and all its tables
    DROP DATABASE StudentAttendance;
  
9.5 & 9.7 SQL for Data Manipulation Language (DML)

Data Manipulation Language ( DML ) statements handle the insertion, modification, and deletion of records within tables.

Record Insertion (INSERT INTO)

Records can be inserted by specifying values for all columns in schema order, or by explicitly declaring target columns.

  
    -- Insertion by schema order
    INSERT INTO GUARDIAN
    VALUES (444444444444, 'Amit Ahuja', 5711492685, 'G-35, Ashok Vihar, Delhi');
    -- Insertion with explicit column mapping (useful for omitting nullable/default columns)
    INSERT INTO GUARDIAN (GUID, GName, GAddress)
    VALUES (333333333333, 'Danny Dsouza', 'S-13, Ashok Village, Daman');
  
Record Modification (UPDATE)

The UPDATE statement modifies existing values. A WHERE clause is critical to restrict the scope of modification; omitting it updates all rows in the table.

  
    UPDATE STUDENT
    SET GUID = '101010101010'
    WHERE RollNumber = 3;
  
Record Deletion (DELETE)

The DELETE statement removes rows. Like UPDATE , omitting the WHERE clause deletes all records while preserving the table structure.

  
    DELETE FROM STUDENT
    WHERE RollNumber = 2;
  
9.6 SQL for Data Query Language (DQL)

Data Query Language ( DQL ) centers on the SELECT statement, which retrieves data from one or more tables.

Technical Profile: SELECT Statement

  • Architecture Layer / Tier: Query Execution Engine
  • Operational Mechanics & Syntax: Evaluates clauses in the logical order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY .
  • System Trade-offs & Failures: Highly expressive, but complex nested queries or unindexed WHERE clauses can cause full-table scans, leading to severe performance bottlenecks.
Basic Queries and Column Aliasing
  
    -- Retrieve all columns and rows
    SELECT * FROM EMPLOYEE;
    -- Retrieve specific columns
    SELECT EmpNo, Ename FROM EMPLOYEE;
    -- Column Aliasing (Renaming output headers)
    SELECT EName AS Name, Salary * 12 AS 'Annual Income'
    FROM EMPLOYEE;
  
Filtering and Conditional Operators

The WHERE clause filters records based on logical and comparison expressions.

  • Relational Operators: = , < , > , <= , >= , != (or <> ).
  • Logical Operators: AND , OR , NOT .
  • Range Filtering (BETWEEN): Inclusive boundary check.
      
        SELECT Ename, DeptId FROM EMPLOYEE
        WHERE Salary BETWEEN 20000 AND 50000;
      
    
  • Set Membership (IN): Matches any value in a specified list.
      
        SELECT * FROM EMPLOYEE
        WHERE DeptId IN ('D01', 'D02', 'D04');
      
    
Sorting Results (ORDER BY)

Sorts the output in ascending ( ASC , default) or descending ( DESC ) order.

  
    SELECT * FROM EMPLOYEE
    ORDER BY Salary DESC, Bonus ASC;
  
Handling NULL Values

Because NULL represents an unknown state, standard comparison operators (like = NULL ) fail. Special operators must be used:

  
    -- Find records with missing values
    SELECT * FROM EMPLOYEE WHERE Bonus IS NULL;
    -- Find records with defined values
    SELECT * FROM EMPLOYEE WHERE Bonus IS NOT NULL;
  
Pattern Matching (LIKE Operator)

Enables substring search using wildcards:

  • % : Matches zero, one, or multiple characters.
  • _ : Matches exactly one character.
  
    -- Names starting with 'K'
    SELECT * FROM EMPLOYEE WHERE Ename LIKE 'K%';
    -- Names ending with 'a'
    SELECT * FROM EMPLOYEE WHERE Ename LIKE '%a';
    -- Names with 'a' as the second character
    SELECT * FROM EMPLOYEE WHERE Ename LIKE '_a%';
    -- Exactly 5-character names ending with 'ANYA'
    SELECT * FROM EMPLOYEE WHERE Ename LIKE '_ANYA';
  
9.8 Built-in Functions in SQL

SQL provides built-in functions categorized into Single Row Functions (Scalar) and Multiple Row Functions (Aggregate).

Single Row Functions

These functions operate on a single value per row and return one result per row.

Category Function Description & Example
Math Functions POWER(X, Y) Calculates $X^Y$.
SELECT POWER(2,3); -- Output: 8
ROUND(N, D) Rounds $N$ to $D$ decimal places.
SELECT ROUND(2912.564, 1); -- Output: 2912.6
MOD(A, B) Returns the remainder of $A/B$.
SELECT MOD(21, 2); -- Output: 1
String Functions UCASE(str) / UPPER(str) Converts string to uppercase.
SELECT UCASE('sql'); -- Output: 'SQL'
LOWER(str) / LCASE(str) Converts string to lowercase.
SELECT LCASE('SQL'); -- Output: 'sql'
MID(str, pos, n) Extracts $n$ characters starting from position $pos$.
SELECT MID('Informatics', 3, 4); -- Output: 'form'
LENGTH(str) Returns character count.
SELECT LENGTH('Delhi'); -- Output: 5
INSTR(str, substr) Returns 1-based index of first occurrence of $substr$.
SELECT INSTR('Informatics', 'ma'); -- Output: 6
TRIM(str) Removes leading and trailing spaces.
SELECT TRIM(' MADAM '); -- Output: 'MADAM'
Date Functions NOW() Returns current system date and time.
SELECT NOW(); -- Output: '2019-07-11 19:41:17'
DATE(dt) Extracts date portion.
SELECT DATE(NOW()); -- Output: '2019-07-11'
MONTHNAME(d) Returns name of the month.
SELECT MONTHNAME('2019-07-11'); -- Output: 'July'
DAYNAME(d) Returns name of the day.
SELECT DAYNAME('2019-07-11'); -- Output: 'Thursday'
Multiple Row (Aggregate) Functions

These functions process a set of values across multiple rows to return a single summary value.

  • MAX(column) : Returns the largest value in the column.
  • MIN(column) : Returns the smallest value in the column.
  • AVG(column) : Computes the average value (ignores NULL ).
  • SUM(column) : Calculates the total sum of values.
  • COUNT(*) : Counts the total number of rows in a table, including those with NULL values.
  • COUNT(column) : Counts the number of non-NULL values in a specific column.
9.9 GROUP BY and HAVING Clauses

The GROUP BY clause aggregates rows with identical values in specified columns into summary rows.

Grouping and Filtering Aggregates

To filter groups based on aggregate conditions, the HAVING clause must be used instead of WHERE (since WHERE filters individual rows before aggregation occurs).

  
    -- Count cars purchased by each customer
    SELECT CustID, COUNT(*) AS 'Number of Cars'
    FROM SALE
    GROUP BY CustID;
    -- Find customers who purchased more than 1 car
    SELECT CustID, COUNT(*)
    FROM SALE
    GROUP BY CustID
    HAVING COUNT(*) > 1;
  
9.10 Operations on Relations (Set Operations & Cartesian Product)

Relational algebra operations combine tuples from two relations. For set operations, relations must be union-compatible (same number of attributes with matching domains).

Set Operations
  • UNION ($\\cup$): Combines rows from both tables, eliminating duplicate rows.
        
          SELECT Name FROM DANCE
          UNION
          SELECT Name FROM MUSIC;
        
      
  • INTERSECT ($\\cap$): Returns only the common rows present in both tables.
      
        -- Conceptual representation (MySQL uses INNER JOIN or IN for intersection)
        SELECT D.Name FROM DANCE D
        WHERE D.Name IN (SELECT M.Name FROM MUSIC M);
      
    
  • MINUS / EXCEPT (-): Returns rows present in the first table but absent in the second.
      
        -- Conceptual representation
        SELECT D.Name FROM DANCE D
        WHERE D.Name NOT IN (SELECT M.Name FROM MUSIC M);
      
    
Cartesian Product (X)

Combines every row of the first relation with every row of the second relation.

  • Degree: Sum of the degrees of both relations ($Degree(R \\times S) = Degree(R) + Degree(S)$).
  • Cardinality: Product of the cardinalities of both relations ($Cardinality(R \\times S) = Cardinality(R) \\times Cardinality(S)$).
  
  SELECT * FROM DANCE, MUSIC;

9.11 Querying Multiple Relations (JOINs)

A JOIN operation combines related tuples from two tables based on a common attribute.

Technical Profile: NATURAL JOIN

  • Architecture Layer / Tier: Relational Algebra Engine
  • Operational Mechanics & Syntax: Automatically joins tables based on columns with identical names and data types, returning only one copy of the common column. Syntax: SELECT * FROM TableA NATURAL JOIN TableB;
  • System Trade-offs & Failures: Simplifies query syntax and removes redundant columns, but can produce unexpected empty sets if tables share unrelated columns with matching names (e.g., 'Remarks' or 'Status').
Join Implementations
  1. Equi-Join using WHERE clause:
        
          SELECT * FROM UNIFORM U, COST C
          WHERE U.UCode = C.UCode;
        
      
  2. Explicit JOIN ON clause:
      
        SELECT * FROM UNIFORM U
        JOIN COST C ON U.UCode = C.UCode;
      
    
  3. Natural Join:
      
        SELECT * FROM UNIFORM
        NATURAL JOIN COST;
      
    

Case Study: CARSHOWROOM Database Schema Design


Socio-Technical Analysis & Core Systemic Impact: Designing a multi-table relational database for a car showroom requires establishing clear primary and foreign key relationships to prevent anomalies. For instance, the SALE table references INVENTORY(CarID) , CUSTOMER(CustID) , and EMPLOYEE(EmpID) . If referential integrity constraints are not strictly enforced, a sale could be recorded for a non-existent car or customer, leading to critical accounting and inventory discrepancies. Implementing cascading updates and deletes ensures that changes in core business entities propagate safely throughout the system.