📥 Download Complete 2026 Printable PDF Notes, Architecture Diagrams & GitHub Code
Get instant free access to the 2026 printable PDF cheat-sheet, runnable lab repositories, interview evaluation rubric, and AI Campus 6-Month Paid Corporate Internship roadmap.
Download Free PDF & Syllabus Roadmap →Top 12 SQL Technical Interview Questions for Data Analysts & BI Engineers (2026)
Advanced SQL window functions, CTEs, query optimization, EXPLAIN execution plans, and analytical queries asked during Data Analyst, BI Developer, and Analytics Engineer interviews:
Q1 Explain RANK() vs DENSE_RANK() vs ROW_NUMBER() with tie-breaking examples.
SELECT student, score,
ROW_NUMBER() OVER (ORDER BY score DESC) AS rn,
RANK() OVER (ORDER BY score DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY score DESC) AS drnk
FROM test_scores; If two students tie for 1st place with a score of 98: ROW_NUMBER() assigns strictly consecutive numbers (1, 2) non-deterministically. RANK() assigns tied values the same rank and skips subsequent ranks to maintain count alignment (1, 1, 3). DENSE_RANK() assigns tied values the same rank but does NOT skip any numbers (1, 1, 2).
Q2 When should you use Common Table Expressions (CTEs) vs Subqueries vs Temporary Tables?
WHERE col IN (SELECT ...). Can hurt readability when nested 3+ levels deep. CTEs (WITH clause): Named temporary result sets defined at the query top. Dramatically improve readability, break complex business logic into modular steps, and enable Recursive CTEs for hierarchical data (org charts, graph traversal). Modern query optimizers inline CTEs without performance penalties. Temporary Tables (#temp / CREATE TEMP TABLE): Physical tables written to disk/tempdb. Indispensable for massive multi-million row batch pipelines where intermediate datasets need explicit indexes created to optimize subsequent joins.
Q3 How do Window Functions with LEAD, LAG, and NTILE calculate period-over-period growth?
SELECT month, revenue,
LAG(revenue, 1) OVER (ORDER BY month) AS prev_revenue,
ROUND((revenue - LAG(revenue, 1) OVER (ORDER BY month)) /
LAG(revenue, 1) OVER (ORDER BY month) * 100, 2) AS mom_growth_pct
FROM monthly_sales; LEAD(): Looks forward into future rows. NTILE(N): Divides an ordered partition into N equal quartiles or percentiles (e.g. NTILE(4) creates quartiles for customer spending tiers).
Q4 Explain Correlated Subqueries vs JOINs: Why are JOINs typically faster?
O(M * N)). Modern SQL engines optimize JOINs into Hash Joins or Merge Joins, processing datasets in single-pass linear time O(M + N) with parallel execution.
Q5 How does SQL handle NULL values in aggregations, Boolean logic, and JOIN conditions?
TRUE, FALSE, and UNKNOWN. Comparisons like NULL = NULL evaluate to UNKNOWN, never TRUE (use IS NULL / IS NOT NULL). In JOIN conditions, rows with NULL keys never match unless explicitly handled using COALESCE or IS NOT DISTINCT FROM. In aggregate functions: COUNT(*) counts all rows including NULLs, whereas COUNT(column_name), AVG(column), and SUM(column) strictly ignore NULL values.
Q6 Explain Database Index internals: B-Tree vs Hash Index, and how to read EXPLAIN ANALYZE.
=), range queries (BETWEEN, >, <), and ORDER BY sorting. Hash Index: Uses an in-memory hash table for ultra-fast O(1) equality lookups, but cannot support range queries or sorting. EXPLAIN ANALYZE: Executes the query and outputs the actual query plan. Watch for: Seq Scan (table scan on large tables indicating missing indexes), Index Scan vs Index Only Scan (where all required columns are in the index), and differences between estimated rows vs actual rows indicating stale database statistics.
Q7 What is the operational difference between WHERE and HAVING in SQL aggregations?
WHERE SUM(sales) > 1000 is invalid syntax). HAVING: Filters aggregated summary groups after the GROUP BY clause has executed. Best practice: Always filter as many rows as possible in the WHERE clause first to reduce the volume of data flowing into memory for grouping.
Q8 How do you perform Dynamic Pivoting in SQL using CASE WHEN and modern PIVOT clauses?
SELECT salesperson_id,
SUM(CASE WHEN region = 'North' THEN sales_amount ELSE 0 END) AS north_sales,
SUM(CASE WHEN region = 'South' THEN sales_amount ELSE 0 END) AS south_sales,
SUM(CASE WHEN region = 'West' THEN sales_amount ELSE 0 END) AS west_sales
FROM transactions
GROUP BY salesperson_id; This cross-tabulation handles arbitrary metrics cleanly and works across PostgreSQL, MySQL, Snowflake, and SQL Server.
Q9 How do Self Joins resolve hierarchical data (e.g. Employee-to-Manager mapping)?
SELECT e.employee_id, e.name AS employee_name,
COALESCE(m.name, 'Top Executive (No Manager)') AS manager_name
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.employee_id; Using a LEFT JOIN ensures that top executives with manager_id = NULL are retained in the reporting hierarchy.
Q10 How do you handle Date-Time analytics in SQL (DATE_TRUNC, DATEDIFF, intervals)?
'2026-03-15 14:32:00' becomes '2026-03-01 00:00:00'), allowing clean grouping by month. To calculate active user cohort churn: combine DATE_TRUNC with INTERVAL '30 days' and window functions to measure days elapsed between successive user sessions.
Q11 What is the difference between UNION and UNION ALL: Performance and execution?
UNION ALL in production.
Q12 Compare OLTP (Row-Oriented) vs OLAP (Column-Oriented) database storage mechanics.
AVG(sales_amount) across 100M rows reads only the single column block from disk with extreme compression (ZSTD, Parquet dictionary encoding), skipping the other 50 columns entirely.
Q1 What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER() in SQL?
ROW_NUMBER() assigns a unique sequential integer to every row within a partition regardless of ties.
RANK() assigns identical ranks to tied rows, skipping subsequent rank numbers (e.g. 1, 2, 2, 4).
DENSE_RANK() assigns identical ranks to ties without skipping numbers (e.g. 1, 2, 2, 3).
Q2 How do Common Table Expressions (CTEs) work, and when do you use recursive CTEs?
CTEs define a temporary, named result set using WITH. Recursive CTEs refer to themselves to traverse hierarchical data such as organizational charts or nested bill-of-materials.
Q3 Explain the difference between B-Tree indexes, Hash indexes, and Composite indexes.
B-Tree indexes maintain balanced hierarchical trees that support range queries (<, >, BETWEEN) and equality queries.
Hash indexes only support exact equality (=) lookups with O(1) complexity.
Composite indexes cover multiple columns; queries must respect the leftmost prefix rule to utilize the index.
Q4 What is the difference between WHERE and HAVING clauses?
WHERE filters individual rows before aggregation occurs and cannot use aggregate functions.
HAVING filters aggregated groups after the GROUP BY clause has evaluated.
Q5 What are Correlated Subqueries and why can they cause significant performance bottlenecks?
A correlated subquery references columns from the outer query, forcing the database engine to execute the inner query once for every single candidate row in the outer query.
Rewriting correlated subqueries with JOINs or window functions allows the optimizer to execute single-pass hash or merge joins.
Q6 Explain ACID properties in relational database management systems.
Atomicity guarantees all operations in a transaction succeed or all roll back.
Consistency ensures data meets all schema constraints and foreign keys.
Isolation prevents concurrent transactions from interfering (Read Committed, Repeatable Read, Serializable).
Durability guarantees committed changes survive power failures via write-ahead logging (WAL).
Q7 How do you find the Nth highest salary in SQL using window functions or LIMIT/OFFSET?
Using DENSE_RANK() ensures that salary ties are handled accurately across the enterprise.
Q8 What is the difference between UNION and UNION ALL?
UNION combines query results and performs a costly deduplication sort pass across all records.
UNION ALL concatenates datasets directly without deduplication, executing much faster when uniqueness is already guaranteed.
Q9 How do window aggregate functions with framing (ROWS BETWEEN) calculate rolling sums?
Framing specifications define the dynamic subset of rows within a partition evaluated for each row.
Q10 What is database normalization (1NF, 2NF, 3NF, BCNF) vs denormalization in data warehousing?
Normalization eliminates data redundancy and update anomalies in OLTP systems.
Denormalization deliberately introduces redundancy into star schemas and snowflake schemas in data warehouses to eliminate expensive multi-table joins for analytical OLAP workloads.
Accelerate Your Career with Guaranteed Paid Internship*
Transparent ₹1,20,000 Fee (Inclusive of GST) • ₹10,000/month No-Cost EMI • 6-Month Corporate Paid Internship (₹15,000 – ₹35,000/mo stipend) with official IBM & Microsoft Credly credentials.
