MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Back to all articles
Database & SQL9 min read•Published 2026-09-25

Top 30 SQL Queries Asked in Data Analyst & Backend Developer Interviews with Solutions

Master the most frequently asked SQL coding questions in technical interviews: 2nd highest salary, duplicate detection, window functions, self joins, and running totals.

Er. Sumit Kumar
Er. Sumit Kumar
Founder & Lead Technical Mentor
Top 30 SQL Queries Asked in Data Analyst & Backend Developer Interviews with Solutions

Whether you are applying for a Data Analyst, Business Intelligence Engineer, or Backend Software Developer role at companies like Amazon, Swiggy, TCS, or modern tech startups, SQL live coding rounds are the primary barrier between you and the offer letter.

Recruiters don't just test basic SELECT * FROM table; queries. They want to see if you can handle NULL values, tie-breaking logic, self joins, Common Table Expressions (CTEs), and modern window functions.

Here is an essential collection of the top SQL queries most frequently tested in technical rounds, complete with tested syntax and logic explanations compiled by Er. Sumit Kumar at MSK Institute.


1. How to Find the Nth (or 2nd) Highest Salary in an Employee Table?

This is unanimously the single most asked SQL interview problem in India!

Method A: Using DENSE_RANK() (Recommended Industry Standard)

DENSE_RANK() handles duplicates and ties seamlessly without skipping ranks:

1WITH RankedSalaries AS (
2 SELECT
3 emp_id,
4 emp_name,
5 salary,
6 DENSE_RANK() OVER (ORDER BY salary DESC) as rank_pos
7 FROM employees
8)
9SELECT emp_name, salary
10FROM RankedSalaries
11WHERE rank_pos = 2; -- Change to N for Nth highest!

Method B: Subquery with MAX()

1SELECT MAX(salary) AS second_highest_salary
2FROM employees
3WHERE salary < (SELECT MAX(salary) FROM employees);

Method C: Using LIMIT & OFFSET (MySQL / PostgreSQL)

1SELECT salary
2FROM employees
3ORDER BY salary DESC
4LIMIT 1 OFFSET 1; -- Skip top 1, pick 2nd
Pro Tip
Interview Caution: Always ask the interviewer: "How should we handle ties if multiple employees earn the exact same salary?" Answering with DENSE_RANK() demonstrates senior engineering maturity!

2. How to Find and Delete Duplicate Records from a Table?

Given a table with accidental duplicate rows, how do you keep only one unique copy?

Finding Duplicates:

1SELECT email, COUNT(*) AS duplicate_count
2FROM users
3GROUP BY email
4HAVING COUNT(*) > 1;

Deleting Duplicates using CTE and ROW_NUMBER():

1WITH NumberedRows AS (
2 SELECT
3 id,
4 email,
5 ROW_NUMBER() OVER (PARTITION BY email ORDER BY id ASC) as row_num
6 FROM users
7)
8DELETE FROM users
9WHERE id IN (
10 SELECT id FROM NumberedRows WHERE row_num > 1
11);

3. Difference Between RANK(), DENSE_RANK(), and ROW_NUMBER()

Consider three employees with salaries: 100k, 100k, 80k. Look at how each window function assigns ranks:

SalaryROW_NUMBER()RANK()DENSE_RANK()
100k111
100k211
80k33 (Skips 2!)2 (Never skips!)
  • ROW_NUMBER(): Assigns a strictly unique incremental integer to every row regardless of duplicate values.
  • RANK(): Gives identical rank to ties, but skips the next rank numbers.
  • DENSE_RANK(): Gives identical rank to ties, and continues sequentially without skipping numbers.

4. How to Calculate a Running Total (Cumulative Sum) in SQL?

A favorite in financial and e-commerce analytics interviews:

1SELECT
2 order_date,
3 daily_amount,
4 SUM(daily_amount) OVER (
5 ORDER BY order_date ASC
6 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
7 ) AS running_total
8FROM daily_sales;

5. Self-Join: Find Employees Who Earn More Than Their Managers

Given an employees table with emp_id, emp_name, salary, and manager_id:

1SELECT
2 e.emp_name AS Employee,
3 e.salary AS EmpSalary,
4 m.emp_name AS Manager,
5 m.salary AS ManagerSalary
6FROM employees e
7JOIN employees m ON e.manager_id = m.emp_id
8WHERE e.salary > m.salary;

6. How to Find Records Present in Table A but NOT in Table B?

Example: Find customers who registered on your platform but never placed an order.

Method A: Using LEFT JOIN (High Performance)

1SELECT c.customer_id, c.name
2FROM customers c
3LEFT JOIN orders o ON c.customer_id = o.customer_id
4WHERE o.order_id IS NULL;

Method B: Using NOT EXISTS

1SELECT c.customer_id, c.name
2FROM customers c
3WHERE NOT EXISTS (
4 SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
5);

7. How to Calculate Year-over-Year (YoY) Sales Growth Using LAG()?

1WITH AnnualSales AS (
2 SELECT
3 EXTRACT(YEAR FROM order_date) AS sales_year,
4 SUM(revenue) AS total_revenue
5 FROM sales
6 GROUP BY EXTRACT(YEAR FROM order_date)
7)
8SELECT
9 sales_year,
10 total_revenue,
11 LAG(total_revenue, 1) OVER (ORDER BY sales_year) AS prev_year_revenue,
12 ROUND(
13 (total_revenue - LAG(total_revenue, 1) OVER (ORDER BY sales_year)) * 100.0 /
14 LAG(total_revenue, 1) OVER (ORDER BY sales_year), 2
15 ) AS yoy_growth_pct
16FROM AnnualSales;

8. What is the Difference Between WHERE and HAVING?

  • WHERE: Filters individual rows before any grouping or aggregation takes place. It cannot evaluate aggregate functions like SUM() or COUNT().
  • HAVING: Filters grouped summary rows after the GROUP BY clause has aggregated the data.
1-- Valid SQL showing both in action:
2SELECT department_id, AVG(salary) AS avg_sal
3FROM employees
4WHERE status = 'Active' -- Filters raw rows first
5GROUP BY department_id
6HAVING AVG(salary) > 50000; -- Filters aggregated groups

9. Summary & 3 Best Practices for SQL Interviews

  1. 1
    Always State Your Assumptions: Before writing queries, confirm whether column values can be NULL or contain duplicate keys.
  2. 2
    Format Queries with Clean Uppercase Keywords: Writing clauses on new indented lines makes your solution look professional and readable.
  3. 3
    Practice on Live Datasets: Don't just read queries passively. Test and modify complex joins inside our live MSK Code Playground or join our Data Analysis Combo Cohort to master 100+ business SQL queries under direct mentor feedback!
Tags:#SQL#Database#Data Analyst#Backend Developer#Interview Questions#MySQL
Recommended Training Programs

Master These Skills in Our Offline Labs

Beginner to Advanced12 MONTHS

Data Analysis Mastery Combo Course - 12 Months

Master full-stack Data Analytics in 12 months across 15 specialized courses, 150 chapters, and 541 structured topics—covering Excel, SQL, Python, NumPy, Pandas, Statistics, Matplotlib/Seaborn/Plotly, Power BI, Tableau, and Machine Learning.

Explore Course Curriculum
Advanced8 MONTHS

Python Backend Development Mastery Combo - 8 Months

Become a professional Python Backend Developer with this 8-month program covering Django, ORM, REST APIs, Authentication, Deployment, and Advanced Backend Concepts.

Explore Course Curriculum