Cracking a live technical coding screen requires far more than memorizing simple SELECT queries; keeping a battle-tested sql interview cheat sheet at your fingertips is the difference between fumbling under pressure and writing optimal, production-grade database scripts. In this comprehensive interview guide, you will master the 20 most frequently tested SQL interview patterns, from multi-table joins and common table expressions (CTEs) to advanced window functions, deduplication techniques, and cumulative revenue aggregations tested by top tech companies.
| Complexity Tier | Tested Pattern Category | Common Interview Question Archetype | Target Roles |
|---|---|---|---|
| Level 1: Filtering & Grouping | Aggregations with HAVING vs WHERE |
Find customers who spent over $1,000 across multiple orders | Junior Analyst, BI Specialist |
| Level 2: Relational Merges | Venn Joins & Self-Joins | Identify employees earning more than their direct managers | Data Analyst, Business Analyst |
| Level 3: CTEs & Subqueries | Multi-stage pipeline transformations | Calculate monthly user retention and churn rates | Data Engineer, Analytics Engineer |
| Level 4: Window Functions | DENSE_RANK(), LEAD(), LAG() |
Find the top 3 highest-paid employees per department | Senior Data Scientist, Staff Engineer |
The Anatomy of SQL Query Processing: Logical Execution Order
Before diving into query syntax, every candidate must master the physical order in which relational database management systems (such as PostgreSQL, MySQL, and Snowflake) execute queries. Interviewers frequently test this to see whether an engineer understands query optimization.
FROM&JOIN: Gathers source tables and executes Cartesian joins.WHERE: Filters rows prior to any aggregations.GROUP BY: Condenses rows into grouped summary buckets.HAVING: Filters summarized aggregations (cannot use aliases declared in SELECT).SELECT: Extracts specific columns, applies scalar functions, and computes window calculations.DISTINCT: Strips duplicate output records.ORDER BY: Sorts output records (can utilize SELECT aliases).LIMIT/OFFSET: Restricts the total output record count for pagination.
When preparing your broader tech career strategy, use our interactive Career Roadmap Planner to map required technical milestones, or benchmark expected compensation with our Tech Salary & Bootcamp ROI Calculator.
Section 1: The Essential SQL Join Architecture
Relational databases exist to connect disparate entity models. The visual guide below illustrates how standard SQL joins operate across overlapping primary and foreign key domains.

Figure 1: Visual comparison matrix of core SQL join methodologies.
Pattern 1: The Classic Non-Matching Left Join (Anti-Join)
Interview question: “Find all registered customers who have never placed a single order in the last 12 months.”
-- Pattern 1: Left Anti-Join
SELECT
c.customer_id,
c.customer_name,
c.email
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id
WHERE o.order_id IS NULL;
Senior Engineer Tip: In enterprise datasets containing tens of millions of rows, this anti-join pattern consistently outperforms WHERE customer_id NOT IN (SELECT customer_id FROM orders) because NOT IN degrades severely if null values exist in the foreign key column.
Pattern 2: The Self-Join Hierarchy
Interview question: “Given an employee table with columns employee_id, name, and manager_id, list every employee who earns a higher salary than their direct manager.”
-- Pattern 2: Self-Join for Hierarchical Comparison
SELECT
e.name AS employee_name,
e.salary AS employee_salary,
m.name AS manager_name,
m.salary AS manager_salary
FROM employees e
INNER JOIN employees m
ON e.manager_id = m.employee_id
WHERE e.salary > m.salary;
Section 2: Advanced Window Functions Mastery
Window functions perform mathematical calculations across sets of table rows that are related to the current row, without collapsing the individual rows like traditional GROUP BY clauses do.

Figure 2: Execution workflow and partition boundaries of SQL window functions.
Pattern 3: Top N Records Per Category Using DENSE_RANK()
Interview question: “Find the top 2 highest-selling sales representatives within each geographic territory, properly handling ties.”
-- Pattern 3: Top N Per Group
WITH RankedSales AS (
SELECT
rep_id,
territory,
total_revenue,
DENSE_RANK() OVER (
PARTITION BY territory
ORDER BY total_revenue DESC
) AS sales_rank
FROM sales_representatives
)
SELECT
territory,
rep_id,
total_revenue,
sales_rank
FROM RankedSales
WHERE sales_rank <= 2;
Key Distinction: ROW_NUMBER() assigns strict sequential integers (1, 2, 3) breaking ties randomly; RANK() assigns identical ranks to ties but skips following ranks (1, 1, 3); DENSE_RANK() assigns identical ranks to ties without skipping (1, 1, 2).
Pattern 4: Period-over-Period Growth Analysis Using LAG()
Interview question: "Calculate month-over-month revenue growth rate for each product category."
-- Pattern 4: MoM Growth via LAG
WITH MonthlyRevenue AS (
SELECT
DATE_TRUNC('month', order_date)::DATE AS sales_month,
category_name,
SUM(order_amount) AS current_month_revenue
FROM sales
GROUP BY 1, 2
)
SELECT
sales_month,
category_name,
current_month_revenue,
LAG(current_month_revenue, 1) OVER (
PARTITION BY category_name
ORDER BY sales_month
) AS prior_month_revenue,
ROUND(
(current_month_revenue - LAG(current_month_revenue, 1) OVER (
PARTITION BY category_name ORDER BY sales_month
)) / NULLIF(LAG(current_month_revenue, 1) OVER (
PARTITION BY category_name ORDER BY sales_month
), 0) * 100.0, 2
) AS pct_mom_growth
FROM MonthlyRevenue;
Pattern 5: Cumulative Running Totals Without Subqueries
Interview question: "Compute the running year-to-date sum of company revenue ordered by transaction timestamp."
-- Pattern 5: Running Totals
SELECT
transaction_id,
transaction_date,
amount,
SUM(amount) OVER (
ORDER BY transaction_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_cumulative_total
FROM transactions;
Section 3: Data Cleaning & Deduplication Patterns
In modern enterprise environments, dirty data with duplicate records is an everyday reality. Interviewers routinely test candidates' ability to deduplicate tables safely.
Pattern 6: Deleting Duplicate Rows Keeping Only the Latest Entry
-- Pattern 6: Deduplication CTE
WITH DuplicateCTE AS (
SELECT
user_id,
updated_at,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC
) AS row_num
FROM user_profiles
)
DELETE FROM user_profiles
WHERE user_id IN (
SELECT user_id
FROM DuplicateCTE
WHERE row_num > 1
);
For more real-world project scenarios involving complex datasets, check out our guide on 5 Data Analyst Portfolio Projects or expand your foundational skills with our 30-day guide on How to Learn SQL in 30 Days.
Section 4: Advanced Grouping & Pivot Matrix Patterns
Pattern 7: Conditional Aggregation (CASE WHEN inside SUM)
Interview question: "Pivot sales performance across Q1, Q2, Q3, and Q4 into individual columns per department without using vendor-specific PIVOT keywords."
-- Pattern 7: Cross-Tabulation Pivot
SELECT
department_name,
SUM(CASE WHEN EXTRACT(QUARTER FROM sale_date) = 1 THEN amount ELSE 0 END) AS q1_sales,
SUM(CASE WHEN EXTRACT(QUARTER FROM sale_date) = 2 THEN amount ELSE 0 END) AS q2_sales,
SUM(CASE WHEN EXTRACT(QUARTER FROM sale_date) = 3 THEN amount ELSE 0 END) AS q3_sales,
SUM(CASE WHEN EXTRACT(QUARTER FROM sale_date) = 4 THEN amount ELSE 0 END) AS q4_sales,
SUM(amount) AS total_annual_sales
FROM department_sales
GROUP BY department_name;
Section 5: Building a Technical Interview Portfolio
Top data companies don't just rely on LeetCode questions; they review public GitHub repositories to verify code structure and documentation quality. If you want to build an outstanding project that proves production SQL expertise, utilize our free Portfolio Project Generator.
Pairing SQL skills with business understanding is what sets apart elite analysts. Review our roadmap on Financial Modeling Roadmap to see how corporate finance leaders leverage SQL queries to feed enterprise valuation models, or study cloud database architecture in our AWS Cloud Practitioner Study Guide.
Frequently Asked Questions About SQL Interviews
Section 6: Advanced SQL Patterns Tested in FAANG Technical Screens
Top-tier tech employers demand fluency in complex recursive traversal, continuous streak calculations, and statistical distribution modeling. Below are five advanced algorithmic query patterns you must master before walking into a senior interview.
Pattern 8: Recursive CTEs for Hierarchical Tree Traversal
Interview question: "Given an employee hierarchy where every team member reports to a manager, generate a complete organization chart showing each employee's depth level in the company hierarchy starting from the CEO."
-- Pattern 8: Recursive CTE for Org Hierarchy
WITH RECURSIVE OrgChart AS (
-- Anchor member: Select CEO (has no manager)
SELECT
employee_id,
name,
manager_id,
1 AS hierarchy_level,
CAST(name AS VARCHAR(255)) AS management_chain
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- Recursive member: Join subordinates to previous level
SELECT
e.employee_id,
e.name,
e.manager_id,
o.hierarchy_level + 1 AS hierarchy_level,
CAST(o.management_chain || ' -> ' || e.name AS VARCHAR(255)) AS management_chain
FROM employees e
INNER JOIN OrgChart o
ON e.manager_id = o.employee_id
)
SELECT
employee_id,
name,
hierarchy_level,
management_chain
FROM OrgChart
ORDER BY hierarchy_level, employee_id;
Technical Insight: Recursive CTEs execute in two distinct phases: the anchor query establishes base result set (Level 1), and the recursive query iterates repeatedly over newly discovered records until no matching child records remain.
Pattern 9: User Retention & Consecutive Daily Streaks (Gaps & Islands)
Interview question: "Determine the longest consecutive active login streak for each user on a SaaS platform."
-- Pattern 9: Classic Gaps & Islands Problem
WITH UniqueLogins AS (
SELECT DISTINCT
user_id,
login_date::DATE AS active_date
FROM user_activity
),
GroupedStreaks AS (
SELECT
user_id,
active_date,
active_date - (ROW_NUMBER() OVER (
PARTITION BY user_id
ORDER BY active_date
) * INTERVAL '1 day') AS streak_island_group
FROM UniqueLogins
)
SELECT
user_id,
MIN(active_date) AS streak_start_date,
MAX(active_date) AS streak_end_date,
COUNT(*) AS consecutive_days_count
FROM GroupedStreaks
GROUP BY user_id, streak_island_group
ORDER BY consecutive_days_count DESC;
Interview Takeaway: Subtracting a sequential row number from a calendar date creates a constant anchor date (the "island key") for unbroken date sequences. When an activity gap occurs, the calculated anchor shifts, establishing a clean partition boundary.
Pattern 10: Rolling 7-Day Moving Averages
Interview question: "Compute the 7-day smoothed moving average of daily active users (DAU) to filter out weekend volatility."
-- Pattern 10: 7-Day Rolling Moving Average
SELECT
activity_date,
daily_active_users,
ROUND(
AVG(daily_active_users) OVER (
ORDER BY activity_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
), 2
) AS rolling_7d_avg_dau
FROM platform_metrics;
Pattern 11: Calculating Percentage of Total Across Group Partitions
Interview question: "For every individual transaction, display the purchase amount alongside the percentage of total sales that transaction contributed to its overall product department."
-- Pattern 11: Partition Contribution Ratio
SELECT
transaction_id,
department_id,
amount,
SUM(amount) OVER (PARTITION BY department_id) AS dept_total_revenue,
ROUND(
(amount * 100.0) / SUM(amount) OVER (PARTITION BY department_id),
2
) AS pct_dept_contribution
FROM transactions;
Pattern 12: Anti-Semi Joins — NOT EXISTS vs NOT IN vs LEFT JOIN
Interviewers frequently ask candidates to explain how SQL query planners execute anti-semi joins. When querying millions of rows:
NOT EXISTS (SELECT 1 FROM ...)is generally the most performant and null-safe option because database engines terminate correlated subquery execution on the first positive match (early-exit optimization).LEFT JOIN ... WHERE right.id IS NULLgenerates identical execution plans in PostgreSQL and modern MySQL when proper unique indexes exist on foreign keys.NOT IN (SELECT ...)fails catastrophically if the subquery returns even a singleNULLrow, returning zero rows for the entire outer query.
What is the difference between WHERE and HAVING in SQL?
WHERE filters individual records before any grouping or aggregation takes place. HAVING filters aggregated summaries after the GROUP BY clause has executed. You cannot use aggregate functions like SUM() or COUNT() inside a WHERE clause.
Why does NULL != NULL evaluate to unknown or false in SQL?
In standard ANSI SQL, NULL represents an unknown value rather than a literal zero or empty string. Because an unknown value cannot be logically compared to another unknown value, expressions like NULL = NULL or NULL != NULL return NULL (truth-value unknown). To test for null values, always use IS NULL or IS NOT NULL.
When should I use a CTE instead of a subquery or temporary table?
Common Table Expressions (CTEs) are preferred for readability, recursive queries, and modular pipeline development. Subqueries are suitable for simple one-off scalar checks. Temporary tables are best when intermediate datasets are referenced multiple times across long transactions.
What is the performance difference between UNION and UNION ALL?
UNION ALL merges two result sets directly without sorting, making it significantly faster. UNION executes a post-merge deduplication step requiring sorting and disk hashing. Always use UNION ALL unless duplicate elimination is strictly required.
How do indexing strategies affect SQL query execution speed?
B-Tree indexes allow database query planners to perform binary searches (O(log n)) rather than sequential full-table scans (O(n)). Indexing foreign key columns drastically accelerates multi-table JOIN operations.