Skills & Technologies

SQL Interview Questions: From Basics to Advanced Queries

17 min readUpdated April 30, 2025
SQLdatabasewindow functions
SQL is the single most tested technical skill across data analyst, data scientist, data engineer, and backend developer interviews. Regardless of the specific role, the ability to write correct, efficient queries against relational databases is fundamental. This guide covers SQL interview questions from basic joins to advanced window functions, CTEs, and query optimization — with answers that explain not just the solution but the reasoning behind it.

Joins & Aggregations

These form the foundation of SQL interviews. If you can't write joins and aggregations confidently, nothing else matters. Key concepts to master: • JOIN types — INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, CROSS JOIN • Aggregation functions — COUNT, SUM, AVG, MIN, MAX, GROUP BY, HAVING • Subqueries — correlated vs non-correlated, EXISTS vs IN

Q1.Write a query to find departments where the average salary is higher than the company average.

intermediate
Solution using HAVING: SELECT d.department_name, AVG(e.salary) as avg_dept_salary FROM employees e JOIN departments d ON e.department_id = d.id GROUP BY d.department_name HAVING AVG(e.salary) > (SELECT AVG(salary) FROM employees) Key concepts: • GROUP BY to aggregate by department • HAVING to filter groups (not WHERE — WHERE filters rows before aggregation, HAVING filters after) • A subquery for the company-wide average Alternative using a CTE: WITH company_avg AS ( SELECT AVG(salary) as avg_sal FROM employees ) SELECT d.department_name, AVG(e.salary) FROM employees e JOIN departments d ON e.department_id = d.id, company_avg GROUP BY d.department_name HAVING AVG(e.salary) > company_avg.avg_sal The CTE approach is more readable and avoids recomputing the subquery.

Window Functions

Window functions are heavily tested in interviews because they demonstrate advanced SQL thinking. Essential window functions to know: • Ranking — ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE() • Aggregate — SUM(), AVG(), COUNT() with OVER() clause • Navigation — LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE() • Frame clauses — ROWS BETWEEN and RANGE BETWEEN

Q2.Write a query to find each employee's salary rank within their department.

intermediate
Solution: SELECT employee_name, department_id, salary, RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) as salary_rank FROM employees Understanding the variants: • RANK() — leaves gaps after ties (1, 1, 3) • DENSE_RANK() — doesn't leave gaps (1, 1, 2) • ROW_NUMBER() — assigns unique numbers even for ties (1, 2, 3 — non-deterministic for ties) When to use each: • Use RANK when you want to know position including ties • Use DENSE_RANK when you want the count of distinct values ahead of you • Use ROW_NUMBER when you need unique ordering (e.g., deduplication — take the first row per group) The PARTITION BY clause resets the ranking for each department; without it, you'd rank across the entire company.

Q3.Calculate a 7-day rolling average of daily revenue.

advanced
Solution: SELECT date, revenue, AVG(revenue) OVER ( ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) as rolling_7day_avg FROM daily_revenue ORDER BY date Key details: • ROWS BETWEEN 6 PRECEDING AND CURRENT ROW gives you exactly 7 rows (current + 6 prior) • The alternative RANGE BETWEEN is date-aware but works differently — it considers actual date values, not row positions Handling gaps in dates: For a true calendar-day rolling average with gaps, either: • Fill the gaps first (generate a date series and LEFT JOIN) • Use RANGE with an interval Edge case: The first 6 rows will have averages over fewer than 7 days. To exclude those, wrap in a subquery and filter WHERE row_number >= 7.

Query Optimization

Senior roles expect you to think about query performance, not just correctness. Areas to cover: • EXPLAIN plans — reading execution plans, identifying bottlenecks • Indexing — B-tree, hash, composite, and covering indexes • Query rewrites — replacing correlated subqueries, using EXISTS vs IN • Data modeling — denormalization, materialized views, partitioning

Q4.A query is running slowly. How would you diagnose and optimize it?

advanced
Step 1: Analyze the execution plan Run EXPLAIN ANALYZE (PostgreSQL) or EXPLAIN (MySQL) to see the query plan. Look for: • Sequential scans on large tables (suggests a missing index) • Nested loop joins on large tables (consider hash or merge joins) • High estimated vs actual row counts (suggests stale statistics — run ANALYZE) Step 2: Check for missing indexes • If the WHERE clause filters on a column with no index, add one • But don't over-index — each index slows writes and consumes storage • Consider composite indexes for multi-column filters Step 3: Rewrite the query • Replace correlated subqueries with JOINs • Use EXISTS instead of IN for large subqueries • Avoid SELECT * — fetch only needed columns • Use LIMIT for exploratory queries Step 4: Consider the data model • Denormalization for read-heavy workloads • Materialized views for expensive aggregations • Partitioning for very large tables (by date, region, etc.)

Frequently Asked Questions

Which SQL dialect should I learn for interviews?+

Standard SQL (ANSI SQL) works everywhere. PostgreSQL is the most commonly used in interviews and has the richest feature set (window functions, CTEs, JSONB). MySQL is also common. The syntax differences are minor — learn standard SQL well and note dialect-specific functions when needed.

How do I practice SQL for interviews?+

Use LeetCode's SQL problems (sorted by difficulty), StrataScratch for company-specific SQL questions, and Mode Analytics SQL tutorial for real-world datasets. Practice writing queries by hand first, then verify in a database. Speed and accuracy matter in live interviews.

Do I need to know NoSQL for SQL-focused interviews?+

Not typically, but understanding when to choose SQL vs NoSQL shows system-level thinking. Know the tradeoffs: SQL excels at structured data with relationships; NoSQL excels at flexible schemas, horizontal scaling, and simple key-based access patterns.

Ready to land your dream job?

CareerUplift gives you AI-powered mock interviews, an ATS-optimized resume builder, and personalized coaching — everything you need to get hired faster.

Related Articles