🎯 Free Interview Preparation

SQL Interview Questions & Answers

Complete SQL interview preparation guide.

SQL Interview Roadmap

Junior

  • SELECT
  • WHERE
  • ORDER BY
  • GROUP BY
  • Aggregate Functions

Mid-Level

  • JOINs
  • Subqueries
  • Indexes
  • Transactions
  • Stored Procedures

Senior

  • Window Functions
  • Execution Plans
  • Optimization
  • Partitioning
  • Database Design
Junior Question #1

What is SQL?

SQL (Structured Query Language) is a standard language used to communicate with relational databases. It is used to create, retrieve, update and delete data.

Example

SELECT *

FROM Employees;

Common Uses

  • Insert Data
  • Update Data
  • Delete Data
  • Retrieve Data
  • Create Database Objects
Expected Answer: Candidate should explain SQL is used to interact with relational databases.
Junior Question #2

What is the difference between SQL and MySQL?

SQLMySQL
LanguageDatabase Management System
StandardImplementation

SQL is the language used to query databases. MySQL is a database server that understands SQL.

Junior Question #3

What are the different SQL commands?

CategoryCommands
DDLCREATE, ALTER, DROP
DMLINSERT, UPDATE, DELETE
DQLSELECT
DCLGRANT, REVOKE
TCLCOMMIT, ROLLBACK
Junior Question #4

What is a Primary Key?

A Primary Key uniquely identifies each row in a table.

Characteristics

  • Unique
  • Cannot be NULL
  • One Primary Key per table
CREATE TABLE Employees (

  EmployeeId INT PRIMARY KEY,

  Name VARCHAR(100)

);
Follow-up: Can a table exist without a Primary Key?

Expected Answer: Yes, but it is not recommended.
Junior Question #5

What is a Foreign Key?

A Foreign Key creates a relationship between two tables.

CREATE TABLE Orders (

  OrderId INT PRIMARY KEY,

  CustomerId INT,

  FOREIGN KEY(CustomerId)

  REFERENCES Customers(CustomerId)

);

Benefits

  • Maintains Data Integrity
  • Prevents Invalid Data
  • Creates Relationships
Junior Question #6

Difference Between DELETE, TRUNCATE and DROP

CommandDescription
DELETERemoves rows
TRUNCATERemoves all rows
DROPDeletes table completely

Examples

DELETE FROM Employees;

TRUNCATE TABLE Employees;

DROP TABLE Employees;
Junior Question #7

What is the WHERE clause?

WHERE filters records based on conditions.

SELECT *

FROM Employees

WHERE Salary > 50000;

Common Operators

  • =
  • !=
  • >
  • << /li>
  • IN
  • LIKE
Junior Question #8

Difference Between WHERE and HAVING

WHEREHAVING
Filters RowsFilters Groups
Before GROUP BYAfter GROUP BY

Example

SELECT DepartmentId,
       COUNT(*)

FROM Employees

GROUP BY DepartmentId

HAVING COUNT(*) > 5;
Junior Question #9

What is GROUP BY?

GROUP BY groups rows that have the same values.

SELECT

  DepartmentId,

  COUNT(*) AS EmployeeCount

FROM Employees

GROUP BY DepartmentId;

Typical Usage

  • COUNT
  • SUM
  • AVG
  • MIN
  • MAX
Junior Question #10

What are Aggregate Functions?

Aggregate functions perform calculations on multiple rows and return a single value.

FunctionDescription
COUNT()Counts rows
SUM()Total value
AVG()Average value
MIN()Minimum value
MAX()Maximum value

Example

SELECT

  AVG(Salary) AS AverageSalary,

  MAX(Salary) AS HighestSalary,

  MIN(Salary) AS LowestSalary

FROM Employees;
Very common fresher interview topic.
Mid-Level Question #11

What is an INNER JOIN?

INNER JOIN returns only matching records from both tables.

SELECT

  e.EmployeeName,

  d.DepartmentName

FROM Employees e

INNER JOIN Departments d

ON e.DepartmentId = d.DepartmentId;
Follow-up: What happens when a matching record doesn't exist?

Expected Answer: Row is excluded from result.
Mid-Level Question #12

What is a LEFT JOIN?

LEFT JOIN returns all records from the left table and matching records from the right table.

SELECT

  e.EmployeeName,

  d.DepartmentName

FROM Employees e

LEFT JOIN Departments d

ON e.DepartmentId = d.DepartmentId;

Example Use Case

Find employees who are not assigned to any department.

Mid-Level Question #13

Difference Between INNER JOIN and LEFT JOIN

INNER JOINLEFT JOIN
Only matching rowsAll rows from left table
Unmatched rows excludedUnmatched rows included
Mid-Level Question #14

What is a Self Join?

A Self Join joins a table with itself.

Employee Manager Example

SELECT

  e.EmployeeName,

  m.EmployeeName AS ManagerName

FROM Employees e

LEFT JOIN Employees m

ON e.ManagerId = m.EmployeeId;
Mid-Level Question #15

What is a Subquery?

A Subquery is a query nested inside another query.

SELECT *

FROM Employees

WHERE Salary >

(

  SELECT AVG(Salary)

  FROM Employees

);
Common follow-up: Difference between Subquery and Join?
Mid-Level Question #16

What is a View?

A View is a virtual table created from a SQL query.

CREATE VIEW ActiveEmployees AS

SELECT *

FROM Employees

WHERE IsActive = 1;

Benefits

  • Reusable Queries
  • Security
  • Simplified Access
Mid-Level Question #17

What is Normalization?

Normalization reduces data redundancy and improves data consistency.

Normal FormPurpose
1NFAtomic values
2NFRemove partial dependency
3NFRemove transitive dependency
Mid-Level Question #18

What is Denormalization?

Denormalization intentionally adds redundancy to improve read performance.

Example

Storing customer name directly in Orders table to avoid frequent joins.

Expected discussion: Performance vs Data Consistency trade-off.
Mid-Level Question #19

What is a Stored Procedure?

A Stored Procedure is a precompiled SQL program stored in the database.

CREATE PROCEDURE GetEmployees

AS

BEGIN

  SELECT *

  FROM Employees

END

Advantages

  • Reusability
  • Performance
  • Security
Mid-Level Question #20

What are SQL Constraints?

Constraints enforce rules on table data.

ConstraintPurpose
PRIMARY KEYUnique Identifier
FOREIGN KEYRelationship
UNIQUEUnique Values
NOT NULLMandatory Value
CHECKValidation Rule
DEFAULTDefault Value
CREATE TABLE Users (

  UserId INT PRIMARY KEY,

  Email VARCHAR(100) UNIQUE,

  Age INT CHECK (Age >= 18)

);
Mid-level candidates should explain when and why each constraint is used.
Senior Question #21

What is an Index?

An Index is a database object that improves query performance by reducing the amount of data scanned.

Example

CREATE INDEX IX_Employee_Email

ON Employees(Email);

Benefits

  • Faster Search Operations
  • Reduced Table Scans
  • Improved Query Performance
Follow-up: Why shouldn't every column be indexed?

Expected Answer: More indexes increase INSERT, UPDATE and DELETE costs.
Senior Question #22

Difference Between Clustered and Non-Clustered Index

Clustered IndexNon-Clustered Index
Stores actual dataStores references to data
Only one per tableMultiple allowed
Physically sorts rowsSeparate structure
Frequently asked senior-level interview question.
Senior Question #23

What is a Transaction?

A Transaction is a group of operations executed as a single unit.

BEGIN TRANSACTION;

UPDATE Accounts
SET Balance = Balance - 1000
WHERE Id = 1;

UPDATE Accounts
SET Balance = Balance + 1000
WHERE Id = 2;

COMMIT;

Real World Example

Bank money transfer between accounts.

Senior Question #24

What are ACID Properties?

PropertyDescription
AtomicityAll or Nothing
ConsistencyValid State
IsolationNo Interference
DurabilityPermanent Storage
Banking systems commonly use ACID guarantees.
Senior Question #25

What is a Deadlock?

Deadlock occurs when two transactions wait for each other indefinitely.

Example

  • Transaction A locks Table 1
  • Transaction B locks Table 2
  • A waits for Table 2
  • B waits for Table 1

Prevention

  • Access tables in same order
  • Keep transactions short
  • Proper indexing
Senior Question #26

What is a Cursor?

A Cursor processes rows one at a time.

DECLARE EmployeeCursor CURSOR

FOR

SELECT EmployeeId

FROM Employees;
Strong candidates explain that set-based operations are generally preferred over cursors.
Senior Question #27

What is Query Optimization?

Query Optimization improves performance and reduces execution time.

Common Techniques

  • Proper Indexing
  • Avoid SELECT *
  • Optimize Joins
  • Reduce Subqueries
  • Partition Large Tables
Senior candidates should discuss execution plans.
Senior Question #28

What is an Execution Plan?

Execution Plan shows how SQL Server executes a query.

Things to Look For

  • Table Scans
  • Index Scans
  • Index Seeks
  • Missing Indexes
  • High Cost Operators
Expected answer includes Index Seek vs Table Scan discussion.
Senior Question #29

What are SQL Window Functions?

Window Functions perform calculations across rows without collapsing results.

SELECT

  EmployeeName,

  Salary,

  ROW_NUMBER() OVER(

    ORDER BY Salary DESC

  ) AS RankNo

FROM Employees;

Common Window Functions

  • ROW_NUMBER()
  • RANK()
  • DENSE_RANK()
  • LAG()
  • LEAD()
Senior Question #30

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

FunctionBehavior
ROW_NUMBER()Always unique sequence
RANK()Skips numbers after ties
DENSE_RANK()No gaps after ties

Example

SalaryROW_NUMBERRANKDENSE_RANK
100111
100211
90332
Very common SQL Server, Oracle and PostgreSQL interview question.
Practical Question #31

Find the Second Highest Salary

One of the most frequently asked SQL interview questions.

SELECT MAX(Salary)

FROM Employees

WHERE Salary < (

  SELECT MAX(Salary)

  FROM Employees

);
Follow-up: How would you find the 3rd or Nth highest salary?
Practical Question #32

Find Duplicate Records

Find duplicate email addresses.

SELECT

  Email,

  COUNT(*) AS Total

FROM Users

GROUP BY Email

HAVING COUNT(*) > 1;
Common question for testing GROUP BY and HAVING knowledge.
Practical Question #33

Delete Duplicate Records

WITH DuplicateUsers AS (

  SELECT

    Id,

    ROW_NUMBER() OVER (

      PARTITION BY Email

      ORDER BY Id

    ) AS RowNum

  FROM Users

)

DELETE

FROM DuplicateUsers

WHERE RowNum > 1;
Strong candidates understand ROW_NUMBER() usage.
Practical Question #34

Find Employees With Highest Salary In Each Department

SELECT

  DepartmentId,

  MAX(Salary) AS HighestSalary

FROM Employees

GROUP BY DepartmentId;

Advanced Version

WITH RankedEmployees AS (

  SELECT

    EmployeeName,

    DepartmentId,

    Salary,

    RANK() OVER (

      PARTITION BY DepartmentId

      ORDER BY Salary DESC

    ) AS RankNo

  FROM Employees

)

SELECT *

FROM RankedEmployees

WHERE RankNo = 1;
Practical Question #35

Find Top 3 Highest Salaries

SELECT TOP 3 *

FROM Employees

ORDER BY Salary DESC;

MySQL Version

SELECT *

FROM Employees

ORDER BY Salary DESC

LIMIT 3;
Practical Question #36

Find Employees Who Joined In Last 30 Days

SELECT *

FROM Employees

WHERE JoiningDate >=

DATEADD(DAY, -30, GETDATE());
Tests Date Functions knowledge.
Practical Question #37

Find Missing IDs

IDs: 1,2,3,5,6,7 Missing = 4

SELECT

  t1.Id + 1 AS MissingId

FROM Employees t1

LEFT JOIN Employees t2

ON t1.Id + 1 = t2.Id

WHERE t2.Id IS NULL;
Frequently asked in product companies.
Practical Question #38

Find Department Wise Employee Count

SELECT

  DepartmentId,

  COUNT(*) AS EmployeeCount

FROM Employees

GROUP BY DepartmentId;

Expected Output

DepartmentTotal Employees
IT25
HR8
Practical Question #39

Find Employees Without Manager

SELECT *

FROM Employees

WHERE ManagerId IS NULL;

Real Scenario

Find CEO or top-level managers.

Practical Question #40

Find Running Total Of Sales

Frequently asked Window Function problem.

SELECT

  OrderDate,

  Amount,

  SUM(Amount) OVER (

    ORDER BY OrderDate

  ) AS RunningTotal

FROM Orders;

Sample Output

DateAmountRunning Total
01-Jan100100
02-Jan200300
03-Jan150450
Follow-up: Difference between SUM() and SUM() OVER()?

Expected Answer: SUM() groups rows. SUM() OVER() preserves individual rows while calculating aggregates.
Architect Question #41

How Would You Optimize a Slow Query?

Investigation Steps

  • Check Execution Plan
  • Identify Table Scans
  • Review Missing Indexes
  • Analyze Join Conditions
  • Review Statistics
  • Check Blocking Sessions

Example

SELECT *

FROM Orders

WHERE CustomerId = 100;

If CustomerId is frequently searched, create an index.

CREATE INDEX IX_Orders_CustomerId

ON Orders(CustomerId);
Strong candidates discuss execution plans before adding indexes.
Architect Question #42

How Would You Design an E-Commerce Database?

Core Tables

  • Users
  • Products
  • Categories
  • Orders
  • OrderItems
  • Payments
  • Coupons
  • Inventory

Relationships

  • User → Orders
  • Order → OrderItems
  • Product → Category
  • Order → Payment
Strong candidates discuss indexing, inventory locking and scaling.
Architect Question #43

How Would You Handle 100 Million Records?

Strategies

  • Table Partitioning
  • Read Replicas
  • Sharding
  • Redis Cache
  • Archiving
  • Optimized Indexes

Common Mistake

Adding more CPU without fixing bad queries.

Architect Question #44

What is Database Sharding?

Sharding distributes data across multiple databases.

Example

ShardCustomers
Shard 11 - 1,000,000
Shard 21,000,001 - 2,000,000
Follow-up: What challenges come with sharding?
Architect Question #45

What is Database Replication?

Replication copies data from a primary database to secondary databases.

Benefits

  • Read Scaling
  • High Availability
  • Disaster Recovery

Architecture

  • Primary Database → Writes
  • Replica Databases → Reads
Architect Question #46

How Would You Prevent Database Deadlocks?

  • Access Tables In Same Order
  • Keep Transactions Short
  • Use Proper Indexes
  • Avoid Long Running Transactions
  • Reduce Lock Duration

Real Example

Payment systems often experience deadlocks during concurrent updates.

Architect Question #47

How Would You Design an Audit Logging System?

Audit Table

AuditLogs

(
  Id,
  UserId,
  Action,
  TableName,
  OldValue,
  NewValue,
  CreatedDate
)

Requirements

  • Immutable Records
  • Searchable
  • Retention Policy
  • Security Compliance
Architect Question #48

How Would You Design a Multi-Tenant Database?

Approaches

ApproachDescription
Shared DatabaseTenantId Column
Separate SchemaSchema Per Tenant
Separate DatabaseDatabase Per Tenant
Follow-up: Which approach would you choose for SaaS products?
Architect Question #49

How Would You Design a High-Traffic Banking Database?

  • Strict ACID Transactions
  • Optimistic/Pessimistic Locking
  • Read Replicas
  • Audit Logs
  • Encryption
  • Disaster Recovery

Critical Requirement

Data consistency is more important than raw performance.

Architect Question #50

Design a Database for a Social Media Platform

Core Tables

  • Users
  • Posts
  • Comments
  • Likes
  • Followers
  • Messages
  • Notifications

Scaling Considerations

  • Read Replicas
  • Caching
  • Partitioning
  • Search Engine Integration
  • Event Driven Processing
This question evaluates database design, scalability, indexing, caching and architecture knowledge.

Frequently Asked Questions

Are SQL coding questions included?

Yes. Real-world SQL queries, joins, window functions and optimization questions are covered.

Is this suitable for experienced developers?

Yes. Junior, Mid-Level, Senior and Architect level SQL questions are included.

Does it cover performance tuning?

Yes. Indexing, execution plans and optimization discussions are included.