SQL Server and T-SQL interview questions and answers

SQL Server interview questions go past standard SQL into how Microsoft's engine behaves: recovery models and the transaction log, clustered index design, key lookups and covering indexes, statistics and parameter sniffing, T-SQL error handling with TRY...CATCH and XACT_ABORT, isolation levels including read committed snapshot, and why NOLOCK is not a free speed-up. DBA roles add wait statistics, Query Store, backups and Always On availability groups.

By Published 8 min read

What a SQL Server interview covers

SQL Server is common in .NET shops, finance, healthcare, government and companies running the Microsoft data stack, so the same engine shows up in interviews for backend developers, database developers, DBAs and BI engineers. Expect a T-SQL writing exercise, questions about indexes and plans, and, for DBAs, operational questions about the log, backups and high availability. Interviewers like to hand you a slow stored procedure or a blocking incident and listen to your first three checks.

Focus by role
RoleWhere the questions leanTypical exercise
Database or backend developerT-SQL, indexing, plans, transactions and error handling.Write a query or procedure, then explain its plan and fix a slow version.
DBALog management, backups and restores, HA and DR, waits, security, maintenance.Walk through a restore to a point in time or a blocking incident.
BI or data engineerLarge reads, columnstore, partitioning, loads and ETL patterns.Speed up a reporting query or design an incremental load.
Focus by role. Scroll sideways on a small screen.

Fundamentals

SQL Server fundamentals for freshers and developers
QuestionWhat it testsWhat a strong answer shows
What are the system databases?Instance layoutmaster holds instance-level metadata and logins, model is the template for new databases, msdb stores Agent jobs and backup history, and tempdb holds temporary objects and version rows, rebuilt at every restart.
Simple, full and bulk-logged recovery models?Transaction logSimple reuses log space after checkpoints and allows no log backups, so no point-in-time restore. Full keeps the log until it is backed up and allows point-in-time recovery. Bulk-logged minimally logs some bulk operations.
Why does a transaction log keep growing?Log managementCommonly a database in full recovery with no log backups, a long open transaction, or replication or an availability group falling behind. Check log_reuse_wait_desc in sys.databases.
SCOPE_IDENTITY, @@IDENTITY or IDENT_CURRENT?Identity valuesSCOPE_IDENTITY returns the last identity in the current scope and session. @@IDENTITY can return a value from a trigger's insert. IDENT_CURRENT is per table across all sessions, so it races.
Temp table, table variable or CTE?Intermediate resultsA temp table lives in tempdb, can be indexed and has statistics. A table variable has limited statistics, so estimates can be poor on large sets. A CTE is just a named query, not stored, and is re-evaluated where referenced.
VARCHAR versus NVARCHAR?Data typesNVARCHAR stores Unicode, needed for names and text in many languages. Mixing the two in comparisons causes implicit conversions, covered below.
DATETIME versus DATETIME2?Data typesDATETIME2 has a larger range and configurable precision up to 100 nanoseconds. DATETIME rounds to about 3 milliseconds, which surprises range queries at the end of a day.
ISNULL versus COALESCE?FunctionsISNULL takes two arguments and returns the first argument's type, which can truncate. COALESCE takes many, follows type precedence and is standard SQL.
Why put SET NOCOUNT ON in procedures?HabitsIt stops the rows-affected message after each statement, which reduces chatter and avoids confusing some client libraries.
SQL Server fundamentals for freshers and developers. Scroll sideways on a small screen.
WITH ranked AS (
  SELECT customer_id, order_id, order_date,
         ROW_NUMBER() OVER (
           PARTITION BY customer_id
           ORDER BY order_date DESC, order_id DESC
         ) AS rn
  FROM dbo.orders
)
SELECT customer_id, order_id, order_date
FROM ranked
WHERE rn = 1;
Latest order per customer, with a tie-breaker so the result is deterministic.

Indexes, statistics and execution plans

  • What makes a good clustered index key? Narrow, unique, static and ever-increasing, such as an INT or BIGINT identity. Every nonclustered index carries the clustered key, so a wide key makes them all bigger.
  • Why is a random UNIQUEIDENTIFIER a poor clustered key? New rows land all over the index, causing page splits and fragmentation. NEWSEQUENTIALID or a separate identity clustering key avoids that if you need GUIDs.
  • What is a heap and when is it a problem? A table with no clustered index. Updates that grow a row leave forwarded records, scans get slower, and space from deletes is not always reclaimed.
  • What is a key lookup and how do you remove it? The nonclustered index found the rows, but the query needs more columns, so the engine fetches each row from the clustered index. Add the missing columns with INCLUDE, or reconsider whether the query needs them.
  • When is a filtered index useful? When queries target a small, well-defined subset, such as open orders. It is smaller and its statistics are more accurate for that subset.
  • What is a columnstore index for? Analytics on large tables: data is stored by column and compressed, and queries can use batch mode. It is a poor fit for frequent single-row lookups and updates.
  • How do statistics affect plans? The optimizer estimates row counts from histograms on columns. Stale or sampled statistics on skewed data lead to bad join choices and memory grants. Auto-update helps, but large tables can need scheduled updates.
  • Estimated versus actual execution plan? The estimated plan is the optimizer's intention. The actual plan adds real row counts, executions and warnings, such as spills to tempdb or implicit conversions.
CREATE NONCLUSTERED INDEX ix_orders_customer_date
ON dbo.orders (customer_id, order_date DESC)
INCLUDE (amount);
A covering index for a customer's recent orders: seek on customer_id, read in date order, no key lookup for amount.

T-SQL: errors, transactions and concurrency

CREATE OR ALTER PROCEDURE dbo.transfer_funds
  @from_account INT,
  @to_account   INT,
  @amount       DECIMAL(19, 4)
AS
BEGIN
  SET NOCOUNT ON;
  SET XACT_ABORT ON;

  BEGIN TRY
    BEGIN TRANSACTION;
      UPDATE dbo.accounts SET balance = balance - @amount WHERE account_id = @from_account;
      UPDATE dbo.accounts SET balance = balance + @amount WHERE account_id = @to_account;
    COMMIT TRANSACTION;
  END TRY
  BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
    THROW;
  END CATCH;
END;
A transfer that rolls back fully on any error and rethrows it to the caller.
T-SQL and concurrency questions for mid-level candidates
QuestionWhat it testsWhat a strong answer shows
Why set XACT_ABORT ON?Error handlingWithout it, some errors end only the statement and leave the transaction open. With it, most run-time errors roll back the whole transaction, and a client timeout does not leave locks behind.
THROW versus RAISERROR?Error handlingTHROW without arguments rethrows the original error with its number and line. RAISERROR is older, needs a message and does not abort the batch by itself.
Are nested transactions real?TransactionsNo. Inner BEGIN TRANSACTION only increments @@TRANCOUNT; an inner COMMIT decrements it; any ROLLBACK undoes everything to the outermost transaction unless you use savepoints.
What does the OUTPUT clause do?DMLReturns rows affected by INSERT, UPDATE, DELETE or MERGE, with inserted and deleted values. Useful for auditing, capturing new identities from a set insert, or claiming queue rows.
What are the risks of MERGE?UpsertsIt has had a history of bugs in edge cases, and without a HOLDLOCK hint, concurrent upserts can still collide. Many teams prefer a separate UPDATE then INSERT inside a transaction with proper locking.
Read committed versus RCSI versus SNAPSHOT?IsolationDefault read committed takes shared locks, so readers and writers block each other. Read committed snapshot reads the last committed version per statement from the version store. SNAPSHOT isolation does the same per transaction and can raise update conflicts.
What does NOLOCK really do?Dirty readsIt reads without shared locks, so it can return uncommitted data, and during page splits it can skip rows or read them twice. If blocking is the problem, RCSI is usually the safer fix.
How do you find the cause of a deadlock?DiagnosisRead the deadlock graph from the system_health Extended Events session: the two statements, the resources and lock modes. Fix with consistent access order, better indexes so fewer rows lock, and shorter transactions.
What is lock escalation?LockingWhen one statement holds many row or page locks, SQL Server can escalate to a table lock to save memory, which blocks others. Batching large updates keeps under the threshold.
What does CROSS APPLY add over a join?T-SQLIt runs a table expression per outer row, such as the top three orders per customer or a table-valued function. OUTER APPLY keeps rows with no match, like a left join.
T-SQL and concurrency questions for mid-level candidates. Scroll sideways on a small screen.
UPDATE TOP (10) dbo.jobs WITH (READPAST, UPDLOCK, ROWLOCK)
SET status = 'running', started_at = SYSUTCDATETIME()
OUTPUT inserted.job_id, inserted.payload
WHERE status = 'ready';
Workers claim up to ten jobs each, skipping rows another worker already locked.

Senior performance and DBA questions

  • What is parameter sniffing, and how do you handle it? A procedure's plan is compiled for the first parameter values it sees and reused. With skewed data, a plan built for a small customer can be terrible for a huge one. Options: OPTION (RECOMPILE) on that statement, OPTIMIZE FOR, a plan forced through Query Store, or splitting the logic. Newer versions add parameter-sensitive plan optimization, so check the compatibility level.
  • Why can an NVARCHAR parameter slow a query on a VARCHAR column? Data type precedence converts the column, not the parameter. Depending on collation, that can turn an index seek into a scan or a less efficient range seek. Match parameter types to column types.
  • What is Query Store for? It keeps query text, plans and run-time statistics over time, so you can see when a plan changed and force the previous one. It is often the fastest way to explain a sudden regression.
  • Which waits would you look at first? Top waits from sys.dm_os_wait_stats over a time window: PAGEIOLATCH for reads from disk, WRITELOG for log write latency, LCK_M for blocking, and parallelism waits that need context before you act on them.
  • How do you find what is running right now? sys.dm_exec_requests joined to the SQL text and plan, with blocking_session_id to trace a blocking chain to its head.
  • How should MAXDOP and cost threshold for parallelism be set? Not left blindly at defaults on modern hardware. Follow current Microsoft guidance for the core and NUMA layout, then adjust based on workload rather than folklore numbers.
  • Rebuild or reorganize indexes? Rebuild recreates the index and updates its statistics with a full scan; reorganize defragments leaf pages in place and is always online. Many teams now focus on statistics and only rebuild where fragmentation measurably hurts.
  • What causes tempdb contention? Many sessions creating temp objects at once compete for allocation pages. Several equally sized data files and newer engine improvements reduce it.
Backup, recovery and availability
QuestionWhat it testsWhat a strong answer shows
Full, differential and log backups: how do they combine?Backup strategyRestore the latest full, then the latest differential, then every log backup after it in order. Backup frequency follows the agreed recovery point objective.
What is a tail-log backup?RecoveryA last log backup taken from a damaged or about-to-be-restored database, so no committed work since the previous log backup is lost.
How do you restore to a point in time?RecoveryRestore the full and differential WITH NORECOVERY, then logs with STOPAT the chosen time, then recover. It needs full recovery and an unbroken log chain.
Always On availability groups versus a failover cluster instance?High availabilityAn availability group copies databases to replicas with their own storage and can offer readable secondaries. A failover cluster instance moves the whole instance between nodes over shared storage, protecting the server but not the storage.
Synchronous or asynchronous commit?Data loss trade-offSynchronous waits for the secondary to harden the log, allowing failover without data loss at some latency cost. Asynchronous suits distant replicas where some loss is acceptable.
Why run DBCC CHECKDB regularly?IntegrityIt finds corruption early, while backups that predate it still exist. Corruption found months late may already be in every backup you keep.
Backup, recovery and availability. Scroll sideways on a small screen.

Fictional example

Answering "A report procedure is suddenly slow. What do you do?"
Interviewer
A sales report procedure took a second yesterday and takes two minutes today. Nothing was deployed. Where do you start?
Candidate
I would open Query Store and check whether the plan changed. In a case like this I have seen a new plan compiled after a statistics update, sniffed from a call for a tiny region, using nested loops that fell apart for the largest region. Short term, I forced the previous plan in Query Store so users were unblocked. Then I looked at why the plan was fragile: the procedure had one query serving very different data sizes. I added OPTION (RECOMPILE) to that statement, since it ran a few times an hour and compile cost was trivial, tested both small and large regions, and removed the forced plan. I would also set an alert on that query's duration so we hear about it before the sales team does.

Preparation plan for a SQL Server interview

  • Days 1 and 2, T-SQL: window functions, APPLY, OUTPUT, TRY...CATCH with XACT_ABORT. Write a transfer procedure and break it on purpose to watch the rollback.
  • Days 3 and 4, indexes and plans: on a free Developer edition install or a container, build a table with a million rows, then create a key lookup, cover it, and compare actual plans.
  • Day 5, concurrency: open two sessions, cause blocking and a deadlock, read the deadlock graph, then switch on RCSI and repeat.
  • Day 6, performance: reproduce parameter sniffing with skewed data and fix it two ways. Practice explaining Query Store in a minute.
  • Day 7, operations (DBAs): recite a restore sequence to a point in time, explain availability group commit modes, and list your morning checks.

Joins, NULL logic and general query writing are covered in SQL interview questions. Oracle's engine works differently on undo, read consistency and partitioning, as Oracle Database interview questions explains. For the application side of the Microsoft stack, see .NET and ASP.NET Core interview questions.

When you practice, Natively acts as an AI interview assistant on Mac and Windows. It transcribes your mock SQL Server rounds, so you can check whether you explained parameter sniffing in plain words or buried it in jargon. In practice it can read a T-SQL task or a plan from a screenshot and point to what to examine first, and with Pro or the free trial it uses your résumé and the job description you add. Saved transcripts and notes let you track progress across sessions.

Questions people ask

What SQL Server questions are asked in interviews?

Recovery models and the transaction log, clustered index design, key lookups and covering indexes, statistics, parameter sniffing, TRY...CATCH with XACT_ABORT, isolation levels with RCSI and NOLOCK, deadlocks, Query Store, backups and Always On.

What is parameter sniffing in SQL Server?

SQL Server compiles a plan using the first parameter values a procedure receives and reuses it. With skewed data that plan can be poor for other values. Fixes include OPTION (RECOMPILE), OPTIMIZE FOR and forcing a plan in Query Store.

Why is NOLOCK considered risky?

It reads without shared locks, so results can include uncommitted changes and can skip or duplicate rows while pages move. Read committed snapshot isolation usually removes the blocking without those errors.

What do SQL Server DBA interviews focus on?

Log growth, backup and point-in-time restore sequences, Always On availability groups versus failover clusters, wait statistics and DMVs, blocking and deadlocks, DBCC CHECKDB and index and statistics maintenance.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP