This SQL Server interview preparation guide focuses on understanding each concept, explaining when it matters, and supporting your answer with a practical example. Use it as a revision checklist and practise explaining the ideas in your own words.
1. What are DDL, DML, DCL and TCL commands?
Answer: DDL defines or changes database objects, such as CREATE, ALTER and DROP. DML reads or changes table data, such as SELECT, INSERT, UPDATE and DELETE. DCL controls permissions, for example GRANT and REVOKE. TCL controls transaction boundaries, such as BEGIN TRANSACTION, COMMIT and ROLLBACK. Classifications can vary slightly by teaching source, but these groups are a useful interview framework.
Example
CREATE TABLE dbo.Employee (Id int PRIMARY KEY, Name varchar(100));
INSERT INTO dbo.Employee (Id, Name) VALUES (1, 'Asha');
BEGIN TRANSACTION;
UPDATE dbo.Employee SET Name = 'Asha K' WHERE Id = 1;
COMMIT;
2. What is the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?
Answer: INNER JOIN returns only rows with matching join keys on both sides. LEFT JOIN returns every left-side row and matching right-side rows, filling unmatched right columns with NULL. RIGHT JOIN is the mirror image. FULL OUTER JOIN returns matched rows plus unmatched rows from both sides. Choose the join based on which unmatched records the result must retain.
Example
SELECT c.CustomerId, o.OrderId
FROM dbo.Customer AS c
LEFT JOIN dbo.[Order] AS o ON o.CustomerId = c.CustomerId;
3. What is the difference between WHERE and HAVING?
Answer: WHERE filters individual rows before grouping and aggregation. HAVING filters groups after GROUP BY has formed them and aggregate values are available. Put non-aggregate row conditions in WHERE when possible because reducing rows earlier can make the query easier for the optimizer. HAVING is appropriate for conditions such as groups with more than five orders.
Example
SELECT CustomerId, COUNT(*) AS OrderCount
FROM dbo.[Order]
WHERE OrderDate >= '2026-01-01'
GROUP BY CustomerId
HAVING COUNT(*) > 5;
4. What is the difference between a subquery and a CTE?
Answer: A subquery is a query nested inside another statement. A common table expression (CTE) is a named query expression introduced with WITH and scoped to a single statement. CTEs can improve readability and support recursive queries. They are not automatically materialised or faster than equivalent subqueries; the optimizer may produce similar plans. Use the form that makes the logic clearest, then measure.
Example
WITH HighValueOrders AS (
SELECT OrderId, CustomerId, Total
FROM dbo.[Order] WHERE Total > 10000
)
SELECT * FROM HighValueOrders;
5. What is a recursive CTE?
Answer: A recursive CTE references itself to process hierarchical or iterative data, such as an employee-manager tree or category hierarchy. It consists of an anchor member and a recursive member combined with UNION ALL. The recursion stops when the recursive member returns no more rows or a recursion limit is reached. Prevent cycles in the underlying data or include safeguards to avoid runaway recursion.
Example
WITH Org AS (
SELECT EmployeeId, ManagerId, 0 AS Level
FROM dbo.Employee WHERE ManagerId IS NULL
UNION ALL
SELECT e.EmployeeId, e.ManagerId, o.Level + 1
FROM dbo.Employee e JOIN Org o ON e.ManagerId = o.EmployeeId
)
SELECT * FROM Org OPTION (MAXRECURSION 100);
6. What is a clustered index?
Answer: A clustered index defines the row organisation of a table’s data pages around the clustered key. A table can have only one clustered index because the data rows can have only one clustered order. The key should usually be stable and appropriately narrow. A clustered index is not necessarily the primary key, although a primary key is clustered by default in some table-creation patterns unless specified otherwise.
Example
CREATE CLUSTERED INDEX IX_Order_OrderDate
ON dbo.[Order](OrderDate, OrderId);
7. What is a nonclustered index?
Answer: A nonclustered index is a separate index structure containing key values and row locators. It can help SQL Server find rows without scanning the whole table. A table can have multiple nonclustered indexes, but each adds storage and maintenance cost to INSERT, UPDATE and DELETE operations. Design indexes around actual query predicates, join keys and ordering, and verify usage through execution plans and workload data.
Example
CREATE NONCLUSTERED INDEX IX_Employee_Department
ON dbo.Employee(DepartmentId);
8. What is a covering index and how does INCLUDE help?
Answer: A covering index contains all columns needed by a query, either as key columns or included non-key columns. SQL Server can then satisfy the query from the index without an additional key lookup to the base table. INCLUDE is useful for output columns that do not need to participate in sorting or seeking. Keep covering indexes focused because wide indexes consume more space and slow writes.
Example
CREATE INDEX IX_Order_CustomerDate
ON dbo.[Order](CustomerId, OrderDate)
INCLUDE (Total, Status);
9. What is SARGability?
Answer: A predicate is SARGable when SQL Server can use an index efficiently to seek matching ranges. Applying a function or calculation to an indexed column can make a predicate harder to seek. Rewrite conditions so the indexed column is compared directly to a value or range where possible. The optimizer may transform some expressions, so always validate the actual execution plan.
Example
-- Less seek-friendly in many cases
WHERE YEAR(OrderDate) = 2026
-- Range predicate is generally more SARGable
WHERE OrderDate >= '2026-01-01'
AND OrderDate < '2027-01-01'
10. What is an execution plan?
Answer: An execution plan shows how SQL Server intends to retrieve or modify data. It includes operators such as scans, seeks, joins, sorts and lookups, along with estimated or actual row counts and costs. Use an actual execution plan with runtime statistics to investigate expensive operators, cardinality-estimation differences, missing or unused indexes and implicit conversions. Do not optimise based only on a single graphical cost percentage.
Example
In SSMS, enable Include Actual Execution Plan, run the query, then compare estimated rows with actual rows and inspect expensive reads, sorts and lookups.
11. What are ACID properties?
Answer: ACID describes core transaction properties. Atomicity means a transaction succeeds as a unit or rolls back. Consistency means constraints and rules remain satisfied. Isolation controls how concurrent transactions see one another’s changes. Durability means committed changes survive failures according to the database’s durability guarantees. These properties help explain why transaction boundaries and isolation levels matter in production systems.
Example
BEGIN TRANSACTION;
UPDATE dbo.Account SET Balance = Balance - 500 WHERE AccountId = 1;
UPDATE dbo.Account SET Balance = Balance + 500 WHERE AccountId = 2;
COMMIT;
12. What are SQL Server transaction isolation levels?
Answer: Isolation levels define which effects of concurrent transactions a query may observe. READ UNCOMMITTED permits dirty reads. READ COMMITTED prevents dirty reads and is the common default. REPEATABLE READ protects rows already read from changing before the transaction ends. SERIALIZABLE provides stronger range protection but can reduce concurrency. SNAPSHOT uses row versions to provide a transaction-consistent view when enabled. Choose based on correctness and workload, not simply the strongest level.
Example
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
SELECT * FROM dbo.Inventory WHERE ProductId = 10;
COMMIT;
13. What is a deadlock and how can you handle it?
Answer: A deadlock occurs when transactions hold resources while waiting for resources held by one another, forming a cycle. SQL Server detects the cycle and chooses a victim transaction to roll back. Reduce deadlocks by accessing tables and rows in a consistent order, keeping transactions short, adding appropriate indexes and avoiding user interaction inside transactions. Applications should be prepared to retry a deadlock-victim operation when it is safe.
Example
If one process updates Customer then Order while another updates Order then Customer, make both code paths acquire resources in the same order where possible.
14. What is the difference between a primary key and a unique constraint?
Answer: A primary key uniquely identifies each row and does not allow NULL values. A table can have one primary key, which may contain multiple columns. A table can have multiple unique constraints, which enforce uniqueness on alternate candidate keys; NULL handling for unique indexes in SQL Server follows SQL Server’s uniqueness rules. Both commonly create supporting unique indexes.
Example
CREATE TABLE dbo.Employee (
EmployeeId int PRIMARY KEY,
Email varchar(200) NOT NULL UNIQUE
);
15. What is the difference between a stored procedure and a function?
Answer: A stored procedure is executed with EXEC and can perform multiple statements, modify data and return result sets or output parameters. A user-defined function returns a scalar or table value and is designed to be used within expressions or queries, with restrictions on side effects and permitted operations. Choose a procedure for an operation or workflow; choose a function when a reusable value or table expression belongs in a query.
Example
CREATE PROCEDURE dbo.GetOrdersByCustomer @CustomerId int
AS
BEGIN
SELECT * FROM dbo.[Order] WHERE CustomerId = @CustomerId;
END;
16. What are window functions?
Answer: Window functions calculate values across a set of related rows while retaining individual rows in the result. The OVER clause defines the partition and ordering. Common functions include ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD and aggregate functions used as windows. They are useful for ranking, running totals, comparisons with previous rows and selecting the latest record per group.
Example
SELECT EmployeeId, DepartmentId, Salary,
ROW_NUMBER() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) AS rn
FROM dbo.Employee;
17. How do you implement pagination in SQL Server?
Answer: Offset pagination uses ORDER BY with OFFSET and FETCH NEXT to return a page of rows. It requires a deterministic order, ideally including a unique tie-breaker. Large offsets can become expensive because the database may still need to process skipped rows. Keyset pagination, using the last-seen key as a filter, can perform better for sequential navigation through large datasets.
Example
SELECT OrderId, OrderDate, Total
FROM dbo.[Order]
ORDER BY OrderDate DESC, OrderId DESC
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
18. How can you prevent SQL injection?
Answer: Use parameterised queries or stored procedure parameters so input is treated as data, not executable SQL. Avoid concatenating user input into command text. Validate and authorise values even when parameterised; parameters do not replace business validation or permission checks. For dynamic identifiers such as column names, use a strict allow-list because identifiers generally cannot be supplied as ordinary value parameters.
Example
using var cmd = new SqlCommand(
"SELECT * FROM dbo.Employee WHERE Email = @Email", connection);
cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 200).Value = email;
19. What is the difference between DELETE, TRUNCATE and DROP?
Answer: DELETE removes selected rows and can use a WHERE clause; it logs row deletions and fires DELETE triggers. TRUNCATE removes all rows from a table by deallocating data pages, does not support WHERE and has restrictions such as foreign-key references; it is generally more efficient for clearing a table. DROP removes the table object itself, including its definition. Transaction and identity behaviour should be checked for the particular operation and schema.
Example
DELETE FROM dbo.Logs WHERE CreatedAt < DATEADD(day, -90, SYSUTCDATETIME());
TRUNCATE TABLE dbo.StageImport;
-- DROP TABLE dbo.OldArchive; -- removes the table definition
20. How do you troubleshoot and optimise a slow SQL query?
Answer: Start with the actual execution plan, logical reads, CPU time, duration and representative parameter values. Check scans, lookups, sorts, spills, implicit conversions, inaccurate estimates, missing or excessive indexes and non-SARGable predicates. Return only required columns, filter early, paginate large outputs and keep statistics current. Compare before-and-after measurements under representative load; avoid adding indexes or hints without evidence.
Example
SET STATISTICS IO, TIME ON;
SELECT CustomerId, SUM(Total)
FROM dbo.[Order]
WHERE OrderDate >= @FromDate
GROUP BY CustomerId;
SET STATISTICS IO, TIME OFF;
How to prepare for your interview
Do not memorise definitions word for word. Practise explaining the concept in your own words, describe when you would use it, and mention one trade-off or common mistake. For coding and database topics, write the example yourself and test the edge cases.
Use this guide as a revision checklist, then review the topics you find difficult in more depth. Interview discussions often move from fundamentals to project decisions, debugging and performance scenarios.
Keep learning with DotNetRevision. Explore the ebook library for structured study guides, interview preparation and practical professional-development resources.