Chapter 5 — SQL Server / Database Interview Questions (60 Questions)

Topics:

SQL Fundamentals

  1. Clustered vs non-clustered indexes
  2. Query execution plans
  3. Index optimization
  4. Stored procedures
  5. Views
  6. Functions
  7. Triggers
  8. Transactions
  9. Isolation levels
  10. Deadlocks

Advanced Database

  1. Normalization
  2. Denormalization
  3. Partitioning
  4. Replication
  5. Sharding
  6. Query tuning
  7. SQL Server memory
  8. Locking
  9. Blocking
  10. Performance troubleshooting

Entity Framework + SQL

  1. EF Core queries
  2. Tracking
  3. Migrations
  4. Relationships
  5. Lazy loading
  6. Eager loading
  7. Transactions
  8. Bulk operations
  9. Stored procedures
  10. Performance optimization

Cloud Databases

31–60:

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

Interview Answer

A clustered index determines the physical order of data in a table. A non-clustered index is a separate structure that stores indexed columns and pointers to the actual data.


Clustered Index

A table can have only one clustered index.

Example:

CREATE CLUSTERED INDEX IX_Orders_Id

ON Orders(Id);

Data storage:

Clustered Index

Id

 |

 +---- Row Data

 +---- Row Data

 +---- Row Data

The data itself is stored in index order.


Non-Clustered Index

A table can have multiple non-clustered indexes.

Example:

CREATE NONCLUSTERED INDEX IX_Orders_CustomerId

ON Orders(CustomerId);

Structure:

Non-Clustered Index

CustomerId

     |

     |

 Row Pointer

     |

     v

 Actual Table Data


Example

Table:

Orders

Id    CustomerId    Date

1        100       2026-01-01

2        200       2026-01-02

3        100       2026-01-03

Query:

SELECT *

FROM Orders

WHERE CustomerId = 100;

Without index:

Scan every row

With index:

Find CustomerId=100

        |

        |

Jump directly to rows


Comparison

Clustered Index

Non-Clustered Index

Defines physical order

Separate lookup structure

One per table

Many per table

Faster for range searches

Good for specific queries

Contains actual data

Contains references


Senior Answer

I use clustered indexes for primary access patterns, usually on identity keys or frequently ranged columns. Non-clustered indexes support specific query patterns, but I avoid over-indexing because indexes increase storage and write cost.


2. How do indexes improve query performance?

Interview Answer

Indexes improve performance by allowing SQL Server to locate data without scanning the entire table.


Without index:

SELECT *

FROM Customers

WHERE Email='john@test.com';

SQL Server:

Read Row 1

Read Row 2

Read Row 3

...

Read Row 10,000,000

This is a:

Table Scan


With index:

CREATE INDEX IX_Customers_Email

ON Customers(Email);

SQL Server:

Index lookup

       |

Matching row

       |

Return data


Example

Table:

Customers

Id     Email

1      a@test.com

2      b@test.com

3      c@test.com

...

Index:

Email Index

a@test.com -> Row 1

b@test.com -> Row 2

c@test.com -> Row 3


Benefits

Indexes improve:


Problems with Too Many Indexes

Every INSERT:

Insert row

   |

   + Update clustered index

   |

   + Update index 1

   |

   + Update index 2

   |

   + Update index 3

More indexes:


Senior Answer

Indexes improve read performance by reducing data scans, but they must be designed according to query patterns because they increase write overhead.


3. What is a covering index?

Interview Answer

A covering index contains all columns required by a query, allowing SQL Server to retrieve data directly from the index without accessing the table.


Example table:

Orders

(

 Id,

 CustomerId,

 OrderDate,

 TotalAmount

)

Query:

SELECT

    CustomerId,

    OrderDate

FROM Orders

WHERE CustomerId = 100;


Create index:

CREATE INDEX IX_Order_Customer

ON Orders(CustomerId)

INCLUDE(OrderDate);


Now SQL Server can use:

Index

CustomerId

OrderDate

No additional table lookup required.


Without covering index

Execution:

Index Seek

    |

Key Lookup

    |

Table


With covering index

Index Seek

    |

Return Result


Senior Answer

Covering indexes reduce key lookups by including all columns needed by a query, improving read performance for frequently executed queries.


4. What is an execution plan?

Interview Answer

An execution plan shows how SQL Server executes a query.

It explains:


Example:

Query:

SELECT *

FROM Orders

WHERE CustomerId = 10;

Execution plan:

Index Seek

      |

      |

Nested Loop Join

      |

      |

Table Access


Common Operators

Table Scan

Reads entire table.

Usually expensive.

Read all rows


Index Seek

Finds rows directly.

Usually efficient.

Index

 |

Find matching rows


Index Scan

Reads many index entries.


Key Lookup

Finds additional columns from the table.


How to view

SQL Server Management Studio:

Include Actual Execution Plan

Shortcut:

Ctrl + M


Senior Answer

I use execution plans to understand query behavior and identify issues such as missing indexes, scans, expensive joins, and incorrect cardinality estimates.


5. What is query optimization?

Interview Answer

Query optimization is the process of improving SQL query performance.


Typical steps:

Slow Query

    |

Analyze Execution Plan

    |

Identify Bottleneck

    |

Optimize

    |

Measure Result


Common Optimizations


1. Add Appropriate Indexes

Before:

WHERE CustomerId = 10

No index:

Table Scan

After:

Index Seek


2. Avoid SELECT *

Bad:

SELECT *

FROM Orders;

Better:

SELECT Id, Date, Total

FROM Orders;

Benefits:


3. Optimize Joins

Bad:

JOIN without indexes

Better:

Index foreign keys


4. Reduce Returned Rows

Use:

TOP

WHERE

Pagination


5. Avoid Functions on Indexed Columns

Bad:

WHERE YEAR(OrderDate)=2026

SQL Server cannot efficiently use the index.

Better:

WHERE OrderDate >= '2026-01-01'

AND OrderDate < '2027-01-01'


Senior Answer

Query optimization starts with understanding execution plans, then improving indexing, query structure, and data access patterns.


6. What is normalization?

Interview Answer

Normalization is the process of organizing data to reduce duplication and improve consistency.


Example: Bad Design

Customer table:

Orders

OrderId

CustomerName

CustomerEmail

ProductName

ProductPrice

Problem:

Customer information repeats:

John

john@test.com

John

john@test.com


Normalized Design

Customers:

CustomerId

Name

Email

Orders:

OrderId

CustomerId

OrderDate

Products:

ProductId

Name

Price


Relationship:

Customer

   |

 Orders

   |

Products


Normal Forms

First Normal Form (1NF)

No repeating groups.

Bad:

Phone1

Phone2

Phone3


Second Normal Form (2NF)

Remove partial dependencies.


Third Normal Form (3NF)

Remove transitive dependencies.


Benefits


Senior Answer

I normalize transactional databases to maintain consistency, but I consider controlled denormalization when read performance requirements justify it.


7. What is denormalization and when would you use it?

Interview Answer

Denormalization intentionally duplicates data to improve read performance.


Example:

Normalized:

Customer

CustomerId

Name

Orders

OrderId

CustomerId

Query:

SELECT

Customer.Name,

Orders.Total

Requires JOIN.


Denormalized:

Orders

OrderId

CustomerName

Total

No JOIN required.


Advantages


Disadvantages


Common Usage

Good for:


Senior Answer

I keep transactional systems normalized but use denormalization strategically for read-heavy workloads such as reporting and analytics.


8. What are database transactions?

Interview Answer

A transaction is a group of database operations treated as one unit of work.

A transaction follows ACID principles.


ACID

Atomicity

All operations succeed or fail together.

Example:

Transfer money

Debit account

Credit account

Both succeed or rollback


Consistency

Database remains valid.


Isolation

Transactions do not interfere incorrectly.


Durability

Committed data survives failures.


Example

BEGIN TRANSACTION;

UPDATE Accounts

SET Balance = Balance - 100

WHERE Id = 1;

UPDATE Accounts

SET Balance = Balance + 100

WHERE Id = 2;

COMMIT;

If something fails:

ROLLBACK;


Senior Answer

Transactions guarantee data consistency by grouping related operations into an atomic unit following ACID principles.


9. What are SQL Server isolation levels?

Interview Answer

Isolation levels control how transactions interact with each other.

SQL Server supports:

  1. Read Uncommitted
  2. Read Committed
  3. Repeatable Read
  4. Serializable
  5. Snapshot

Read Uncommitted

Allows dirty reads.

Example:

Transaction A:

Update balance = 500

Transaction B reads:

500

But A may rollback.


Read Committed

Default SQL Server level.

Prevents dirty reads.


Repeatable Read

Prevents changes to data already read.


Serializable

Highest isolation.

Transactions behave as if executed sequentially.


Snapshot

Uses row versioning.

Readers do not block writers.


Comparison

Level

Performance

Consistency

Read Uncommitted

Highest

Lowest

Read Committed

Good

Good

Serializable

Lowest

Highest

Snapshot

Good

High


Senior Answer

I choose isolation levels based on consistency requirements and performance impact. The default Read Committed is usually appropriate, while Snapshot can reduce blocking in read-heavy systems.


10. What is a deadlock?

Interview Answer

A deadlock occurs when two transactions wait for each other and neither can continue.


Example:

Transaction A:

Lock Customer table

Wait for Order table

Transaction B:

Lock Order table

Wait for Customer table

Result:

A waits for B

B waits for A

SQL Server detects this and kills one transaction.


Example

Transaction 1:

BEGIN TRAN

UPDATE Customers

SET Name='John'

WHERE Id=1;

Transaction 2:

BEGIN TRAN

UPDATE Orders

SET Status='Done'

WHERE Id=10;

Then both access each other's locked resources.


How to Prevent Deadlocks

1. Access tables in the same order

Good:

Customer

then

Order

Everywhere.


2. Keep transactions short

Avoid:

BEGIN TRAN

Long processing

COMMIT


3. Use proper indexes

Reduce locking duration.


4. Handle retries

Deadlocks can happen in distributed systems.


Senior Answer

I prevent deadlocks by keeping transactions short, accessing resources consistently, optimizing queries, and implementing retry logic for transient failures.


11. What is a stored procedure?

Interview Answer

A stored procedure is a precompiled collection of SQL statements stored in the database and executed as a single unit.

It can:


Example

Create procedure:

CREATE PROCEDURE GetCustomerOrders

(

    @CustomerId INT

)

AS

BEGIN

    SELECT *

    FROM Orders

    WHERE CustomerId = @CustomerId;

END

Execute:

EXEC GetCustomerOrders 100;


Benefits

Performance

SQL Server can reuse execution plans.


Security

Users can execute procedures without direct table access.

Example:

Application

     |

Stored Procedure

     |

Database Tables


Centralized Logic

Common operations can be reused.


Disadvantages


Senior Answer

I use stored procedures for complex database operations, reporting, and performance-critical queries. I avoid putting all business logic into stored procedures because application code is easier to maintain and test.


12. Stored Procedure vs SQL Query — what is the difference?

Interview Answer

A stored procedure is a reusable database object, while a SQL query is an individual command executed directly.


SQL Query

Example:

SELECT *

FROM Customers

WHERE Id = 10;

Executed directly.


Stored Procedure

Example:

EXEC GetCustomer 10;

Stored in database.


Comparison

SQL Query

Stored Procedure

Executed directly

Stored in database

Less reusable

Reusable

No parameters usually

Supports parameters

Simple operations

Complex operations

Less control

Better security


When to use stored procedures?

Good for:


Senior Answer

I choose between ad-hoc SQL and stored procedures based on complexity, performance requirements, security, and maintainability.


13. What is a SQL Server view?

Interview Answer

A view is a virtual table based on a SELECT query.

A view does not usually store data itself; it stores the query definition.


Example:

Create view:

CREATE VIEW CustomerOrders

AS

SELECT

    c.Name,

    o.OrderDate,

    o.Total

FROM Customers c

JOIN Orders o

ON c.Id = o.CustomerId;

Use:

SELECT *

FROM CustomerOrders;


Benefits

Simplifies complex queries

Instead of:

10 lines of JOINs

Use:

SELECT *

FROM CustomerOrders;


Security

Hide sensitive columns.

Example:

Table:

Employee

Id

Name

Salary

Password

View:

EmployeePublic

Id

Name


Reuse

Multiple applications can use the same logic.


Limitations


Senior Answer

Views are useful for abstraction, security, and simplifying repeated queries, but I still analyze the underlying execution plan to ensure performance.


14. What is the difference between a view and a stored procedure?

Interview Answer

A view represents data, while a stored procedure performs operations.


View

Example:

SELECT *

FROM ActiveCustomers;

Purpose:

Retrieve data


Stored Procedure

Example:

EXEC CreateOrder;

Purpose:

Execute logic


Comparison

View

Stored Procedure

Returns data

Performs actions

Used like a table

Executed with EXEC

No parameters (normal view)

Supports parameters

Mainly SELECT

INSERT/UPDATE/DELETE possible

Simpler

More powerful


Example

View:

Customer Summary

Stored procedure:

Create Customer Order


Senior Answer

I use views for reusable data projections and stored procedures when I need parameters, transactions, or more complex processing.


15. What are SQL functions?

Interview Answer

A SQL function is a reusable piece of logic that returns a value or a table.

SQL Server supports:

  1. Scalar functions
  2. Table-valued functions

Scalar Function

Returns one value.

Example:

CREATE FUNCTION GetFullName

(

    @FirstName VARCHAR(50),

    @LastName VARCHAR(50)

)

RETURNS VARCHAR(100)

AS

BEGIN

RETURN @FirstName + ' ' + @LastName;

END

Usage:

SELECT dbo.GetFullName(

'John',

'Smith');


Table-Valued Function

Returns a table.

Example:

CREATE FUNCTION GetCustomerOrders

(

 @CustomerId INT

)

RETURNS TABLE

AS

RETURN

(

 SELECT *

 FROM Orders

 WHERE CustomerId=@CustomerId

)


Function vs Stored Procedure

Function

Stored Procedure

Must return value

Can return nothing

Can be used in SELECT

Executed separately

Usually no side effects

Can modify data

More restricted

More powerful


Senior Answer

I use functions for reusable calculations or table expressions, but avoid excessive scalar functions because they can negatively impact query performance.


16. What are database triggers?

Interview Answer

A trigger is a special piece of SQL code that automatically executes when a database event occurs.

Events:


Example:

Audit trigger:

CREATE TRIGGER AuditCustomerUpdate

ON Customers

AFTER UPDATE

AS

BEGIN

INSERT INTO AuditLog

(

 Action,

 Date

)

VALUES

(

 'Customer Updated',

 GETDATE()

)

END


When:

UPDATE Customers

SET Name='John'

Automatically:

Customer updated

        |

Audit record created


Common Uses


Problems

Triggers can:


Senior Answer

I use triggers carefully, mainly for auditing or database-level requirements. I avoid putting complex business logic into triggers because they reduce application transparency.


17. What is a Common Table Expression (CTE)?

Interview Answer

A Common Table Expression is a temporary named result set used inside a query.

It improves readability and supports recursive queries.


Example:

Without CTE:

SELECT *

FROM

(

    SELECT *

    FROM Employees

) x;


With CTE:

WITH EmployeeData AS

(

    SELECT *

    FROM Employees

)

SELECT *

FROM EmployeeData;


Recursive CTE Example

Employee hierarchy:

CEO

 |

 +-- Manager

       |

       +-- Developer

Query:

WITH EmployeeHierarchy AS

(

    SELECT Id, Name, ManagerId

    FROM Employees

    WHERE ManagerId IS NULL

    UNION ALL

    SELECT e.Id, e.Name, e.ManagerId

    FROM Employees e

    JOIN EmployeeHierarchy h

    ON e.ManagerId=h.Id

)

SELECT *

FROM EmployeeHierarchy;


Benefits


Senior Answer

I use CTEs to make complex queries easier to understand, especially recursive queries and multi-step transformations.


18. Temporary Table vs Table Variable

Interview Answer

Both store temporary data, but they have different behavior.


Temporary Table

Created with:

CREATE TABLE #Orders

(

 Id INT,

 Total MONEY

);

Stored in:

tempdb


Characteristics:


Table Variable

Example:

DECLARE @Orders TABLE

(

 Id INT,

 Total MONEY

);


Characteristics:


Comparison

Temporary Table

Table Variable

#TableName

@TableName

Better for large data

Better for small data

Has statistics

Limited statistics

Supports indexes

Limited indexing


Example

Large report:

100,000 rows

Use:

Temporary table

Small calculation:

20 rows

Use:

Table variable


Senior Answer

I choose temporary tables for larger intermediate datasets because SQL Server can create statistics and optimize execution plans more effectively.


19. What are SQL window functions?

Interview Answer

Window functions perform calculations across related rows without grouping them into a single result.


Example table:

Sales

Employee   Amount

John       100

John       200

Mary       300


ROW_NUMBER()

Assigns sequential numbers.

SELECT

Employee,

Amount,

ROW_NUMBER()

OVER(

ORDER BY Amount DESC

)

AS RowNum

FROM Sales;

Result:

Mary  300  1

John  200  2

John  100  3


RANK()

Handles ties.

Example:

100

100

90

Result:

1

1

3


SUM() OVER()

Running total:

SELECT

Date,

Amount,

SUM(Amount)

OVER(

ORDER BY Date

)

FROM Sales;


Common Uses


Senior Answer

Window functions allow analytical calculations while preserving individual rows, which makes them very useful for reporting and complex queries.


20. Explain SQL JOIN types.

Interview Answer

JOINs combine data from multiple tables based on relationships.


Assume:

Customers:

Id

Name

Orders:

CustomerId

Amount


INNER JOIN

Returns matching records only.

SELECT *

FROM Customers c

INNER JOIN Orders o

ON c.Id=o.CustomerId;

Result:

Customers with orders


LEFT JOIN

Returns all records from the left table.

SELECT *

FROM Customers c

LEFT JOIN Orders o

ON c.Id=o.CustomerId;

Result:

All customers

+

Orders if available


RIGHT JOIN

Opposite of LEFT JOIN.


FULL OUTER JOIN

Returns everything from both tables.


Visual Summary

INNER JOIN

A ∩ B

LEFT JOIN

A + matching B

FULL JOIN

A + B


Performance Tips

Good:

JOIN on indexed columns

Avoid:

JOIN without indexes


Senior Answer

I select JOIN types based on the business requirement and ensure join columns are properly indexed to avoid expensive scans.

21. What is Entity Framework Core (EF Core)?

Interview Answer

Entity Framework Core is an Object-Relational Mapper (ORM) for .NET that allows developers to work with databases using C# objects instead of writing SQL manually.

It maps:

C# Classes  <----->  Database Tables


Example

Entity:

public class Customer

{

    public int Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

}

Database table:

Customers

Id

Name

Email


DbContext

The DbContext manages database communication.

Example:

public class AppDbContext : DbContext

{

    public DbSet<Customer> Customers { get; set; }

}

Query:

var customers =

    await context.Customers.ToListAsync();

EF Core generates SQL:

SELECT *

FROM Customers;


Benefits


Limitations


Senior Answer

EF Core improves developer productivity by mapping objects to relational data, but I always analyze generated SQL and use raw SQL when performance-critical operations require it.


22. What is DbContext in EF Core?

Interview Answer

DbContext is the main class responsible for communication between the application and the database.

It manages:


Example:

public class ApplicationDbContext

    : DbContext

{

    public DbSet<Order> Orders { get; set; }

}


Adding data:

context.Orders.Add(order);

await context.SaveChangesAsync();

Generated SQL:

INSERT INTO Orders(...)

VALUES(...);


DbContext Lifetime

Common in ASP.NET Core:

services.AddDbContext<AppDbContext>();

Default:

Scoped lifetime

Meaning:

One HTTP Request

        |

One DbContext instance


Important Rule

Do not keep DbContext as a singleton.

Bad:

Application lifetime

      |

One DbContext

Problems:


Senior Answer

DbContext represents a unit of work in EF Core. In web applications I typically use a scoped lifetime so each request has its own context.


23. What is change tracking in EF Core?

Interview Answer

Change tracking allows EF Core to detect modifications to entities and automatically generate SQL updates.


Example:

Load customer:

var customer =

    await context.Customers

    .FirstAsync(x=>x.Id==1);

EF Core tracks:

Original:

Name = John

Change:

customer.Name = "Mike";

Save:

await context.SaveChangesAsync();

EF generates:

UPDATE Customers

SET Name='Mike'

WHERE Id=1;


Entity States

EF Core tracks:

State

Meaning

Added

New entity

Modified

Changed entity

Deleted

Remove entity

Unchanged

No changes

Detached

Not tracked


Performance Issue

Tracking thousands of records:

var data =

await context.Orders.ToListAsync();

Consumes memory.


Solution:

var data =

await context.Orders

.AsNoTracking()

.ToListAsync();


Senior Answer

Change tracking is useful for updates, but for read-only scenarios I use AsNoTracking to reduce memory usage and improve performance.


24. What is AsNoTracking in EF Core?

Interview Answer

AsNoTracking disables EF Core change tracking for a query.

It is used for read-only operations.


Normal query:

var products =

await context.Products.ToListAsync();

EF stores:

Product 1 → tracked

Product 2 → tracked

Product 3 → tracked


With AsNoTracking:

var products =

await context.Products

.AsNoTracking()

.ToListAsync();

EF returns:

Product objects only

No tracking information.


Benefits


Example

Good:

Dashboard

Reports

Search Results


Not good:

Edit Customer

Update Order

because EF does not know changes.


Senior Answer

I use AsNoTracking for read-heavy scenarios where entities are not modified. It improves performance by avoiding unnecessary tracking overhead.


25. Explain Lazy Loading, Eager Loading, and Explicit Loading.

Interview Answer

These are three ways EF Core loads related data.


1. Eager Loading

Loads related data immediately.

Example:

Customer:

public class Customer

{

    public int Id {get;set;}

    public ICollection<Order> Orders {get;set;}

}

Query:

var customer =

await context.Customers

.Include(x=>x.Orders)

.FirstAsync();

SQL:

SELECT *

FROM Customers

JOIN Orders

ON Customers.Id=Orders.CustomerId


2. Lazy Loading

Loads related data only when accessed.

Example:

customer.Orders

Triggers database query automatically.


Problem:

Can create N+1 queries.


3. Explicit Loading

Developer controls when data loads.

Example:

context.Entry(customer)

.Collection(x=>x.Orders)

.Load();


Comparison

Type

When Data Loads

Eager

Immediately

Lazy

When accessed

Explicit

Manually


Senior Answer

I usually prefer eager loading for known relationships and explicit loading when I need control. I use lazy loading carefully because it can create hidden database calls.


26. What is the N+1 query problem?

Interview Answer

The N+1 problem occurs when an application executes one query to load parent records and then additional queries for each related record.


Example:

Load customers:

var customers =

await context.Customers.ToListAsync();

SQL:

SELECT *

FROM Customers;

Returns:

100 customers

Then:

foreach(var customer in customers)

{

    customer.Orders;

}

Produces:

1 query for customers

+

100 queries for orders

Total:

101 queries


Solution

Use Include:

var customers =

await context.Customers

.Include(x=>x.Orders)

.ToListAsync();

Now:

1 optimized query


Other Solutions


Senior Answer

I detect N+1 problems by analyzing generated SQL and database logs. Usually I solve them with eager loading or projections.


27. What are EF Core migrations?

Interview Answer

EF Core migrations allow developers to manage database schema changes through code.


Example:

Add property:

public string PhoneNumber {get;set;}

Create migration:

dotnet ef migrations add AddPhoneNumber

EF generates:

Migration File

Apply:

dotnet ef database update

Generates SQL:

ALTER TABLE Customers

ADD PhoneNumber varchar(50);


Benefits


Production Considerations

Avoid automatically running:

Database.Migrate();

on large production systems.

Better:

CI/CD Pipeline

        |

Review Migration

        |

Apply Migration


Senior Answer

EF migrations are useful for managing schema changes, but production database changes should be controlled through deployment pipelines.


28. How do you optimize EF Core performance?

Interview Answer

I optimize EF Core by controlling queries, tracking, and database access patterns.


1. Use Projection

Bad:

var customers =

await context.Customers.ToListAsync();

Loads everything.


Better:

var result =

await context.Customers

.Select(x=>new

{

    x.Id,

    x.Name

})

.ToListAsync();

Only required columns.


2. Use AsNoTracking

For reads:

.AsNoTracking()


3. Avoid N+1 Queries

Use:

.Include()

or projections.


4. Pagination

Bad:

.ToListAsync()

Large table.

Better:

.Skip(100)

.Take(50)


5. Review Generated SQL

Use:

.ToQueryString()

Example:

var sql =

query.ToQueryString();


Senior Answer

EF Core performance comes from understanding generated SQL, minimizing data transfer, controlling tracking, and designing efficient queries.


29. How do you handle transactions in EF Core?

Interview Answer

EF Core supports transactions to ensure multiple operations succeed or fail together.


Example:

using var transaction =

await context.Database

.BeginTransactionAsync();

try

{

    context.Orders.Add(order);

    await context.SaveChangesAsync();

    context.Payments.Add(payment);

    await context.SaveChangesAsync();

    await transaction.CommitAsync();

}

catch

{

    await transaction.RollbackAsync();

}


Automatic Transactions

EF Core automatically creates a transaction for:

SaveChanges()

when multiple changes occur.


When Use Explicit Transactions?

Examples:


Senior Answer

EF Core provides automatic transaction handling, but I use explicit transactions when coordinating multiple operations that must succeed together.


30. How do you prevent SQL Injection?

Interview Answer

SQL injection occurs when malicious SQL is inserted into application input.


Dangerous Example

var sql =

"SELECT * FROM Users WHERE Name='"

+ userInput

+ "'";

User enters:

' OR 1=1 --

Generated SQL:

SELECT *

FROM Users

WHERE Name='' OR 1=1


Solution 1 — Parameterized Queries

Good:

context.Users

.Where(x=>x.Name == userInput);

EF generates:

WHERE Name=@p0


Solution 2 — Stored Procedures with Parameters

Good:

CREATE PROCEDURE GetUser

(

 @Name varchar(50)

)


Solution 3 — Input Validation

Validate:


Senior Answer

I prevent SQL injection by using parameterized queries, ORM protections, input validation, and avoiding dynamic SQL whenever possible.

31. Explain SQL Server architecture.

Interview Answer

SQL Server architecture consists of several major components responsible for processing queries, managing memory, storing data, and handling transactions.


High-Level Architecture

Application

    |

SQL Query

    |

SQL Server Engine

    |

+-------------------+

| Query Processor   |

+-------------------+

+-------------------+

| Storage Engine    |

+-------------------+

+-------------------+

| Buffer Manager    |

+-------------------+

+-------------------+

| Transaction Log   |

+-------------------+

    |

Database Files


Query Processor

Responsible for:

Example:

SELECT *

FROM Orders

WHERE CustomerId = 10;

SQL Server decides:

Table Scan?

or

Index Seek?


Storage Engine

Responsible for:


Buffer Manager

Manages memory cache.

Example:

First query:

Disk -> Memory -> Result

Second query:

Memory -> Result

Much faster.


Transaction Log

Records database changes.

Example:

UPDATE Account

SET Balance=500

SQL Server writes:

Transaction Log

Before:

400

After:

500

Used for:


Senior Answer

SQL Server separates query processing from data storage. The query processor determines the optimal execution strategy, while the storage engine manages data access, caching, and transaction durability.


32. How does SQL Server execute a query?

Interview Answer

SQL Server processes queries through several stages.


Step 1 — Parsing

SQL Server checks syntax.

Example:

SELECT *

FROM Customers;

Checks:


Step 2 — Compilation

SQL Server creates an execution plan.

Example:

Use index IX_Customer_Email


Step 3 — Optimization

The query optimizer evaluates possible plans.

Example:

Option A:

Table Scan

Cost: 100

Option B:

Index Seek

Cost: 5

SQL Server chooses Option B.


Step 4 — Execution

Storage engine retrieves data.


Example

Query:

SELECT *

FROM Orders

WHERE OrderId=100;

Execution:

Parse

 |

Optimize

 |

Index Seek

 |

Return Row


Senior Answer

SQL Server parses the query, generates an execution plan through the optimizer, and executes it using the storage engine.


33. What is the SQL Server query optimizer?

Interview Answer

The Query Optimizer is the component that determines the most efficient way to execute a SQL query.


It considers:


Example:

Query:

SELECT *

FROM Orders

WHERE CustomerId=100;

Possible plans:

Plan 1:

Scan 50 million rows

Plan 2:

Use index IX_CustomerId

Optimizer chooses:

Plan 2


Cost-Based Optimization

SQL Server assigns estimated costs:

Plan A = 80%

Plan B = 10%

Plan C = 40%

Chooses lowest cost.


Problems

Sometimes optimizer chooses a poor plan because of:


Senior Answer

The optimizer creates execution plans based on statistics and estimated cost. Maintaining indexes and statistics is critical for good query performance.


34. What are SQL Server statistics?

Interview Answer

Statistics contain information about data distribution that SQL Server uses to create efficient execution plans.


Example:

Column:

CustomerId

Statistics tell SQL Server:

Customer 100:

5000 rows

Customer 200:

20 rows


Query:

SELECT *

FROM Orders

WHERE CustomerId=200;

SQL Server estimates:

Only 20 rows

Uses:

Index Seek


If statistics are wrong:

SQL Server may choose:

Table Scan


Updating Statistics

Automatic:

AUTO_UPDATE_STATISTICS

Manual:

UPDATE STATISTICS Orders;


Senior Answer

Statistics help the optimizer estimate row counts and choose efficient execution plans. Outdated statistics are a common cause of unexpected performance issues.


35. What is index fragmentation?

Interview Answer

Index fragmentation occurs when the logical order of index pages no longer matches their physical order.

It happens because of:


Example:

Before:

Page 1

10

20

30

Page 2

40

50

60

After many inserts:

Page 1

10

25

30

Page 2

20

40

60

Data becomes scattered.


Problems


Check Fragmentation

SELECT *

FROM sys.dm_db_index_physical_stats

(

NULL,

NULL,

NULL,

NULL,

'DETAILED'

);


Solutions

Reorganize

Small fragmentation:

ALTER INDEX IX_Order

ON Orders

REORGANIZE;


Rebuild

Large fragmentation:

ALTER INDEX IX_Order

ON Orders

REBUILD;


Senior Answer

I monitor fragmentation and rebuild or reorganize indexes depending on fragmentation level and workload characteristics.


36. What is the difference between index rebuild and reorganize?

Interview Answer

Both improve indexes, but they work differently.


Index Reorganize

Lightweight operation.

Characteristics:

Used for:

Small fragmentation


Index Rebuild

Recreates the entire index.

Characteristics:

Used for:

High fragmentation


Comparison

Reorganize

Rebuild

Small changes

Complete recreation

Less resource usage

More resource usage

Slower

Faster

Does not fully update statistics

Updates statistics


Senior Answer

I use reorganize for moderate fragmentation and rebuild for heavily fragmented indexes, usually scheduled during maintenance windows.


37. What is blocking in SQL Server?

Interview Answer

Blocking occurs when one transaction holds a lock and another transaction must wait.


Example:

Transaction A:

BEGIN TRAN

UPDATE Customers

SET Name='John'

WHERE Id=1;

Lock:

Customer Id=1

Transaction B:

SELECT *

FROM Customers

WHERE Id=1;

Must wait.


Diagram:

Transaction A

Lock Resource

       |

       v

Transaction B

Waiting


Causes


Find Blocking

sp_who2

or:

sys.dm_exec_requests


Solutions


Senior Answer

I analyze blocking by identifying the blocking session, checking the SQL statement holding locks, and optimizing the transaction or query causing contention.


38. Explain SQL Server locking.

Interview Answer

Locks protect data consistency when multiple transactions access the same resources.


Lock Types


Shared Lock (S)

Used for reading.

Example:

SELECT *

FROM Customers;

Multiple readers allowed.


Exclusive Lock (X)

Used for modifications.

Example:

UPDATE Customers

SET Name='John';

Only one transaction can modify data.


Update Lock (U)

Used before updating data.

Prevents update conflicts.


Intent Locks

Used for hierarchy management.

Example:

Database

 |

 Table

 |

 Row


Lock Granularity

Locks can occur at:


Senior Answer

SQL Server uses locks to maintain transaction consistency. Good indexing and short transactions reduce excessive locking.


39. How do you troubleshoot SQL Server performance issues?

Interview Answer

I follow a structured troubleshooting process.


Step 1 — Identify Symptoms

Examples:


Step 2 — Analyze Queries

Check:

Tools:


Step 3 — Check Database Health

Look at:


Step 4 — Check Infrastructure

Examples:


Example

Problem:

API response increased from 300ms to 10 seconds

Investigation:

API

 |

SQL Query

 |

Execution Plan

 |

Table Scan

 |

Missing Index

 |

Create Index

 |

Performance Improved


Senior Answer

I use a data-driven approach: identify the bottleneck, analyze execution plans and metrics, make targeted changes, and validate improvements.


40. How do you optimize a table with hundreds of millions of rows?

Interview Answer

For very large tables, I focus on indexing, partitioning, archiving, and query patterns.


1. Proper Indexing

Example:

Large table:

StockPrices

900 million rows

Query:

SELECT *

FROM StockPrices

WHERE StockId=100

AND SavedAt > '2026-01-01';

Possible index:

CREATE INDEX IX_StockPrices

ON StockPrices

(

    StockId,

    SavedAt

);


2. Partitioning

Split large table into smaller logical sections.

Example:

Partition by year:

2024 Data

2025 Data

2026 Data

Query:

Only scan 2026 partition


3. Archiving

Move old data:

Active Table

Last 2 years

Archive Table

Older data


4. Pagination

Avoid:

SELECT *

FROM LargeTable;

Use:

OFFSET 1000

FETCH NEXT 50 ROWS;


5. Batch Processing

Avoid:

DELETE FROM Logs;

Use:

DELETE TOP(10000)

FROM Logs;


Senior Answer

For billion-row tables, I design around access patterns: proper indexes, partitioning, archiving strategies, query optimization, and controlled batch operations.

41. What is database normalization in enterprise systems?

Interview Answer

Database normalization is the process of organizing data to reduce duplication and maintain data consistency.

In enterprise applications, normalized databases are commonly used for transactional systems because data integrity is critical.


Example

Poor Design

CustomerOrders

OrderId

CustomerName

CustomerEmail

ProductName

ProductPrice

Problem:

Customer information is duplicated:

John john@test.com

John john@test.com

John john@test.com


Normalized Design

Customer table:

Customers

CustomerId

Name

Email

Orders table:

Orders

OrderId

CustomerId

OrderDate

Products:

Products

ProductId

Name

Price


Benefits


When Not to Fully Normalize?

For reporting and analytics:

Data Warehouse

Reporting Database

Dashboards

some duplication may improve performance.


Senior Answer

I normally design OLTP systems using normalization principles, but I apply controlled denormalization for reporting and read-heavy workloads where performance is more important than minimizing duplication.


42. What is database denormalization?

Interview Answer

Denormalization intentionally duplicates data to improve read performance.


Example:

Normalized:

Customers

CustomerId

Name

Orders

OrderId

CustomerId

Total

Query requires:

JOIN Customers

JOIN Orders


Denormalized:

Orders

OrderId

CustomerName

Total

Now:

SELECT *

FROM Orders;

No join required.


Advantages


Disadvantages


Common Examples

Reporting Table

SalesSummary

Month

Region

TotalSales

CustomerCount


Data Warehouse

Uses:


Senior Answer

I use denormalization when read performance is critical, especially for reporting systems and analytics platforms, while keeping transactional databases mostly normalized.


43. What is database partitioning?

Interview Answer

Database partitioning divides a large table into smaller physical sections while keeping it logically as one table.


Example:

Large table:

StockPrices

1 billion rows

Partition by date:

Partition 2024

Partition 2025

Partition 2026


Query:

SELECT *

FROM StockPrices

WHERE SavedAt >= '2026-01-01';

SQL Server can read only:

Partition 2026

This is called:

Partition Elimination


Types

Range Partitioning

Most common.

Example:

Date ranges

2025-01

2025-02

2025-03


List Partitioning

Based on values.

Example:

Region

Canada

USA

Europe


Benefits


Limitations


Senior Answer

I use partitioning for very large tables where queries naturally filter by the partition key, such as date-based transactional or historical data.


44. What is database sharding?

Interview Answer

Sharding distributes data across multiple database servers.

Unlike partitioning, which happens inside one database server, sharding distributes data horizontally across different servers.


Example:

Customers:

CustomerId 1-1,000,000

Database A

CustomerId 1,000,001-2,000,000

Database B


Architecture:

             Application

                   |

              Sharding Logic

             /             \

       Database A       Database B


Sharding Key

A value used to decide where data goes.

Example:

CustomerId % 2

Result:

Even IDs -> Database A

Odd IDs -> Database B


Advantages


Challenges


Senior Answer

Sharding is useful when a single database cannot scale vertically anymore. However, it introduces complexity around data distribution and cross-database operations.


45. What is database replication?

Interview Answer

Replication copies data from one database server to another.

It is used for:


Architecture:

            Primary Database

                    |

              Replication

                    |

          Secondary Database


SQL Server Replication Types

Transactional Replication

Copies changes almost immediately.

Good for:


Snapshot Replication

Copies entire database periodically.


Merge Replication

Allows changes at multiple locations.


Example

Production:

Orders Database

Replication:

Reporting Database

Reports do not affect production performance.


Senior Answer

Replication improves availability and read scalability by maintaining copies of data, but consistency and conflict handling must be carefully designed.


46. What are SQL Server Always On Availability Groups?

Interview Answer

Always On Availability Groups provide high availability and disaster recovery by maintaining synchronized copies of databases.


Architecture:

            Application

                  |

             Listener

                  |

        +---------+---------+

    Primary              Secondary

    Read/Write            Read Only


Features

Automatic Failover

If primary fails:

Primary Down

      |

Secondary becomes Primary


Readable Secondary

Reports can run on secondary:

Reporting Query

      |

Secondary Server


Data Synchronization

Modes:

Synchronous

Primary commits

       |

Secondary confirms

Higher consistency.


Asynchronous

Primary commits

       |

Secondary catches up

Better performance.


Senior Answer

Always On Availability Groups provide database-level high availability by synchronizing databases between primary and secondary replicas with configurable failover options.


47. Explain database backup strategies.

Interview Answer

A backup strategy defines how data can be recovered after failures.


Types of SQL Server Backups


Full Backup

Copies the entire database.

Example:

Sunday 2 AM

Full Backup


Differential Backup

Copies changes since the last full backup.

Example:

Monday

Changes since Sunday


Transaction Log Backup

Copies transaction log changes.

Example:

Every 15 minutes


Recovery Example

Failure:

Wednesday 10:00 AM

Restore:

Sunday Full Backup

+

Wednesday Differential

+

Transaction Logs


Important Concepts

RPO

How much data can be lost.

Example:

15 minutes


RTO

How quickly system must recover.

Example:

1 hour


Senior Answer

Backup strategy should be designed according to business RPO and RTO requirements, using appropriate combinations of full, differential, and transaction log backups.


48. How do you migrate SQL Server data to PostgreSQL?

Interview Answer

Database migration requires schema conversion, data transfer, validation, and application changes.


Migration Process

SQL Server

    |

Schema Conversion

    |

Data Migration

    |

Validation

    |

Application Update

    |

PostgreSQL


Step 1 — Analyze Differences

Examples:

SQL Server:

IDENTITY

GETDATE()

NVARCHAR

PostgreSQL:

SERIAL / IDENTITY

CURRENT_TIMESTAMP

VARCHAR


Step 2 — Convert Schema

Convert:


Step 3 — Transfer Data

Tools:


Step 4 — Validate

Check:


Step 5 — Update Application

Changes may include:


Senior Answer

I approach migrations incrementally: analyze differences, migrate schema, transfer data, validate results, and gradually move application traffic to the new database.


49. What are the differences between SQL Server and PostgreSQL?

Interview Answer

Both are powerful relational databases, but they have different ecosystems and features.


SQL Server

PostgreSQL

Microsoft ecosystem

Open source

T-SQL

SQL + extensions

Strong Windows/Azure integration

Strong Linux/cloud adoption

SSMS tooling

Multiple open tools

Proprietary

Open source


Data Types

SQL Server:

nvarchar

datetime

money

PostgreSQL:

varchar

timestamp

numeric


Identity Columns

SQL Server:

IDENTITY(1,1)

PostgreSQL:

GENERATED AS IDENTITY


JSON Support

PostgreSQL has very strong JSON capabilities:

jsonb


Senior Answer

Both databases are enterprise capable. The choice depends on ecosystem, workload requirements, operational experience, and application needs.


50. What is a reporting database?

Interview Answer

A reporting database is a separate database optimized for analytics and reporting instead of transactional workloads.


Architecture:

Production Database

        |

      ETL

        |

Reporting Database

        |

Reports / Dashboards


Why Separate?

Production workload:

INSERT

UPDATE

DELETE

Reporting workload:

Large SELECT queries

Aggregations

GROUP BY

They compete for resources.


Common Technologies


Example

Production:

Orders

Customers

Payments

Reporting:

DailySalesSummary

CustomerStatistics

RevenueByRegion


Senior Answer

I separate reporting workloads from transactional databases to improve performance and scalability. ETL processes populate reporting databases optimized for analytical queries.

51. What is a data warehouse?

Interview Answer

A data warehouse is a centralized system designed for storing and analyzing large amounts of historical data.

Unlike transactional databases (OLTP), data warehouses are optimized for reporting and analytics (OLAP).


OLTP vs Data Warehouse

OLTP

Data Warehouse

Daily transactions

Historical analysis

INSERT/UPDATE/DELETE

Mostly SELECT

Current data

Historical data

Normalized

Often denormalized

Many small queries

Large analytical queries


Example

Operational database:

Orders

OrderId

CustomerId

ProductId

Amount

Date

Data warehouse:

SalesFact

DateKey

CustomerKey

ProductKey

Amount


Typical Architecture

Applications

     |

Operational Databases

     |

ETL Pipeline

     |

Data Warehouse

     |

BI Reports / Analytics


Technologies

Examples:


Senior Answer

A data warehouse separates analytical workloads from transactional systems and provides optimized storage for historical reporting and business intelligence.


52. What is a star schema?

Interview Answer

A star schema is a common data warehouse design where a central fact table is connected to multiple dimension tables.


Architecture:

             Date

               |

               |

Customer --- Sales Fact --- Product

               |

               |

            Location


Fact Table

Contains measurable business events.

Example:

SalesFact

DateKey

CustomerKey

ProductKey

Quantity

Revenue


Dimension Tables

Contain descriptive information.

Example:

Customer:

CustomerKey

CustomerName

Country

Segment

Product:

ProductKey

ProductName

Category


Benefits


Example Query

Revenue by country:

SELECT

Country,

SUM(Revenue)

FROM SalesFact

JOIN Customer

ON SalesFact.CustomerKey = Customer.CustomerKey

GROUP BY Country;


Senior Answer

Star schema simplifies analytical queries by separating measurable facts from descriptive dimensions.


53. What is ETL?

Interview Answer

ETL stands for:

It is a process for moving and preparing data for analytics.


Architecture

Source Systems

      |

   Extract

      |

   Transform

      |

     Load

      |

Data Warehouse


Extract

Read data from sources.

Examples:


Transform

Clean and modify data.

Examples:

Remove duplicates:

John Smith

John Smith

Convert:

USD → CAD

Calculate:

Total Revenue


Load

Insert into destination.

Example:

SalesFact table


ETL Tools


Senior Answer

ETL pipelines extract data from operational systems, transform it into a consistent format, and load it into analytical storage.


54. What is the difference between ETL and ELT?

Interview Answer

The difference is where transformation happens.


ETL

Transform before loading.

Source

 |

Transform

 |

Warehouse

Common in traditional systems.


ELT

Load first, transform inside the warehouse.

Source

 |

Warehouse

 |

Transform

Common in cloud platforms.


Comparison

ETL

ELT

Transform before loading

Transform after loading

Traditional systems

Cloud data platforms

Less raw data stored

Raw data retained

More controlled

More flexible


Example

AWS:

S3

 |

Redshift

 |

SQL Transformations

is ELT.


Senior Answer

Modern cloud architectures often use ELT because cloud warehouses provide scalable compute for transformations.


55. How would you design a database for a high-volume application?

Interview Answer

I start with workload requirements and design for scalability, availability, and performance.


Architecture Example

               Users

                  |

             Application API

                  |

              Cache Layer

                  |

          Database Cluster

          /             \

     Primary          Replica


Key Decisions

1. Data Model

Choose:


2. Scaling

Vertical:

Bigger server

Horizontal:

More servers


3. Caching

Example:

Redis

Reduce database load.


4. Partitioning

For large tables.

Example:

Orders by year


5. Async Processing

Use queues:

Order Created

      |

Message Queue

      |

Background Worker


Senior Answer

I design high-volume databases around access patterns, indexing, caching, partitioning, asynchronous processing, and high availability requirements.


56. What is SQL Server on AWS RDS?

Interview Answer

Amazon RDS for SQL Server is a managed database service where AWS handles infrastructure management.

AWS manages:


Architecture

Application

    |

AWS RDS SQL Server

    |

Storage


Features

Automated Backups

AWS automatically performs backups.


Multi-AZ Deployment

Primary:

Availability Zone A

Secondary:

Availability Zone B


Monitoring

Integration with:


Limitations

Compared with self-managed SQL Server:


Senior Answer

RDS reduces operational overhead by managing database infrastructure, while still providing SQL Server capabilities, backups, monitoring, and high availability options.


57. How do you optimize SQL Server running on AWS RDS?

Interview Answer

Optimization includes database-level and cloud-level tuning.


Database Optimization

Indexes

Analyze:

Execution Plans


Query Optimization

Find:


Statistics

Keep updated.


AWS Optimization

Instance Size

Monitor:


Storage

Choose appropriate:


Read Replicas

For read-heavy workloads.


Monitoring

Use:


Senior Answer

I optimize RDS by combining SQL Server tuning practices with AWS monitoring and capacity planning.


58. How do you secure a database?

Interview Answer

Database security requires multiple layers.


1. Authentication

Control who can connect.

Examples:


2. Authorization

Control permissions.

Example:

Application User

SELECT only


3. Encryption

Encryption at Rest

Protect database files.

Examples:


Encryption in Transit

Use:

TLS/SSL


4. Least Privilege

Avoid:

Application = Database Admin

Better:

Application

SELECT

INSERT

UPDATE


5. Auditing

Track:


Senior Answer

I secure databases using least privilege, encryption, auditing, secure authentication, and continuous monitoring.


59. What is Transparent Data Encryption (TDE)?

Interview Answer

TDE encrypts database files at rest.

It protects data if someone obtains the physical database files.


Architecture:

Database Files

      |

Encryption Layer

      |

Encrypted Storage


Example:

Without TDE:

Database file

contains readable data

With TDE:

Database file

encrypted


Important

TDE protects:

It does not protect:


Senior Answer

TDE provides encryption at rest by encrypting database files and backups, helping protect against unauthorized access to storage media.


60. Design a database architecture for an enterprise application.

Interview Answer

I would design based on scalability, availability, security, and maintainability.


Example Architecture

                   Users

                      |

               Load Balancer

                      |

              Application Services

                      |

        +-------------+-------------+

       Cache                    Database

      Redis                 SQL Server

                                  |

                         Read Replicas

                                  |

                         Reporting DB


Database Layer

Primary Database

Handles:


Read Replicas

Handle:


Cache

Stores:


Message Queue

For asynchronous processing:

Order Created

      |

RabbitMQ / SQS

      |

Background Worker


Security

Include:


Monitoring

Track:


Senior Answer

I design enterprise database architectures with separation of workloads, appropriate scaling strategies, strong security controls, and monitoring to support reliability and growth.