Joins & Aggregations
- 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,
EXISTSvsIN
Q1.Write a query to find departments where the average salary is higher than the company average.
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
- Ranking —
ROW_NUMBER(),RANK(),DENSE_RANK(),NTILE() - Aggregate —
SUM(),AVG(),COUNT()withOVER()clause - Navigation —
LAG(),LEAD(),FIRST_VALUE(),LAST_VALUE() - Frame clauses —
ROWS BETWEENandRANGE BETWEEN
Q2.Write a query to find each employee's salary rank within their department.
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.
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
- EXPLAIN plans — reading execution plans, identifying bottlenecks
- Indexing — B-tree, hash, composite, and covering indexes
- Query rewrites — replacing correlated subqueries, using
EXISTSvsIN - Data modeling — denormalization, materialized views, partitioning
Q4.A query is running slowly. How would you diagnose and optimize it?
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.
Don't freeze in your next interview
InterviewsUnlocked gives you real-time AI coaching during live interviews — role-tailored answers, follow-up cues, and confidence when you need it most.
Related Resources
Top Data Analyst Interview Questions & Answers
Master your data analyst interview with questions on SQL, statistics, data visualization, business acumen, and real-world case studies with detailed answers.
Read moreInterview QuestionsTop Data Scientist Interview Questions & Answers
Prepare for data science interviews with expert questions on machine learning, statistics, Python, deep learning, and A/B testing with detailed model answers.
Read moreSkills & TechnologiesPython Interview Questions & Answers for All Levels
Comprehensive Python interview prep covering core language features, OOP, data structures, concurrency, and real-world coding questions with expert answers.
Read moreInterview TipsTechnical Interview Preparation: A 4-Week Plan
A structured 4-week technical interview preparation plan covering data structures, algorithms, system design, and mock interviews with daily schedules.
Read moreCompany InterviewsGoogle Interview Guide: Process, Questions & Tips
Complete Google interview guide covering the hiring process, common questions across engineering, PM, and analyst roles, and insider tips to stand out.
Read more