📢
Admissions Open | Free Career Counselling | Limited Scholarships
Register Now →

Interview Preparation

SQL Interview Questions and Answers: 50 Questions Tested on Real Data (2026)

50 SQL interview questions with answers tested on one practice dataset: basics, queries, joins, window functions and indexes, plus Indian round formats.

SQL interview questions guide cover showing a candidate explaining a SQL answer in an interview

Most lists of SQL interview questions give you an answer you can't check.

You read "find the second highest salary", nod along, and then freeze when the interviewer asks "what if two people tie?"

This guide fixes that. Every query below runs against one small practice dataset you can download, and we show the real output. You'll get 50 SQL interview questions (basics, queries, joins, window functions and indexes), how rounds actually work at Indian companies, the 7 mistakes that sink most candidates, and a 7-day prep plan.

SQL interview questions are technical questions that test whether you can store, filter, combine and summarise data in a relational database using Structured Query Language. Freshers mostly get definitions (keys, joins, normalization) and simple queries. Data analyst and experienced roles add GROUP BY, window functions, CTEs and query performance, usually as live queries on a shared screen.

Quick answer: SQL interview questions (November 2026)

  • The most tested topics are joins, GROUP BY with HAVING, subqueries, NULL handling, window functions (ROW_NUMBER, RANK, DENSE_RANK, LAG) and indexes.
  • IT services firms such as Infosys and Accenture lean heavily on theory, according to 2026 Glassdoor interview reviews, and an Infosys reviewer was asked for the second highest salary without LIMIT.
  • Five queries come up again and again: second highest salary, duplicate rows, employees earning more than their manager, top N per group and running totals.
  • SQL was used by 58.6% of developers in the Stack Overflow 2025 Developer Survey, so it stays a core filter for analyst, developer and data engineer roles.
  • A focused 7-day plan (basics, filtering, joins, CTEs, window functions, indexes, one timed mock) is enough to revise for most fresher rounds.

Contents

  1. How SQL Interview Rounds Work in India
  2. The Practice Dataset Used in This Guide
  3. Basic SQL Interview Questions for Freshers (1 to 15)
  4. SQL Query Interview Questions (16 to 32)
  5. Window Functions and Advanced SQL Interview Questions (33 to 42)
  6. SQL Interview Questions for Experienced Candidates (43 to 50)
  7. 7 SQL Interview Mistakes, With Wrong and Right Queries
  8. The DEEP Method: How to Answer Any SQL Question Out Loud
  9. A 7-Day SQL Interview Prep Plan
  10. FAQ

How SQL Interview Rounds Work in India

SQL interview rounds in India usually follow one of three patterns, depending on the type of employer. Knowing which one you face tells you whether to revise theory or practise live queries.

Employer typeTypical SQL roundWhat they checkPrepare
IT services (TCS, Infosys, Wipro, Accenture)Online test, then a technical interview with theory and 1 to 2 queriesDefinitions, keys, joins, normalization, DELETE vs TRUNCATEQuestions 1 to 20
Product companies and startupsLive coding on a shared screen or a platform like HackerRankWindow functions, CTEs, edge cases, clean logicQuestions 21 to 42
Analytics, MIS and BI roles (SQL interview questions for data analyst jobs)Business questions on sales or HR tables, sometimes alongside ExcelGROUP BY, CASE, date logic, percentagesQuestions 16 to 36

Candidate reports back this up. One 2026 Infosys data analyst reviewer on Glassdoor said the technical round covered SQL, Excel and basic data interpretation, and they were asked to find the second highest salary without using LIMIT. An Accenture data analyst candidate described the round as mostly concept-oriented theory on SQL tables and database management.

Infographic comparing SQL interview rounds at IT services, product companies and analytics roles in India

The skill itself isn't going anywhere. SQL was used by 58.6% of respondents in the Stack Overflow 2025 Developer Survey, and PostgreSQL (55.6%) and MySQL (40.5%) were the most used databases in the same survey.

The Practice Dataset Used in This Guide

The Fireblaze SQL practice dataset is a 4-table schema (departments, employees, customers, orders) with 36 rows. It is built to trigger the edge cases interviewers love: a salary tie, a NULL salary, an employee with no department, a department with no employees, a customer with no orders and one duplicate order.

Entity relationship diagram of the practice dataset with departments, employees, customers and orders tables

Download: fireblaze_sql_practice.sql, with the answer key fireblaze_sql_answers.sql. The practice file runs on MySQL 8, PostgreSQL 13+ and SQLite 3.25+.

Here are the rows you need to follow the answers:

employees (salary is monthly, in INR)

emp_idemp_namedept_idmanager_idsalaryhire_date
1Anita Deshmukh20NULL2,10,0002017-04-01
2Rahul Patil1011,20,0002018-06-15
3Sneha Kulkarni10265,0002021-01-10
4Vikram Joshi10265,0002022-03-05
5Pooja Wankhede10248,0002024-07-01
6Amit Shinde20195,0002019-09-20
7Neha Bhosale2061,05,0002020-11-11
8Karan Mehta30155,0002023-02-14
9Riya Gawande30842,0002025-05-19
10Sagar Thakre401NULL2026-08-01
11Mayur RautNULL238,0002026-09-15

departments: 10 Analytics, 20 Engineering, 30 Sales, 40 HR, 50 Research (no employees).

customers: 101 Orange City Traders, 102 Deccan Retail, 103 Vidarbha Agro, 104 Konkan Foods, 105 Sitabuldi Mobiles, 106 Wardha Textiles (never ordered).

orders: 14 orders from January to May 2026, with statuses Delivered, Cancelled and Returned. Order 1012 duplicates order 1011.

How we tested: every query in this guide was run against this dataset on SQLite 3.53, and the outputs shown are copied from those runs. Questions 29, 38 and 40 are shown in MySQL 8 syntax with PostgreSQL alternatives in the comments; the SQLite versions in the downloadable answer key produce the same outputs.

Basic SQL Interview Questions for Freshers (1 to 15)

Basic SQL interview questions for freshers check vocabulary: keys, commands, constraints and the difference between similar-sounding clauses. Answer each in two or three sentences, then give a one-line example.

1. What is SQL?

SQL (Structured Query Language) is the standard language for creating, reading, updating and deleting data in relational databases. You use it to tell the database what result you want, and the database decides how to fetch it. MySQL, PostgreSQL, SQL Server and Oracle all use SQL, with small differences in syntax.

2. What is the difference between SQL and MySQL?

SQL is the language; MySQL is a database management system that understands it. PostgreSQL, SQL Server, Oracle and SQLite are other systems that speak SQL. A good one-liner: "SQL is like English, MySQL is one person who speaks it with an accent."

3. What are DDL, DML, DCL and TCL commands?

SQL commands fall into four groups:

GroupPurposeCommands
DDL (Data Definition Language)Define structureCREATE, ALTER, DROP, TRUNCATE
DML (Data Manipulation Language)Change dataINSERT, UPDATE, DELETE (SELECT is often grouped here or as DQL)
DCL (Data Control Language)PermissionsGRANT, REVOKE
TCL (Transaction Control Language)TransactionsCOMMIT, ROLLBACK, SAVEPOINT

4. What is a primary key?

A primary key is a column (or set of columns) that uniquely identifies each row. It can't be NULL and can't repeat.

In the dataset, emp_id is the primary key of employees. Each table can have only one primary key.

5. What is a foreign key?

A foreign key is a column that points to the primary key of another table, which keeps related data consistent. employees.dept_id references departments.dept_id, so you can't assign an employee to a department that doesn't exist. manager_id is a foreign key that points back to the same table.

6. What is the difference between a primary key and a unique key?

Both prevent duplicate values. A table has one primary key, which never allows NULL.

It can have many unique keys, and most databases allow NULL in a unique column (SQL Server allows only one NULL). dept_name is a unique key in the dataset.

7. What are constraints in SQL?

Constraints are rules the database enforces on data: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK and DEFAULT. They stop bad data at the door, so your queries don't have to clean it up later.

8. What is the difference between DELETE, TRUNCATE and DROP?

CommandRemovesWHERE allowedRollbackStructure kept
DELETESelected rowsYesYes, inside a transactionYes
TRUNCATEAll rowsNoDepends on the database (PostgreSQL and SQL Server yes, MySQL no)Yes
DROPThe whole tableNoUsually noNo

9. What is the difference between WHERE and HAVING?

WHERE filters rows before grouping. HAVING filters groups after GROUP BY, so it can use aggregates like AVG(salary). You can't write WHERE AVG(salary) > 60000; SQLite returns "misuse of aggregate: AVG()" and other databases throw a similar error.

Funnel diagram showing WHERE filtering rows before GROUP BY and HAVING filtering groups after

10. What is the order of execution of a SQL query?

The database runs clauses in a different order from how you write them: FROM, JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT. That's why a column alias created in SELECT can't be used in WHERE, but can be used in ORDER BY.

Flow diagram of SQL logical order of execution from FROM to LIMIT

11. What are the different types of joins?

A join combines rows from two tables on a related column. INNER JOIN keeps only matches. LEFT JOIN keeps every row from the left table, filling NULL where there's no match.

RIGHT JOIN does the same for the right table. FULL OUTER JOIN keeps everything from both.

CROSS JOIN returns every combination, and a self join joins a table to itself.

Venn diagrams of INNER, LEFT, RIGHT and FULL OUTER JOIN

12. What is the difference between UNION and UNION ALL?

UNION stacks two result sets and removes duplicates. UNION ALL keeps duplicates and is faster because it skips the de-duplication step. Combining the city columns of customers and departments gives 4 rows with UNION (Mumbai, Nagpur, Pune, Wardha) but 11 rows with UNION ALL.

13. What does NULL mean, and how do you check for it?

NULL means "unknown or missing", not zero and not an empty string. Any comparison with NULL returns unknown, so salary = NULL matches nothing. Use IS NULL or IS NOT NULL:

SELECT emp_name FROM employees WHERE salary IS NULL;
-- Sagar Thakre

14. What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?

COUNT(*) counts rows. COUNT(column) skips NULLs. COUNT(DISTINCT column) counts unique non-NULL values.

SELECT COUNT(*) AS all_rows, COUNT(salary) AS with_salary,
       COUNT(DISTINCT salary) AS distinct_salaries
FROM employees;
-- all_rows 11 | with_salary 10 | distinct_salaries 9

The two 65,000 salaries collapse into one, and Sagar's NULL is ignored.

15. What is a view?

A view is a saved SELECT query that behaves like a virtual table. It stores the query, not the data, so it always shows current rows. Teams use views to hide complex joins or restrict which columns a user can see.

SQL Query Interview Questions (16 to 32)

SQL query interview questions ask you to write working code, usually on employee or sales tables like the ones above. Questions 20 to 25 are the SQL joins interview questions you'll see most.

Say your assumptions first (ties? NULLs? duplicates?), then write the query.

16. Find the second highest salary.

SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
-- 120000

This works without LIMIT, which is exactly what the Infosys reviewer above was asked. It also handles ties at the top, because it looks for the highest value strictly below the maximum.

17. Find the Nth highest salary (handle ties).

Use DENSE_RANK so tied salaries share a rank. For the 3rd highest:

SELECT DISTINCT salary FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees WHERE salary IS NOT NULL
) t
WHERE rnk = 3;
-- 105000

LIMIT 1 OFFSET 2 also works in MySQL and PostgreSQL, but it breaks on ties unless you add DISTINCT. Mention that trade-off out loud.

18. Find duplicate records.

SELECT customer_id, order_date, amount, COUNT(*) AS copies
FROM orders
GROUP BY customer_id, order_date, amount
HAVING COUNT(*) > 1;
-- 102 | 2026-04-15 | 5600 | 2

Group by the columns that define "the same record", not by the primary key (which is always unique).

19. Delete duplicates but keep one copy.

DELETE FROM orders
WHERE order_id NOT IN (
  SELECT MIN(order_id) FROM orders
  GROUP BY customer_id, order_date, amount
);
-- 1 row deleted, 13 orders remain

MySQL won't let you delete from a table you select from in the same statement (error 1093). Wrap the subquery in a derived table, SELECT order_id FROM (SELECT MIN(order_id) AS order_id ... ) x, or use ROW_NUMBER in a CTE.

20. Find employees who earn more than their manager.

This is the classic self join:

SELECT e.emp_name, e.salary, m.emp_name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON e.manager_id = m.emp_id
WHERE e.salary > m.salary;
-- Neha Bhosale | 105000 | Amit Shinde | 95000

21. Count direct reports for each manager.

SELECT m.emp_name AS manager, COUNT(e.emp_id) AS direct_reports
FROM employees m
JOIN employees e ON e.manager_id = m.emp_id
GROUP BY m.emp_name
ORDER BY direct_reports DESC;
-- Rahul Patil 4, Anita Deshmukh 4, Karan Mehta 1, Amit Shinde 1

22. Find departments with no employees.

SELECT d.dept_name
FROM departments d
LEFT JOIN employees e ON d.dept_id = e.dept_id
WHERE e.emp_id IS NULL;
-- Research

The LEFT JOIN keeps Research with NULLs on the employee side, and the WHERE picks exactly those rows. Interviewers call this an "anti join".

23. Find customers who never placed an order.

SELECT c.customer_name
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
-- Wardha Textiles

NOT EXISTS is safer than NOT IN here because it isn't affected by NULLs. Mistake 1 below shows why.

24. Show department headcount, including empty departments.

SELECT d.dept_name, COUNT(e.emp_id) AS headcount
FROM departments d
LEFT JOIN employees e ON d.dept_id = e.dept_id
GROUP BY d.dept_name
ORDER BY headcount DESC;
-- Analytics 4, Engineering 3, Sales 2, HR 1, Research 0

Count e.emp_id, not *. COUNT(*) would give Research a headcount of 1, because the LEFT JOIN still produces one row for it.

25. Find rows with no match on either side (FULL OUTER JOIN).

SELECT e.emp_name, d.dept_name
FROM employees e
FULL OUTER JOIN departments d ON e.dept_id = d.dept_id
WHERE e.emp_id IS NULL OR d.dept_id IS NULL;
-- Mayur Raut | NULL
-- NULL | Research

MySQL doesn't support FULL OUTER JOIN. Interviewers often ask how you'd do it there: LEFT JOIN UNION RIGHT JOIN.

26. Departments averaging above ₹60,000 a month.

SELECT dept_id, COUNT(*) AS headcount, AVG(salary) AS avg_salary
FROM employees
WHERE dept_id IS NOT NULL
GROUP BY dept_id
HAVING AVG(salary) > 60000;
-- 10 | 4 | 74500
-- 20 | 3 | 136667

27. Put employees into salary bands with CASE.

SELECT
  CASE WHEN salary >= 100000 THEN 'High'
       WHEN salary >= 50000  THEN 'Mid'
       WHEN salary IS NULL   THEN 'Not set'
       ELSE 'Entry' END AS band,
  COUNT(*) AS employees
FROM employees
GROUP BY band;
-- Mid 4, High 3, Entry 3, Not set 1

Without the IS NULL line, Sagar would silently fall into "Entry". That's the detail that impresses.

28. Replace NULL salaries with 0 in the output.

SELECT emp_name, COALESCE(salary, 0) AS salary
FROM employees WHERE emp_id IN (9, 10);
-- Riya Gawande 42000 | Sagar Thakre 0

COALESCE returns the first non-NULL value. MySQL's IFNULL and SQL Server's ISNULL do the same for two arguments.

29. Find employees who joined in the last 90 days.

-- MySQL
SELECT emp_name, hire_date FROM employees
WHERE hire_date >= CURDATE() - INTERVAL 90 DAY;
-- PostgreSQL: WHERE hire_date >= CURRENT_DATE - INTERVAL '90 days'
-- Run on 12 Nov 2026: Mayur Raut | 2026-09-15

30. What is a subquery, and what is a correlated subquery?

A subquery is a query inside another query, like the SELECT MAX(salary) in question 16. It runs once.

A correlated subquery refers to the outer query's row, so it runs once per row, like the NOT EXISTS in question 23. Correlated subqueries are easy to read but can be slow on large tables, where a join is often faster.

31. What is a CTE?

A CTE (Common Table Expression) is a named temporary result defined with WITH, used inside a single query. It makes long logic readable and lets you reference the same step twice. Recursive CTEs can walk hierarchies, like an org chart (question 41).

32. What share of revenue does each customer bring?

SELECT customer_id, SUM(amount) AS revenue,
  ROUND(100.0 * SUM(amount) / SUM(SUM(amount)) OVER (), 1) AS pct_of_total
FROM orders WHERE status = 'Delivered'
GROUP BY customer_id
ORDER BY revenue DESC;
-- 101 | 42200 | 34.1
-- 103 | 34000 | 27.4
-- 102 | 30700 | 24.8
-- 104 | 17000 | 13.7

These totals include duplicate order 1012, which question 19 removes. The 100.0 matters. In SQLite and SQL Server, integer division of 5600 by 12000 returns 0. MySQL returns a decimal, so this bug often appears only after you switch databases.

Window Functions and Advanced SQL Interview Questions (33 to 42)

Window functions calculate across a set of rows while keeping every row in the output, unlike GROUP BY, which collapses them. They are the single biggest jump between fresher and mid-level SQL interview questions.

Diagram comparing GROUP BY collapsing rows with a window function keeping every row

33. What is a window function?

A window function performs a calculation over a "window" of related rows defined by OVER (PARTITION BY ... ORDER BY ...). PARTITION BY splits rows into groups, ORDER BY sets the sequence inside each group.

Common ones: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, SUM and AVG. The PostgreSQL window functions tutorial is a good reference.

34. What is the difference between ROW_NUMBER, RANK and DENSE_RANK?

SELECT emp_name, salary,
  ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num,
  RANK()       OVER (ORDER BY salary DESC) AS rnk,
  DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees WHERE dept_id = 10;
emp_namesalaryrow_numrnkdense_rnk
Rahul Patil1,20,000111
Sneha Kulkarni65,000222
Vikram Joshi65,000322
Pooja Wankhede48,000443

ROW_NUMBER never ties. RANK gives ties the same number, then skips (4). DENSE_RANK gives ties the same number and doesn't skip (3).

Table showing ROW_NUMBER, RANK and DENSE_RANK values for tied salaries

35. Find the highest-paid employee in each department.

SELECT dept_id, emp_name, salary FROM (
  SELECT dept_id, emp_name, salary,
         RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
  FROM employees
  WHERE dept_id IS NOT NULL AND salary IS NOT NULL
) t
WHERE rnk = 1;
-- 10 Rahul Patil 120000 | 20 Anita Deshmukh 210000 | 30 Karan Mehta 55000

We first ran this without salary IS NOT NULL, and HR returned Sagar Thakre with a NULL salary as its "top earner". Always say how you treat NULLs.

36. Get the top 2 delivered orders for each customer.

SELECT customer_id, order_id, amount FROM (
  SELECT customer_id, order_id, amount,
         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn
  FROM orders WHERE status = 'Delivered'
) t
WHERE rn <= 2;
-- 101: 1014 (14200), 1001 (12000) | 102: 1007, 1002 | 103: 1010, 1004 | 104: 1013, 1006

Use RANK instead of ROW_NUMBER if tied amounts should both appear.

37. Calculate a running total.

SELECT order_date, amount,
  SUM(amount) OVER (ORDER BY order_date, order_id) AS running_total
FROM orders WHERE customer_id = 101;
-- 12000, 16300, 26200, 32300, 46500

Adding order_id to ORDER BY breaks ties when two orders share a date, so the total is deterministic.

38. Calculate month-on-month revenue growth.

WITH monthly AS (
  SELECT DATE_FORMAT(order_date, '%Y-%m') AS month,  -- PostgreSQL: TO_CHAR(order_date, 'YYYY-MM')
         SUM(amount) AS revenue
  FROM orders WHERE status = 'Delivered'
  GROUP BY DATE_FORMAT(order_date, '%Y-%m')
)
SELECT month, revenue,
  LAG(revenue) OVER (ORDER BY month) AS prev_month,
  ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
        / LAG(revenue) OVER (ORDER BY month), 1) AS growth_pct
FROM monthly;
monthrevenueprev_monthgrowth_pct
2026-0120,500NULLNULL
2026-0232,70020,50059.5
2026-0317,10032,700-47.7
2026-0429,60017,10073.1
2026-0524,00029,600-18.9

This is one of the most common scenario based SQL interview questions for analyst roles, because it mirrors a real MIS report.

39. Calculate a 3-order moving average.

SELECT order_id, amount,
  ROUND(AVG(amount) OVER (ORDER BY order_date, order_id
        ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 0) AS moving_avg_3
FROM orders WHERE customer_id = 101;
-- 12000, 8150, 8733, 6767, 10067

The ROWS BETWEEN clause defines the frame. Interviewers use this to check you know frames exist.

40. Find customers who ordered in 3 consecutive months.

WITH m AS (
  SELECT DISTINCT customer_id,
         YEAR(order_date) * 12 + MONTH(order_date) AS month_no
  FROM orders WHERE status = 'Delivered'
)
SELECT DISTINCT a.customer_id
FROM m a
JOIN m b ON a.customer_id = b.customer_id AND b.month_no = a.month_no + 1
JOIN m c ON a.customer_id = c.customer_id AND c.month_no = a.month_no + 2;
-- 101 (January, February, March)

Turning a date into a month number turns a calendar problem into simple arithmetic. That trick solves most "streak" questions.

41. Print the reporting hierarchy with a recursive CTE.

WITH RECURSIVE chain AS (
  SELECT emp_id, emp_name, manager_id, 1 AS level
  FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.emp_id, e.emp_name, e.manager_id, c.level + 1
  FROM employees e JOIN chain c ON e.manager_id = c.emp_id
)
SELECT emp_name, level FROM chain ORDER BY level, emp_name;
-- Level 1: Anita | Level 2: Amit, Karan, Rahul, Sagar | Level 3: the other six

SQL Server writes WITH without the word RECURSIVE.

42. Show each customer's first order date.

SELECT customer_id, MIN(order_date) AS first_order
FROM orders GROUP BY customer_id;
-- 101 2026-01-04 | 102 2026-01-09 | 103 2026-02-02 | 104 2026-02-25 | 105 2026-03-28

The window version uses FIRST_VALUE(order_date) OVER (PARTITION BY customer_id ORDER BY order_date). Give the simple answer first, then mention the window version if they want the full order row alongside it.

SQL Interview Questions for Experienced Candidates (43 to 50)

SQL interview questions for experienced candidates shift from "can you write it" to "can you make it fast, safe and correct at scale". Expect follow-ups on indexes, transactions and debugging slow queries.

43. What is an index, and how does it speed up queries?

An index is a separate, sorted structure (usually a B-tree) that lets the database jump to matching rows instead of scanning the whole table. It's like the index at the back of a book. The cost: indexes use storage and slow down INSERT, UPDATE and DELETE, because they must be updated too.

Illustration comparing a full table scan with a B-tree index lookup

44. What is the difference between a clustered and a non-clustered index?

A clustered index decides the physical order of rows on disk, so a table has only one (in MySQL InnoDB it's the primary key). A non-clustered index is a separate structure with pointers back to the rows, and a table can have many. PostgreSQL doesn't keep clustered order automatically; its CLUSTER command reorders once.

45. When won't a query use an index even if one exists?

Common reasons: wrapping the column in a function (WHERE YEAR(hire_date) = 2026), a leading wildcard (LIKE '%patil'), implicit type conversion, low selectivity (a status column with three values), or a composite index used without its first column. Fix the first case by rewriting as a range: hire_date >= '2026-01-01' AND hire_date < '2027-01-01'.

46. How do you find out why a query is slow?

Run EXPLAIN (or EXPLAIN ANALYZE in PostgreSQL and MySQL 8) to see the execution plan. Look for full table scans on big tables, a join order that multiplies rows, and sorts spilling to disk. Then check indexes on join and filter columns, remove SELECT *, and filter early.

47. What is normalization? Explain 1NF, 2NF and 3NF.

Normalization organises tables to remove duplicate data and update anomalies. 1NF: each cell holds one value, no repeating groups.

2NF: 1NF plus every non-key column depends on the whole primary key. 3NF: 2NF plus no column depends on another non-key column.

Our dataset stores the department city in departments, not in every employee row. That's 3NF thinking.

48. What are ACID properties?

ACID describes reliable transactions. Atomicity: all steps succeed or none do.

Consistency: data moves from one valid state to another. Isolation: concurrent transactions don't see each other's half-done work.

Durability: committed data survives a crash. The bank transfer example (debit and credit must both happen) is the expected illustration.

49. What is the difference between a stored procedure and a function?

A stored procedure is a saved block of SQL that can run multiple statements, change data and manage transactions; you call it with CALL or EXEC. A function returns a value (or a table) and can be used inside a SELECT, but most databases restrict it from changing data. Use procedures for jobs, functions for reusable calculations.

50. What is SQL injection, and how do you prevent it?

SQL injection happens when user input is pasted straight into a query string, so an attacker can change the query (the classic ' OR '1'='1). Prevent it with parameterised queries or prepared statements, least-privilege database accounts and input validation. The OWASP SQL Injection Prevention Cheat Sheet lists the accepted defences.

7 SQL Interview Mistakes, With Wrong and Right Queries

Most failed SQL rounds don't fail on syntax. They fail on NULLs, joins and grouping, the places where a query runs fine but returns the wrong answer. Here are the seven we see most often, each run on the practice dataset.

Mistake 1: NOT IN with a NULL in the subquery

-- Wrong: "employees who manage nobody"
SELECT emp_name FROM employees
WHERE emp_id NOT IN (SELECT manager_id FROM employees);
-- 0 rows

Anita's manager_id is NULL, and x NOT IN (..., NULL) is never true. The query returns nothing, without an error.

-- Right
SELECT emp_name FROM employees
WHERE emp_id NOT IN (SELECT manager_id FROM employees WHERE manager_id IS NOT NULL);
-- 7 rows

Or use NOT EXISTS, which ignores the problem entirely.

Side by side comparison of the wrong and right NOT IN query with NULL values

Mistake 2: Filtering a LEFT JOIN in WHERE

-- Wrong: "returned orders per customer, including zero"
SELECT c.customer_name, o.order_id
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.status = 'Returned';
-- 1 row: Sitabuldi Mobiles

The WHERE removes every NULL row, so the LEFT JOIN quietly becomes an INNER JOIN.

-- Right: move the condition into ON
SELECT c.customer_name, COUNT(o.order_id) AS returned_orders
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id AND o.status = 'Returned'
GROUP BY c.customer_name;
-- 6 rows: Sitabuldi Mobiles 1, every other customer 0

Mistake 3: Assuming AVG counts NULL as zero

AVG(salary) returns ₹84,300 because it skips Sagar's NULL. AVG(COALESCE(salary, 0)) returns about ₹76,636. Neither is wrong, but you must say which one the business wants.

Mistake 4: Using an aggregate in WHERE

WHERE AVG(salary) > 60000 fails with "misuse of aggregate". Aggregates belong in HAVING (question 26).

Mistake 5: COUNT(*) after a LEFT JOIN

As question 24 showed, COUNT(*) gives an empty department a headcount of 1. Count a column from the right-hand table.

Mistake 6: Integer division

SELECT 5600 / 12000 returns 0 in SQLite and SQL Server. Multiply by 1.0 or cast to a decimal before dividing.

Mistake 7: Not stating assumptions

"Second highest salary" has three possible answers if there are ties. Candidates who ask "should ties count once or twice?" before typing come across as analysts. Candidates who don't come across as people who memorised the answer.

The DEEP Method: How to Answer Any SQL Question Out Loud

The DEEP method is a 4-step structure for answering any SQL interview question so the interviewer hears both knowledge and judgement: Define, Example, Edge case, Performance or purpose. It takes about 45 seconds per answer.

The DEEP answer method for SQL interviews: Define, Example, Edge case, Performance
  1. Define it in one line. "A LEFT JOIN keeps every row from the left table."
  2. Example from the table in front of you. "So Research still appears, with NULL employees."
  3. Edge case that could break it. "If I filter the right table in WHERE, Research disappears."
  4. Performance or purpose. "I'd index dept_id on employees, since we join on it."

Here's DEEP applied to "What is the difference between RANK and DENSE_RANK?":

"Both number rows by an order, but they treat ties differently. In our Analytics team, Sneha and Vikram both earn ₹65,000, so both get rank 2. RANK then jumps to 4 for Pooja, DENSE_RANK goes to 3. So for 'Nth highest salary', I'd use DENSE_RANK, otherwise a tie makes the 3rd highest disappear."

That answer takes under 30 seconds and covers all four steps.

A 7-Day SQL Interview Prep Plan

A 7-day SQL interview prep plan works if you already know basic SELECT queries and can give 1 to 2 hours a day. Load the practice dataset on day 1 and use it all week.

DayTopicQuestionsPractice task
1Basics, keys, commands1 to 8, 15Explain each in 2 sentences out loud
2Filtering, NULL, GROUP BY, HAVING9, 13, 14, 26 to 28Write the salary band query from memory
3Joins and self joins11, 20 to 25Draw each join on paper first
4Subqueries and CTEs16 to 19, 30, 31Solve question 16 three ways
5Window functions33 to 39Rebuild the month-on-month report
6Indexes, normalization, ACID43 to 50Run EXPLAIN on three of your queries
7Timed mockAny 1030 minutes, talk through every answer with DEEP
Seven-day SQL interview prep plan from basics to a timed mock interview

For more practice, free platforms like HackerRank, LeetCode and DataLemur have graded SQL problems. If you want structured training with mock interviews, the SQL course in Nagpur covers these topics end to end, and analyst-focused learners can go straight to the data analyst course in Nagpur, which pairs SQL with Excel and Power BI.

Brush up the Excel for data analysis basics too, since many analyst rounds pair SQL with Excel, and add Python later with the Python course in Nagpur.

Preparing for a specific company? Read our TCS data analytics interview questions guide, and build one SQL portfolio project from our list of data analytics project ideas so you have something real to talk about. Our placement process explains how mock rounds fit in.

Now It's Your Turn

You now have 50 SQL interview questions, a dataset to test them on, and a method for answering out loud.

The fastest way to improve is simple: download the dataset, close this page, and try questions 16, 20, 34 and 38 from memory. Compare your output with ours. Any mismatch is exactly what you should revise before your interview.

Want a mentor to run a mock SQL round with you? Book a free career counselling session and we'll tell you which of these SQL interview questions to focus on for the roles you're targeting.

FAQ

What are the most asked SQL interview questions for freshers?

The most asked SQL interview questions for freshers cover primary and foreign keys, types of joins, WHERE vs HAVING, DELETE vs TRUNCATE vs DROP, NULL handling and one or two queries such as the second highest salary or finding duplicates.

Is SQL enough to get a data analyst job?

SQL alone is rarely enough. Most data analyst job descriptions in India also ask for Excel and a BI tool like Power BI or Tableau, and a growing number mention Python. SQL is usually the first technical filter, though, so it's the best place to start.

Which database should I practise on for SQL interviews?

Practise on MySQL or PostgreSQL. They were the two most used databases in the Stack Overflow 2025 Developer Survey, and most Indian interview platforms support both. The core syntax in this guide works on either.

How long does it take to prepare for a SQL interview?

If you know basic queries, 7 to 14 days of focused practice is enough to revise for most fresher rounds. Starting from zero, plan for 4 to 6 weeks to learn SQL properly before you start interview practice.

Do companies ask window functions in SQL interviews?

Yes, especially product companies, analytics firms and mid-level roles. ROW_NUMBER, RANK, DENSE_RANK, LAG and running totals with SUM OVER are the most common. Service companies ask them less often for freshers, but knowing them sets you apart.

Are SQL interview questions asked as live coding or written tests?

Both. Many companies start with an online test of multiple-choice questions and two or three queries, then a technical interview where you write or explain queries on a shared screen. Some IT services rounds are verbal only, focused on theory.

About the Author

Aniruddha Abhay Kalbande is the founder of Fireblaze AI School, which he started in Nagpur on 31 October 2017. He is an Electronics and Telecommunication Engineer from Yeshwantrao Chavan College of Engineering (YCCE), Nagpur, with 10 years of experience in IT consulting and training. He has trained more than 20,000 students and delivered more than 30,000 hours of training globally. Read more on his author page.

Sources

  1. Stack Overflow 2025 Developer Survey, Technology, 2025
  2. Glassdoor, Infosys Data Analyst interview review, 2026
  3. Glassdoor, Accenture Data Analyst interview review, 2026
  4. PostgreSQL Documentation, Window Functions tutorial, current
  5. MySQL 8.0 Reference Manual, JOIN clause, current
  6. OWASP SQL Injection Prevention Cheat Sheet, current
  7. Fireblaze SQL practice dataset, query outputs generated on SQLite 3.53, November 2026

Want This Mapped to Your Own Background?

A free counselling session will tell you which path fits, and will tell you honestly if none of ours does.

Book Free Career Counselling

Keep Reading

Related Articles