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
§ 4.1.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
§ 4.2.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
§ 4.3.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!
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.
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.
“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.”
Identify the requested output columns and source relations.
SELECT emp_name, dept_id, salary
Single table: Employee (aliased as E1 for outer query)
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.
5. SQL Nuances & 3-Valued Logic Quiz
Verify your understanding of SQL corner cases and execution pipelines.
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'?
6. 1-Minute SQL Revision Card
“WHERE requires TRUE to keep rows; UNKNOWN and FALSE are both discarded. (col = NULL) is always UNKNOWN.”
- •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.
- •Never write WHERE col = NULL; write WHERE col IS NULL.
- •Column aliases created in SELECT cannot be referenced in WHERE.
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.
The definitive analysis of SQL design flaws and 3-valued logic pitfalls.
Standard undergraduate textbook covering subqueries and complex joins.
Curated for clarity, rigorous numerical solving, and semester excellence:
GATE-focused numerical problem-solving with clear worked examples.
Fast conceptual coverage with step-by-step GATE numericals.
Systematic textbook-style explanations ideal for first-time learners.
Deep theoretical rigor on normalization and transaction serializability.