DATABASE MANAGEMENT SYSTEMS/Student Engineering Notebook
Page 04·notes
SQL MASTERY, 3-VALUED LOGIC & COMPLEX SUBQUERIES—~22 MIN READ

SQL Mastery: 3-Valued Logic, Aggregates & Correlated Subqueries

“Execution pipeline, 3-valued truth tables, the NOT IN with NULL trap, and grouping.”

1.The Subtlety of Production SQL

Most students know basic SELECT * FROM Table WHERE id = 1. But competitive examinations and production database engines test corner cases: what happens when NULLs appear in subqueries, how outer joins interact with aggregate filters, and how correlated subqueries execute.

SQL operates under Three-Valued Logic (3VL) with truth values TRUE, FALSE, and UNKNOWN. Missing data (NULL) is not zero or an empty string—it represents unknown or inapplicable information. Failing to understand 3VL leads to silent data bugs in production banking systems and lost marks in GATE exams.

2.Three-Valued Logic & The Dangerous NULL Trap

Any comparison with NULL (even NULL = NULL) evaluates to UNKNOWN, never TRUE.

Truth Tables with UNKNOWN:

• AND: TRUE AND UNKNOWN = UNKNOWN, FALSE AND UNKNOWN = FALSE.

• OR: TRUE OR UNKNOWN = TRUE, FALSE OR UNKNOWN = UNKNOWN.

• NOT: NOT UNKNOWN = UNKNOWN.

The Infamous 'NOT IN' with NULL Trap:

Consider table R with values {1, NULL}. What does 'SELECT * FROM S WHERE x NOT IN (SELECT a FROM R)' return?

x NOT IN (1, NULL) expands logically to: (x ≠ 1) AND (x ≠ NULL).

Because (x ≠ NULL) always evaluates to UNKNOWN, the expression becomes: (x ≠ 1) AND UNKNOWN.

• If x = 1: FALSE AND UNKNOWN = FALSE.

• If x = 2: TRUE AND UNKNOWN = UNKNOWN.

In SQL, a WHERE clause only keeps rows that evaluate strictly to TRUE! Because the result is either FALSE or UNKNOWN for every possible value of x, the query returns EMPTY (0 rows)!

The Production Solution: Always use NOT EXISTS instead of NOT IN when subquery columns can contain NULLs.

3.SQL Query Logical Execution Order

SQL is written in one order but executed by the database engine in a strictly defined logical pipeline:

1. FROM / JOIN -> Identify data sources & compute Cartesian cross-products

2. WHERE -> Filter individual rows before grouping

3. GROUP BY -> Partition rows into buckets by group keys

4. HAVING -> Filter aggregated groups (can use COUNT, SUM, AVG)

5. SELECT -> Compute output projections & expressions

6. DISTINCT -> Eliminate duplicate output tuples

7. ORDER BY -> Sort final output rows (can use aliases defined in SELECT)

8. LIMIT / OFFSET -> Slice final row window

Key Rule: You can never use a column alias defined in SELECT inside the WHERE clause because WHERE executes before SELECT!

LABORATORY · INTERACTIVE SIMULATION —Concept Exploration

4. University Exam Question-to-SQL Translation Studio

Step-by-step interactive derivation: see how English problem descriptions are decomposed into relational target attributes, subquery correlation anchors, WHERE vs HAVING filters, and row-by-row live evaluation traces.

EXAM STUDIOQuestion-to-SQL Systematic Translation Flow

Translating University Exam Questions into Production SQL

In university exams, professors test your ability to decompose natural language problem statements into logical relational algebra pipelines. Follow this 5-step heuristic to never lose marks.

Exam Problem Statement
Asked in 90% of University DBMS Semester Exams & Technical InterviewsIntermediate

“Write an SQL query to find the employee name, department ID, and salary of all employees who earn strictly more than the average salary of their own department.”

Step 1: Entity & Output Attribute Extraction

Identify the requested output columns and source relations.

Target Projection (What will SELECT output?)

SELECT emp_name, dept_id, salary

Candidate Data Sources (FROM Clause)

Single table: Employee (aliased as E1 for outer query)

✎ When an exam question says 'more than the average of THEIR OWN department', each employee must be compared against a different calculated value. This signals a Correlated Subquery!
Engine Deep Dive: Logical Order of Execution vs Written Syntax✎ SQL is written in one order, but executed in this strict 8-step pipeline

1. FROM / JOIN: Determines the universe of discourse. Tables are identified and cross-joined. If table is missing, execution halts with relation does not exist.

STUDENT PRACTICE · CONCEPT DRILL

5. SQL Nuances & 3-Valued Logic Quiz

Verify your understanding of SQL corner cases and execution pipelines.

Problem 1 · FOUNDATION

Given a table T with 4 rows where column 'val' has values: 10, 20, NULL, 30. What is the result of 'SELECT COUNT(*), COUNT(val) FROM T'?

RAPID REVIEW · NOTEBOOK SUMMARY

6. 1-Minute SQL Revision Card

core principle:

“WHERE requires TRUE to keep rows; UNKNOWN and FALSE are both discarded. (col = NULL) is always UNKNOWN.”

must-remember principles:
  • •NOT IN with any NULL in subquery returns 0 rows! Always prefer NOT EXISTS.
  • •COUNT(*) counts all rows; COUNT(col) counts only non-null values.
  • •Execution order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY.
  • •WHERE filters raw rows; HAVING filters grouped aggregates.
critical exam pitfalls:
  • •Never write WHERE col = NULL; write WHERE col IS NULL.
  • •Column aliases created in SELECT cannot be referenced in WHERE.
SOURCE TRANSPARENCY & CITATIONS

Primary Academic References & Exam Sources

Every concept in Notes From a B.Tech Brain is synthesized from authoritative academic texts, seminal peer-reviewed research, verified exam archives, and renowned university lectures.

Primary Academic Texts
SQL and Relational Theory: How to Write Accurate SQL Code↗by C. J. Date (O'Reilly Media) · Three-Valued Logic and SQL null semantics

The definitive analysis of SQL design flaws and 3-valued logic pitfalls.

ACADEMIC STANDARD
Database System Concepts (10th Edition)↗by Silberschatz, Korth, Sudarshan · Chapters 3, 4 & 5: Structured Query Language (SQL)

Standard undergraduate textbook covering subqueries and complex joins.

ACADEMIC STANDARD
RECOMMENDED YOUTUBE EDUCATORS & FULL-COURSE PLAYLISTS

Curated for clarity, rigorous numerical solving, and semester excellence:

Knowledge Gate · DBMS for GATE & Semester↗Instructor: Sanchit Jain · Covers: ER diagrams, normalization, SQL, transactions, concurrency control

GATE-focused numerical problem-solving with clear worked examples.

Open YouTube↗
Gate Smashers · DBMS Full Course↗Instructor: Varun Singla · Covers: Relational algebra, SQL queries, B/B+ trees, file organization

Fast conceptual coverage with step-by-step GATE numericals.

Open YouTube↗
Neso Academy · DBMS Complete Playlist↗Instructor: Neso Academy · Covers: Relational model, SQL, normalization theory, ACID properties

Systematic textbook-style explanations ideal for first-time learners.

Open YouTube↗
Ravindrababu Ravula · DBMS Lectures↗Instructor: Ravindrababu Ravula · Covers: Functional dependencies, BCNF, 3NF decomposition, transaction schedules

Deep theoretical rigor on normalization and transaction serializability.

Open YouTube↗