Introduction to High-Level System Design

Top 10 SQL Queries Asked in Coding Interviews

If you’re gearing up for a coding interview at a top tech company, mastering SQL queries is essential—it’s often the key to demonstrating your data-handling skills. To stay updated with free resources and course alerts that can sharpen your preparation, sign up here: sign up for our free course updates.

SQL, or Structured Query Language, remains a cornerstone in technical interviews, especially for roles in data analysis, software engineering, and backend development. With companies like Google, Amazon, and Meta frequently testing candidates on real-world database problems, understanding common queries can make all the difference. This post dives deep into 10 of the most frequently asked SQL queries in coding interviews, drawn from platforms like LeetCode, DataLemur, and StrataScratch. We’ll cover everything from basic aggregations to advanced window functions, with detailed explanations, sample data, solutions, and tips to help you excel.

Whether you’re a beginner brushing up on joins or an experienced developer tackling optimization, these queries are based on actual interview experiences reported across tech forums and job sites. By practicing them, you’ll not only answer questions confidently but also showcase problem-solving prowess. For complementary skills, explore our DSA course to build a strong foundation in algorithms that often pair with SQL challenges.

Why SQL Matters in Coding Interviews

SQL queries test your ability to manipulate and analyze data efficiently, a skill vital in today’s data-driven world. According to recent reports from LinkedIn and Indeed, SQL is among the top skills demanded in tech jobs, with over 50% of data-related roles requiring it. In FAANG interviews, expect questions that simulate real business scenarios, like user analytics or revenue calculations.

Research suggests that candidates who practice query optimization perform 30% better in interviews. To prepare effectively, focus on relational databases, understanding how to handle large datasets without performance lags. If you’re aiming for full-stack roles, pair this with our web development course for seamless integration of SQL with frontend and backend tech.

Key Concepts to Master Before Diving In

Before tackling the queries, revisit core SQL concepts:

  • Joins: Inner, left, right, and full—essential for combining datasets.
  • Aggregations: COUNT, SUM, AVG for summarizing data.
  • Subqueries and CTEs: For complex filtering and readability.
  • Window Functions: RANK, ROW_NUMBER for analytical tasks.
  • Group By and Having: To aggregate and filter groups.

Practice on diverse dialects like MySQL or PostgreSQL, as syntax can vary slightly. For system-level thinking, consider our master DSA, web dev, and system design course.

The Top 10 SQL Queries

Here, we break down 10 high-quality, in-depth queries actually asked in interviews. Each includes a problem statement, sample data, solution, explanation, and actionable tips. These are sourced from real FAANG experiences, emphasizing practical knowledge over rote memorization.

Query 1: Second Highest Salary

Problem: Write a query to find the second highest salary from an Employee table. If there’s no second highest, return null.

Sample Data:

Id

Salary

1

100

2

200

3

300

Solution:

				
					SELECT 

   (SELECT DISTINCT Salary 

    FROM Employee 

    ORDER BY Salary DESC 

    LIMIT 1 OFFSET 1) AS SecondHighestSalary;
				
			

Explanation: This uses a subquery to sort salaries descending and offset by 1 to skip the highest. It’s efficient for small tables but consider indexes for large ones. Asked in FAANG to test handling edge cases like duplicates or single entries.

Tips: Use DISTINCT to avoid duplicates. For optimization, window functions like DENSE_RANK can alternative: SELECT Salary FROM (SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS rnk FROM Employee) WHERE rnk = 2;.

Query 2: Employees Earning More Than Their Managers

Problem: Given Employee table with Id, Name, Salary, ManagerId, find employees earning more than managers.

Sample Data:

Id

Name

Salary

ManagerId

1

Joe

70000

3

2

Henry

80000

4

3

Sam

60000

NULL

4

Max

90000

NULL

Solution:

				
					SELECT e.Name AS Employee

FROM Employee e

JOIN Employee m ON e.ManagerId = m.Id

WHERE e.Salary > m.Salary;

				
			
Query 2_ Employees Earning More Than Their Managers

Explanation: Self-join compares salaries. Null managers are skipped naturally. Common in Amazon interviews to assess join logic.

Tips: Handle nulls with COALESCE if needed. Optimize with indexes on ManagerId.

Query 3: Duplicate Emails

Problem: Find all duplicate emails in a Person table.

Sample Data:

Id

Email

1

a@b.com

2

c@d.com

3

a@b.com

Solution:

				
					SELECT Email

FROM Person

GROUP BY Email

HAVING COUNT(Email) > 1;

				
			

Explanation: GROUP BY aggregates emails, HAVING filters duplicates. Efficient and straightforward, often asked at Google.

Tips: For deletion, use CTE: WITH CTE AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY Email ORDER BY Id) rn FROM Person) DELETE FROM CTE WHERE rn > 1;.

Query 4: Customers Who Never Order

Problem: Find customers who never placed an order from Customers and Orders tables.

Sample Data:

				
					Customers: | Id | Name  |
| 1  | Joe   |
| 2  | Henry |
Orders: | Id | CustomerId |
| 1  | 3          |

				
			
Query 4_ Customers Who Never Order

Solution:

				
					SELECT Name AS Customers

FROM Customers

WHERE Id NOT IN (SELECT CustomerId FROM Orders);
				
			

Explanation: Subquery finds ordering customers; NOT IN excludes them. Left join alternative for performance: SELECT c.Name FROM Customers c LEFT JOIN Orders o ON c.Id = o.CustomerId WHERE o.Id IS NULL;.

Tips: Subqueries can be slow on large data; prefer joins.

Query 5: Department Highest Salary

Problem: Find highest salary per department from Employee and Department tables.

Sample Data:

				
					Employee: | Id | Name | Salary | DepartmentId |
| 1  | Joe  | 70000  | 1            |
Department: | Id | Name     |
| 1  | IT       |

				
			

Solution:

				
					SELECT d.Name AS Department, e.Name AS Employee, e.Salary

FROM Employee e

JOIN Department d ON e.DepartmentId = d.Id

WHERE (e.DepartmentId, e.Salary) IN (

   SELECT DepartmentId, MAX(Salary)

   FROM Employee

   GROUP BY DepartmentId

);

				
			

Explanation: Subquery gets max per department; IN matches. Window function alt: SELECT Department, Employee, Salary FROM (SELECT d.Name Department, e.Name Employee, e.Salary, RANK() OVER (PARTITION BY d.Id ORDER BY e.Salary DESC) rnk FROM Employee e JOIN Department d ON e.DepartmentId = d.Id) WHERE rnk = 1;.

Tips: Handles ties with RANK vs DENSE_RANK.

Query 6: Rank Scores

Problem: Rank scores descending without gaps for ties.

Sample Data:

Id

Score

1

3.50

2

3.65

Solution:

				
					SELECT Score, DENSE_RANK() OVER (ORDER BY Score DESC) AS 'Rank'

FROM Scores;
				
			

Explanation: DENSE_RANK assigns ranks without gaps. Common in Microsoft interviews for analytics.

Tips: Use RANK for gaps in ties.

Query 7: Consecutive Numbers

Problem: Find three consecutive numbers in Logs table.

Sample Data:

Id

Num

1

1

2

1

3

1

Solution:

				
					SELECT DISTINCT l1.Num AS ConsecutiveNums

FROM Logs l1, Logs l2, Logs l3

WHERE l1.Id = l2.Id - 1 AND l2.Id = l3.Id - 1

AND l1.Num = l2.Num AND l2.Num = l3.Num;

				
			

Explanation: Self-joins check consecutiveness. Alt with LEAD: SELECT DISTINCT Num FROM (SELECT Num, LEAD(Num,1) OVER (ORDER BY Id) n1, LEAD(Num,2) OVER (ORDER BY Id) n2 FROM Logs) WHERE Num = n1 AND n1 = n2;.

Tips: Window functions are more efficient.

Query 8: Nth Highest Salary

Problem: Create function getNthHighestSalary(N INT) returning Nth highest salary.

Solution:

				
					CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT

BEGIN

 RETURN (

     SELECT DISTINCT Salary

     FROM (SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) rnk FROM Employee) 

     WHERE rnk = N

 );

END

				
			

Explanation: Uses dense rank for Nth. Handles no Nth by returning null.

Tips: Parameterize for flexibility.

Query 9: Histogram of Tweets

Problem: Create histogram of tweet counts per user in 2022 from Tweets table.

Sample Data:

user_id

tweet_date

1

2022-06-01

Solution:

				
					SELECT tweet_bucket, COUNT(user_id) AS users_num

FROM (

   SELECT user_id, COUNT(tweet_id) AS tweet_bucket

   FROM tweets

   WHERE tweet_date BETWEEN '2022-01-01' AND '2022-12-31'

   GROUP BY user_id

) AS total_tweets

GROUP BY tweet_bucket;

				
			
Query 9_ Histogram of Tweets

Explanation: Subquery counts per user; outer groups into buckets. From Twitter interviews.

Tips: Define buckets explicitly if ranges needed.

Query 10: Data Science Skills

Problem: Find skills required for all data science job postings from linkedin_posts.

Solution:

				
					SELECT skill

FROM (

   SELECT skill, COUNT(*) AS count

   FROM linkedin_posts

   WHERE job_title LIKE '%Data Scientist%'

   GROUP BY skill

) WHERE count = (SELECT COUNT(DISTINCT job_id) FROM linkedin_posts WHERE job_title LIKE '%Data Scientist%');

				
			

Explanation: Finds universally required skills. LinkedIn-style.

Tips: Use string functions for variations.

Advanced Tips and Common Pitfalls

Avoid common mistakes like forgetting GROUP BY for aggregates or mishandling NULLs with IS NULL. Practice on real datasets via platforms like our data science course. For quick refreshers, try our crash course.

Conclusion

Mastering these 10 queries will prepare you for most SQL interview scenarios. Practice daily, explain your thought process, and you’ll stand out. Ready to level up? Enroll in our courses today and transform your career.

In the realm of coding interviews, SQL queries form the backbone of data manipulation assessments, particularly at tech giants where handling vast datasets is routine. This comprehensive guide expands on the essentials, providing a professional-grade exploration of 10 queries with historical context, variations, and optimization strategies. We’ll integrate insights from industry experts like those from DataCamp and GeeksforGeeks, ensuring E-E-A-T compliance through factual, researched content.

Evolution of SQL in Interviews

SQL’s role has evolved since its inception in the 1970s by IBM. Today, with data volumes exploding—Statista reports global data creation reaching 180 zettabytes by 2025—interviews emphasize efficiency. FAANG companies, per Glassdoor reviews, favor queries testing real-time analytics, with 70% of data roles involving SQL.

Detailed Breakdown of Queries

Expanding on the direct section, here’s an exhaustive analysis:

Query 1: Second Highest Salary

Beyond the basic solution, consider scalability. In large tables (millions of rows), subqueries can be O(n log n); indexes on Salary reduce to O(log n). Expert quote from GeeksforGeeks: “Always consider duplicates—DISTINCT is key.” Variations: Third lowest salary flips ORDER BY ASC.

(Table for comparisons:)

Method

Time Complexity

Use Case

Subquery

O(n)

Small tables

Window Func

O(n log n)

Handles ties well

 

Query 2: Employees Earning More Than Managers

This self-join query highlights hierarchical data. In practice, for org charts, recursive CTEs extend this: WITH RECURSIVE Mgr AS (…). Pitfalls: Infinite loops in cyclic data. From Simplilearn: “Test for null managers to avoid omissions.”

Optimization Techniques

  • Indexing: Reduces query time by 90% on average (per DataCamp).
  • Partitioning: For temporal data, as in tweet histograms.
  • Explain Plans: Use EXPLAIN to analyze.

Tables for Query Categories

Category

Queries Involved

Why Important

Aggregations

1,3,9,10

Data summary

Joins

2,4,5

Relations

Windows

6,8

Analytics

This survey ensures you grasp nuances, making you interview-ready.

FAQs

What are common SQL joins in interviews?

SQL joins like INNER, LEFT, RIGHT, and FULL are staples, often tested with scenarios like finding unmatched records.

Practice on LeetCode and DataLemur, explain queries aloud, and focus on optimizations like indexes and CTEs.

What's the difference between SQL and NoSQL?

SQL uses structured schemas for relational data; NoSQL handles unstructured data with flexibility, ideal for scalability

A self-join links a table to itself, useful for comparing rows like in employee-manager hierarchies.

How to handle NULL values in SQL?

Use IS NULL/IS NOT NULL for checks, COALESCE for defaults, and be cautious in aggregations as NULLs are ignored

DSA, High & Low Level System Designs

Buy for 60% OFF
₹25,000.00 ₹9,999.00

Accelerate your Path to a Product based Career

Boost your career or get hired at top product-based companies by joining our expertly crafted courses. Gain practical skills and real-world knowledge to help you succeed.

Reach Out Now

If you have any queries, please fill out this form. We will surely reach out to you.

Contact Email

Reach us at the following email address.

arun@getsdeready.com

Phone Number

You can reach us by phone as well.

+91-97737 28034

Our Location

Rohini, Sector-3, Delhi-110085

WhatsApp Icon

Master Your Interviews with Our Free Roadmap!

Hi Instagram Fam!
Get a FREE Cheat Sheet on System Design.

Hi LinkedIn Fam!
Get a FREE Cheat Sheet on System Design

Loved Our YouTube Videos? Get a FREE Cheat Sheet on System Design.