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
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
What is the difference between SQL and MySQL?
| SQL | MySQL |
|---|---|
| Language | Database Management System |
| Standard | Implementation |
SQL is the language used to query databases. MySQL is a database server that understands SQL.
What are the different SQL commands?
| Category | Commands |
|---|---|
| DDL | CREATE, ALTER, DROP |
| DML | INSERT, UPDATE, DELETE |
| DQL | SELECT |
| DCL | GRANT, REVOKE |
| TCL | COMMIT, ROLLBACK |
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)
);Expected Answer: Yes, but it is not recommended.
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
Difference Between DELETE, TRUNCATE and DROP
| Command | Description |
|---|---|
| DELETE | Removes rows |
| TRUNCATE | Removes all rows |
| DROP | Deletes table completely |
Examples
DELETE FROM Employees;
TRUNCATE TABLE Employees;
DROP TABLE Employees;What is the WHERE clause?
WHERE filters records based on conditions.
SELECT *
FROM Employees
WHERE Salary > 50000;Common Operators
- =
- !=
- >
- << /li>
- IN
- LIKE
Difference Between WHERE and HAVING
| WHERE | HAVING |
|---|---|
| Filters Rows | Filters Groups |
| Before GROUP BY | After GROUP BY |
Example
SELECT DepartmentId,
COUNT(*)
FROM Employees
GROUP BY DepartmentId
HAVING COUNT(*) > 5;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
What are Aggregate Functions?
Aggregate functions perform calculations on multiple rows and return a single value.
| Function | Description |
|---|---|
| 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;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;Expected Answer: Row is excluded from result.
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.
Difference Between INNER JOIN and LEFT JOIN
| INNER JOIN | LEFT JOIN |
|---|---|
| Only matching rows | All rows from left table |
| Unmatched rows excluded | Unmatched rows included |
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;What is a Subquery?
A Subquery is a query nested inside another query.
SELECT *
FROM Employees
WHERE Salary >
(
SELECT AVG(Salary)
FROM Employees
);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
What is Normalization?
Normalization reduces data redundancy and improves data consistency.
| Normal Form | Purpose |
|---|---|
| 1NF | Atomic values |
| 2NF | Remove partial dependency |
| 3NF | Remove transitive dependency |
What is Denormalization?
Denormalization intentionally adds redundancy to improve read performance.
Example
Storing customer name directly in Orders table to avoid frequent joins.
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
ENDAdvantages
- Reusability
- Performance
- Security
What are SQL Constraints?
Constraints enforce rules on table data.
| Constraint | Purpose |
|---|---|
| PRIMARY KEY | Unique Identifier |
| FOREIGN KEY | Relationship |
| UNIQUE | Unique Values |
| NOT NULL | Mandatory Value |
| CHECK | Validation Rule |
| DEFAULT | Default Value |
CREATE TABLE Users (
UserId INT PRIMARY KEY,
Email VARCHAR(100) UNIQUE,
Age INT CHECK (Age >= 18)
);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
Expected Answer: More indexes increase INSERT, UPDATE and DELETE costs.
Difference Between Clustered and Non-Clustered Index
| Clustered Index | Non-Clustered Index |
|---|---|
| Stores actual data | Stores references to data |
| Only one per table | Multiple allowed |
| Physically sorts rows | Separate structure |
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.
What are ACID Properties?
| Property | Description |
|---|---|
| Atomicity | All or Nothing |
| Consistency | Valid State |
| Isolation | No Interference |
| Durability | Permanent Storage |
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
What is a Cursor?
A Cursor processes rows one at a time.
DECLARE EmployeeCursor CURSOR
FOR
SELECT EmployeeId
FROM Employees;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
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
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()
Difference Between ROW_NUMBER(), RANK() and DENSE_RANK()
| Function | Behavior |
|---|---|
| ROW_NUMBER() | Always unique sequence |
| RANK() | Skips numbers after ties |
| DENSE_RANK() | No gaps after ties |
Example
| Salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 100 | 2 | 1 | 1 |
| 90 | 3 | 3 | 2 |
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
);Find Duplicate Records
Find duplicate email addresses.
SELECT
Email,
COUNT(*) AS Total
FROM Users
GROUP BY Email
HAVING COUNT(*) > 1;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;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;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;Find Employees Who Joined In Last 30 Days
SELECT *
FROM Employees
WHERE JoiningDate >=
DATEADD(DAY, -30, GETDATE());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;Find Department Wise Employee Count
SELECT
DepartmentId,
COUNT(*) AS EmployeeCount
FROM Employees
GROUP BY DepartmentId;Expected Output
| Department | Total Employees |
|---|---|
| IT | 25 |
| HR | 8 |
Find Employees Without Manager
SELECT *
FROM Employees
WHERE ManagerId IS NULL;Real Scenario
Find CEO or top-level managers.
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
| Date | Amount | Running Total |
|---|---|---|
| 01-Jan | 100 | 100 |
| 02-Jan | 200 | 300 |
| 03-Jan | 150 | 450 |
Expected Answer: SUM() groups rows. SUM() OVER() preserves individual rows while calculating aggregates.
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);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
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.
What is Database Sharding?
Sharding distributes data across multiple databases.
Example
| Shard | Customers |
|---|---|
| Shard 1 | 1 - 1,000,000 |
| Shard 2 | 1,000,001 - 2,000,000 |
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
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.
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
How Would You Design a Multi-Tenant Database?
Approaches
| Approach | Description |
|---|---|
| Shared Database | TenantId Column |
| Separate Schema | Schema Per Tenant |
| Separate Database | Database Per Tenant |
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.
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
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.
