Mastering SQL Joins & Window Functions for CS Midterms
Struggling with duplicate rows in SQL joins or off-by-one errors in window functions? Learn how to solve the toughest CS midterm database questions step-by-step.

Why SQL Joins and Window Functions Break CS Midterms
Every Computer Science student hits the same wall during database midterms: you write a query that looks syntactically clean, yet it either drops half your dataset or multiplies your row count by ten. Unlike basic `SELECT` statements, SQL Joins and Window Functions test your mental model of relational algebra and execution order.
**Key takeaway:** SQL evaluates `FROM` and `JOIN` clauses *before* `WHERE`, `GROUP BY`, and `SELECT`—meaning a misplaced filter in an `OUTER JOIN` silently turns it into an `INNER JOIN`.
When you are racing against a 60-minute Canvas or Blackboard timer, you cannot afford to guess how `RANK()` differs from `DENSE_RANK()`, or why a `LEFT JOIN` suddenly returns fewer rows than expected. Using the [AI HomeTutor Chrome Extension](/#extension) in Code & Complexity Mode, you can snap a screenshot of any schema diagram or query snippet with QuickSnap OCR and immediately verify the execution trace.
Decoding SQL Joins: The 4 Patterns Tested on Exams
Most midterm multiple-choice questions (MCQs) present two small tables—say, `Students` (5 rows) and `Enrollments` (8 rows)—and ask how many rows a specific join returns. To solve these without guessing, track null-matching behavior.
Worked Example: The `LEFT JOIN` + `WHERE` Filter Trap
Suppose you want a list of all students, along with their Fall 2026 course grades if they have any. Consider these two queries:
-- Query A (TRAP)
SELECT s.name, e.grade
FROM Students s
LEFT JOIN Enrollments e ON s.id = e.student_id
WHERE e.semester = 'Fall2026';
-- Query B (CORRECT)
SELECT s.name, e.grade
FROM Students s
LEFT JOIN Enrollments e
ON s.id = e.student_id AND e.semester = 'Fall2026';
Why Query A fails: Because `WHERE` executes *after* the `LEFT JOIN`, any student with no enrollments has `e.semester = NULL`. The condition `NULL = 'Fall2026'` evaluates to `UNKNOWN` (false), which deletes those students from the final output—quietly turning your `LEFT JOIN` into an `INNER JOIN`.
Why Query B works: Placing `e.semester = 'Fall2026'` inside the `ON` clause filters the `Enrollments` table *during* the join, preserving every student from the left table.
Mastering Window Functions Without Losing Rows
A classic CS midterm question asks: *"Find each employee's salary alongside the average salary of their department, without collapsing the table into one row per department."*
If you use `GROUP BY department_id`, SQL collapses the rows. Instead, you need a Window Function using the `OVER()` clause.
`ROW_NUMBER()` vs. `RANK()` vs. `DENSE_RANK()`
Exam writers love testing ties. Imagine three students score `95, 95, 90` on a quiz:
SELECT
student_name,
score,
ROW_NUMBER() OVER (ORDER BY score DESC) AS row_num,
RANK() OVER (ORDER BY score DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rnk
FROM QuizScores;
1. `ROW_NUMBER()` assigns `1, 2, 3` (arbitrary tie-breaker, never repeats).
2. `RANK()` assigns `1, 1, 3` (leaves a gap after ties, just like Olympic medals).
3. `DENSE_RANK()` assigns `1, 1, 2` (no gaps after ties).
If you are practicing similar algorithmic thinking for coding interviews or exams, check out our guide on [Mastering Python Recursion: Solving Algorithmic Exam Traps in 2026](/blog/mastering-python-recursion-algorithmic-exam-traps) or brush up on [Mastering Boolean Logic Gates: Simplifying CS Exam Truth Tables](/blog/mastering-boolean-logic-gates-cs-exam-truth-tables).
Time Complexity & Query Optimization Questions
CS midterms don't just test syntax—they test whether you understand Big-O time complexity under the hood:
• **Nested Loop Join:** $O(N \times M)$ where $N$ and $M$ are table sizes. Painfully slow on large tables without an index.
• **Hash Join:** $O(N + M)$ average time. The database builds an in-memory hash table on the smaller table and probes it with the larger table.
• **Sort-Merge Join:** $O(N \log N + M \log M)$ if unsorted, or $O(N + M)$ if both tables already have B-Tree indexes on the join key.
When you use [AI HomeTutor](/) to review practice exams, switching to Step-by-Step Study Guide mode breaks down both the SQL output *and* the underlying Big-O cost. Built-in Tutor Vision 4 works out of the box with no API key required on the Free tier (20 solves/month), while Pro and Ultra plans on [AI HomeTutor Pricing](/pricing) unlock BYOK routing for DeepSeek V4.1, Claude Sonnet 5.5, GPT-5.4, and Gemini 4 Flash.
Common Exam Traps & How to Avoid Them
• **Trap 1: Using `WHERE` instead of `HAVING` for aggregates.** You cannot write `WHERE COUNT(*) > 5`. Always use `HAVING` to filter grouped results.
• **Trap 2: Forgetting `PARTITION BY` in Window Functions.** Writing `SUM(salary) OVER (ORDER BY id)` without `PARTITION BY department` computes a running total across the *entire company* rather than per department.
• **Trap 3: `COUNT(*)` vs. `COUNT(column_name)`.** `COUNT(*)` counts every row including `NULL`s; `COUNT(column_name)` ignores `NULL` values.
• **Trap 4: Non-deterministic `GROUP BY` columns.** Selecting a column that is neither in `GROUP BY` nor wrapped in an aggregate function throws a strict SQL mode error.
Frequently Asked Questions
Check the FAQ below for quick answers to the most common SQL midterm questions.
Related Study Guides & Next Steps
• **Related Study Guide:** [Mastering Cryptography Fundamentals: Solving RSA Encryption MCQs](/blog/mastering-cryptography-fundamentals-rsa-encryption-mcqs)
Frequently Asked Questions
What is the main difference between WHERE and HAVING in SQL?
WHERE filters individual rows before any grouping occurs, so it cannot reference aggregate functions like SUM() or COUNT(). HAVING filters groups after GROUP BY has been executed.
When should I use RANK() instead of DENSE_RANK() on an exam?
Use RANK() when you want to leave gaps in the ranking sequence after ties (e.g., 1, 1, 3). Use DENSE_RANK() when you want consecutive rank numbers with no gaps (e.g., 1, 1, 2).
Why does my LEFT JOIN act like an INNER JOIN?
This happens when you place a filter condition on the right-hand table inside the WHERE clause instead of the ON clause. Filtering in WHERE eliminates rows where the right-hand columns are NULL.
How can AI HomeTutor help me study for CS SQL midterms?
AI HomeTutor's QuickSnap OCR lets you capture any SQL schema or query from Canvas, Blackboard, or PDFs directly in your browser. Switching to Code & Complexity mode gives you instant query traces, edge-case checks, and Big-O time complexity breakdowns.