←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Revision

DBMS · Unit 4 Revision

Quick summary and key points for Unit 4

SQL Overview: Schemas, Data Types, and Table Definitions (DDL)

Overview: A table definition decides which values future rows may contain.

What is SQL?

  • SQL (Structured Query Language) is the universal, standardized programming language used by developers worldwide to communicate with…
  • Originally developed at IBM by Donald Chamberlin and Raymond Boyce in the 1970s (originally named SEQUEL).
  • It is a Declarative language: you tell the database what data you want, and the DBMS query engine figures out the most optimized…

Classification of SQL Sub-Languages

  • SQL commands are divided into five fundamental functional sub-languages:
  • 1. DDL (Data Definition) Defines & alters table structures.
  • 2. DML (Data Manipulation) Inserts, modifies & queries records.
  • 3. DCL (Data Control) Manages user security & permissions.
  • 4. TCL (Transaction Control) Manages database transactions.

View diagram · The Sub-Languages of SQL

Standard SQL Data Types and Domains

  • Before creating a table, columns must be assigned specific storage data types:
  • INT or INTEGER: Whole numbers without decimals (positive or negative)
  • NUMERIC(p, s) or DECIMAL(p, s): Exact precision numbers (p = total digits, s = decimal places)
  • CHAR(n): Fixed-length string (pads unused space with blanks)
  • VARCHAR(n): Variable-length string (only consumes memory for actual text)
  • DATE: Calendar date format (YYYY-MM-DD)
  • TIME / TIMESTAMP: Time (HH:MM:SS) or combined Date + Time

Creating Tables and Enforcing Constraints (CREATE TABLE)

  • The CREATE TABLE command creates a new relation and establishes its column definitions, data domains, and business rules.
  • The Six Essential Column Constraints: PRIMARY KEY: Guarantees column values are Unique and NOT NULL.
  • FOREIGN KEY: References the primary key of another table (Referential Integrity).
  • NOT NULL: Prevents a column from ever holding a NULL value.
  • UNIQUE: Ensures all values in a column are distinct (allows NULLs unless NOT NULL is also specified).
  • CHECK: Validates that data values satisfy a specific boolean condition.
  • DEFAULT: Automatically supplies a fallback value if no value is provided on insertion.

Modifying Tables (ALTER TABLE)

  • When business requirements change, you don’t need to delete and recreate tables; use ALTER TABLE:

Removing Tables: DROP vs. TRUNCATE vs. DELETE

  • Students frequently confuse these three commands in university viva and theory exams:
  • Language Category: DDL
  • What is Removed?: Removes data AND table schema structure permanently from disk
  • Speed: Extremely fast
  • Rollback Capability: Cannot be rolled back (auto-committed)
  • WHERE Clause: Not applicable

SQL Data Manipulation (DML): INSERT, UPDATE, DELETE, and SELECT Queries

Overview: An UPDATE without a WHERE condition can affect every row.

What is Data Manipulation Language (DML)?

  • While DDL sets up the empty structure and containers of a database (like tables and columns), DML (Data Manipulation Language) is what…

Database Change Operations: INSERT, UPDATE, and DELETE

  • INSERT adds rows and UPDATE changes values in existing rows.
  • A. Inserting Data (INSERT INTO): There are two primary ways to insert data into a table:
  • B. Modifying Existing Data (UPDATE): The UPDATE statement changes values in existing rows.
  • C. Removing Data (DELETE): The DELETE FROM statement removes rows from a table.

View diagram · The Three Core Database Change Operations

Querying Data: The Fundamental SELECT Statement

  • The SELECT statement is the most widely executed statement in database computing.

Filtering Rows with the WHERE Clause

  • The WHERE clause uses comparison and logical operators to filter records:

Special SQL Filtering Operators

  • A. The BETWEEN Operator (Range Testing): Tests whether a value falls within an inclusive numerical or date range:
  • B. The IN Operator (Set Membership): Tests whether a value matches any value in a specified list:
  • C. The LIKE Operator (Pattern Matching with Wildcards): Used to search for string patterns using two standard wildcards:
  • Percent sign (%): Matches zero, one, or multiple characters.
  • Underscore (_): Matches strictly one single character.
  • D. Testing for NULL Values (IS NULL / IS NOT NULL): You cannot use = NULL because in SQL, NULL represents an unknown state, and comparing anything to NULL yields UNKNOWN!

SQL Joins: Inner, Left, Right, Full Outer, Cross, and Self Joins

Overview: An inner join of Student and Payment includes students with matching payments.

Why Do We Need Joins in SQL?

  • In a normalized database, data is deliberately split across multiple related tables to prevent redundancy (e.g., student details in Student…

Visual Overview of SQL Joins

  • Matching keys produce joined rows and repeated keys can produce several matches.
  • INNER JOIN Returns ONLY rows that have matching values in both tables.
  • LEFT OUTER JOIN Returns ALL rows from Left table + matching rows from Right table.
  • RIGHT OUTER JOIN Returns ALL rows from Right table + matching rows from Left table.
  • FULL OUTER JOIN Returns ALL rows from BOTH tables; unmatched fields become NULL.

View diagram · Visualizing SQL Joins (Venn Diagram Perspective)

Sample Data Used for Examples:

  • 101: Aman
  • 102: Priya
  • 103: Rohan
  • 104: Sneha
  • 1: Computer Science
  • 2: Management
  • 3: Commerce

INNER JOIN (The Default Join)

  • Returns only records that have matching values in both tables:
  • Notice that Sneha (Dept_ID is NULL) and Commerce (no students enrolled) are both excluded!
  • 101: Aman
  • 102: Priya
  • 103: Rohan

LEFT OUTER JOIN (or LEFT JOIN)

  • Returns all rows from the left table (Student), even if there are no matching rows in the right table (Department).
  • 101: Aman
  • 102: Priya
  • 103: Rohan
  • 104: Sneha
  • Result: (Sneha is preserved even though she has no department assigned!).

RIGHT OUTER JOIN (or RIGHT JOIN)

  • Returns all rows from the right table (Department), even if no student from the left table belongs to it:
  • 101: Aman
  • 103: Rohan
  • 102: Priya
  • NULL: NULL
  • Result: (Commerce is preserved even though zero students belong to it!).

FULL OUTER JOIN

  • Combines the results of both Left and Right joins.
  • Result: Shows Aman, Priya, Rohan (matched).
  • Shows Sneha with NULL department.
  • Shows Commerce with NULL student.

CROSS JOIN (Cartesian Product in SQL)

  • Combines every single row of the first table with every single row of the second table without any ON condition:
  • If Table A has 4 rows and Table B has 3 rows: Output has 4 × 3 = 12 rows.

Self Join (Joining a Table with Itself)

  • A Self Join is a regular join where a table is joined with itself using table aliases.

SQL Aggregate Functions, GROUP BY, and the HAVING Clause

Overview: If one department has marks 50, 70 and 90, its average is 70.

What are Aggregate Functions?

  • In ordinary SQL queries, an operation works on one row at a time (e.g., checking if Age > 20).

The 5 Core Built-In Aggregate Functions

  • COUNT counts qualifying items, while SUM and AVG combine numeric values.
  • 1. COUNT() Returns the total number of rows or non-null values.
  • 2. SUM() Calculates the total mathematical sum of a numeric column.
  • 3. AVG() Calculates the arithmetic mean value of a numeric column.
  • 4. MIN() Returns the lowest (minimum) value in a column.
  • 5. MAX() Returns the highest (maximum) value in a column.
  • Practical Examples of Basic Aggregates: Table: Employee (Emp_ID, Name, Salary, Dept_ID)
  • 📌 Important Rule: All aggregate functions (except COUNT(*)) automatically ignore NULL values during calculations!

View diagram · The Five Built-In Aggregate Functions in SQL

Grouping Rows with the GROUP BY Clause

  • The GROUP BY statement groups rows that have the same values in specified columns into summary rows (like *“find the average salary for EACH…
  • Practical Example: ⚠️ The Golden SQL Rule for GROUP BY:
  • Every column listed in the SELECT clause that is NOT enclosed inside an aggregate function MUST be included in the GROUP BY clause!

Filtering Groups with the HAVING Clause

  • What if you want to filter out entire groups?
  • You CANNOT use WHERE with aggregate functions!
  • Why?
  • The HAVING clause was introduced specifically to filter groups AFTER aggregation has occurred!

Crucial Comparison: WHERE vs. HAVING

  • This is one of the most frequently asked 5-mark questions in DAVV examinations:
  • Primary Purpose: Filters individual rows (tuples)
  • Execution Timing: Executes BEFORE GROUP BY
  • Use with Aggregates: Cannot be used with aggregate functions
  • Dependency: Can be used independently without GROUP BY
  • Performance: Fast (reduces dataset size early before grouping)

Complete Query Anatomy (Execution Order)

  • When a complex SQL query contains all clauses, how does the database execute it?
  • Actual Execution Order in the Database Engine: FROM Employee ➔ Locates table on disk.
  • WHERE Age >= 21 ➔ Discards employees younger than 21.
  • GROUP BY Dept_ID ➔ Groups remaining records by department.
  • HAVING COUNT(*) >= 3 ➔ Discards groups with fewer than 3 employees.
  • SELECT Dept_ID, AVG(Salary) ➔ Computes final summary projections.
  • ORDER BY Avg_Sal DESC ➔ Sorts the final output in descending order!

SQL Subqueries: Nested, Correlated, and EXISTS/NOT EXISTS Operators

Overview: EXISTS asks whether a matching row can be found.

What is a Subquery?

  • A Subquery (also called an Inner Query or Nested Query) is a SQL query enclosed inside parentheses and embedded within another…
  • Think of it as answering a question in two steps:
  • Step 1 (Inner Query): “What is the average salary in the company?” ➔ Returns ₹42,000.
  • Step 2 (Outer Query): “Show me all employees earning more than ₹42,000.”
  • Instead of running two separate manual queries, a subquery lets the database execute both in a single command!

Classification of Subqueries

  • An independent subquery can supply a set or value for the outer query.
  • 1. Single-Row Subquery Returns exactly ONE value (1 row, 1 column).
  • 2. Multi-Row Subquery Returns a list of multiple values (multiple rows, 1 column).
  • 3. Correlated Subquery Inner query references a column from the outer query!

View diagram · The Subquery Hierarchy

Single-Row Subqueries

  • A single-row subquery returns a single scalar value.
  • Practical Example: Question: “Find the names and salaries of all employees who earn more than the company average salary.”
  • How it runs: The database executes the inner query SELECT AVG(Salary) first.

Multi-Row Subqueries (IN, ANY, ALL)

  • When the inner query returns a list of multiple values, single-row operators like > or = cannot be used directly.
  • A. The IN Operator: Matches if the outer value equals ANY item in the returned list:
  • B. The ANY (or SOME) Operator: Compares a value to each value in a list:
  • > ANY (list): Greater than the minimum value in the list.
  • < ANY (list): Less than the maximum value in the list.
  • C. The ALL Operator: Compares a value to EVERY value in a list:
  • > ALL (list): Greater than the maximum value in the list.
  • < ALL (list): Less than the minimum value in the list.

Correlated Subqueries (Dependent Subqueries)

  • In an ordinary subquery, the inner query runs just once, and its result is handed to the outer query.
  • As a result, the inner query executes repeatedly — once for every single candidate row in the outer query!
  • Classic Exam Scenario: Question: “Find employees who earn more than the average salary of THEIR OWN department.”
  • For an employee in Dept 10, the inner query calculates the average salary of Dept 10.
  • For the next employee in Dept 20, the inner query recalculates the average salary of Dept 20!

The EXISTS and NOT EXISTS Operators

  • The EXISTS operator tests for the existence of any rows returned by a subquery:
  • It returns TRUE as soon as the inner query produces at least one row.
  • It returns FALSE if the inner query produces an empty result set (0 rows).
  • Because it checks only for existence, EXISTS stops scanning as soon as the first matching row is found, making it blazingly fast!

SQL Views, Updatability, and Programmatic SQL (Embedded & Cursors)

Overview: A view can present just roll number and total marks to a reporting user.

What is a View in SQL?

  • A View is essentially a Virtual Table based on the result-set of an underlying SQL query.
  • Unlike a physical base table, a View does NOT store data rows on the hard drive!
  • Instead, the DBMS stores only the SQL definition of the view in the Data Dictionary.
  • Whenever an application queries the view, the database engine executes the stored query dynamically behind the scenes!

Creating and Using Views (CREATE VIEW)

  • Practical Example: Suppose the college database administrator wants examination staff to view student names and course marks, but wants to hide…

Advantages of Using Views

  • A view gives a stored name to a query and can simplify repeated joins.
  • 1. Security & Access Control Hides sensitive columns (like salaries, passwords) from unauthorized users.
  • 2. Query Simplification Hides complex 5-table joins behind a simple SELECT * FROM MyView .
  • 3. Logical Data Independence If base tables are restructured, the view definition can be modified without breaking client apps.
  • 4. Customized Perspectives Different departments see only the data relevant to their day-to-day operations.

View diagram · The Four Major Benefits of Views

Updatable Views vs. Non-Updatable Views

  • Can you run INSERT, UPDATE, or DELETE statements on a View?
  • Yes, BUT ONLY IF THE VIEW IS UPDATABLE!
  • If a view is updatable, any change made through the view is immediately propagated down into the underlying physical base table.
  • Strict Conditions for a View to Be Updatable: A view is NOT updatable if its SELECT definition contains any of the following:
  • Aggregate Functions: (SUM, AVG, COUNT, MAX, MIN).
  • The DISTINCT keyword .
  • The GROUP BY or HAVING clause .
  • The UNION or UNION ALL operator .

Programmatic SQL: Using SQL with Programming Languages

  • SQL is a non-procedural language lacking loops (for, while), if-else branches, and user interface controls.
  • Two Primary Integration Approaches: Embedded SQL: Standard SQL statements are written directly inside host language source code (prefixed with EXEC SQL).
  • Dynamic SQL / APIs (CLI, JDBC, ODBC):
  • ODBC (Open Database Connectivity): Standard C/C++ API for database access across different database vendors.
  • JDBC (Java Database Connectivity): Standard Java API allowing Java applications to execute SQL queries and process result sets seamlessly.

Database Cursors: Bridging SQL and Host Languages

  • The Fundamental Impedance Mismatch: SQL operates on SETS: A SELECT query returns a set of 1,000 rows all at once (Set-at-a-time).
  • Programming Languages operate on VARIABLES: Java or C processes one variable at a time (Record-at-a-time).
  • A Cursor is a database mechanism that acts as a pointer or iterator over the active query result set, allowing the host application to…

View diagram · Cursor Life-Cycle Steps