SQL Server · Practice

Interview Questions

28 questions you are likely to be asked about SQL Server, from beginner to experienced level — each with a spoken-style answer, a common follow-up and a link to the lesson behind it.

Advanced 15 min Topic 31 of 31
0/31 in SQL Server

Beginner questions (9)

01What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only rows with matches in both tables. LEFT JOIN returns all rows from the left table, with NULLs for unmatched right-hand columns.

Learn: Joins
02WHERE vs HAVING?

WHERE filters rows before grouping; HAVING filters groups after GROUP BY and can use aggregate functions.

SQL Illustrative
SELECT Department, COUNT(*) AS Staff
FROM Employees
WHERE IsActive = 1
GROUP BY Department
HAVING COUNT(*) > 5;
Learn: HAVING
03DELETE vs TRUNCATE vs DROP?

DELETE removes rows (optionally filtered), is fully logged and fires triggers. TRUNCATE removes all rows quickly, resets identity and cannot use WHERE. DROP removes the table itself.

Learn: DELETE
04Primary key vs unique key vs foreign key?

A primary key uniquely identifies each row and cannot be NULL (one per table). A unique constraint enforces uniqueness but allows one NULL. A foreign key references a primary/unique key in another table to enforce referential integrity.

Learn: Primary and Foreign Keys
05What is a relational database?

A database that stores data in tables of rows and columns, links tables through keys and is queried with SQL. Constraints and transactions keep the data consistent. SQL Server, MySQL and PostgreSQL are examples.

Learn: Database Fundamentals
06How do you choose data types for columns?

Pick the smallest type that fits the domain: int or bigint for ids, decimal(18,2) for money (never float), nvarchar(n) with a sensible length for text, date or datetime2 for dates and bit for flags. Good types save space and make indexes faster.

Learn: Data Types
07In which order is a SELECT statement logically processed?

FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and finally TOP/OFFSET. That is why a column alias from SELECT can be used in ORDER BY but not in WHERE.

Learn: SELECT
08How do you sort and page results?

ORDER BY one or more columns (ASC/DESC), then OFFSET n ROWS FETCH NEXT m ROWS ONLY. Without ORDER BY the order is not guaranteed, so paging needs a deterministic order, often ending with the primary key.

Learn: ORDER BY
09What do aggregate functions do with NULLs?

COUNT(column), SUM, AVG, MIN and MAX ignore NULLs; COUNT(*) counts rows. AVG over values with NULLs therefore divides by the non-null count, which can surprise you.

Learn: Aggregate Functions

Intermediate questions (12)

01Clustered vs non-clustered index?

A clustered index defines the physical order of the table’s rows; there can be only one. A non-clustered index is a separate structure with keys and pointers to rows; a table can have many.

Learn: Indexes
02Do stored procedures prevent SQL injection?

Parameterised procedure calls do, because values are never parsed as SQL. A procedure that builds dynamic SQL by concatenating parameters is still vulnerable; use sp_executesql with parameters.

Learn: Stored Procedures
03What is a CTE and when would you use one?

A Common Table Expression (WITH name AS (…)) is a named, temporary result set for one statement. It improves readability, can be referenced multiple times and supports recursion for hierarchies.

Learn: Common Table Expressions
04Explain ROW_NUMBER, RANK and DENSE_RANK.

All are window functions. ROW_NUMBER gives unique sequential numbers. RANK gives ties the same rank and leaves gaps (1,1,3). DENSE_RANK gives ties the same rank without gaps (1,1,2).

Learn: Window Functions
05What is normalization? Explain 1NF, 2NF and 3NF.

1NF: atomic values, no repeating groups. 2NF: 1NF and every non-key column depends on the whole key. 3NF: 2NF and no non-key column depends on another non-key column. It reduces redundancy and update anomalies.

Learn: Normalization
06View vs stored procedure vs function?

A view is a saved SELECT used like a table. A stored procedure runs any logic, can modify data and return multiple result sets. A function returns a value or table, can be used in queries, but cannot change data.

Learn: Views
07How do you write a safe UPDATE or DELETE?

Always include a WHERE clause, test it first as a SELECT, wrap risky changes in a transaction, check @@ROWCOUNT, and use OUTPUT to see what changed. In production, take a backup or use a script reviewed by someone else.

SQL Illustrative
BEGIN TRANSACTION;
UPDATE dbo.Products
SET Price = Price * 1.10
OUTPUT deleted.Price AS OldPrice, inserted.Price AS NewPrice
WHERE CategoryId = 3;
-- check the result, then
COMMIT;
Learn: UPDATE
08Subquery vs JOIN — which should you use?

Use a JOIN when you need columns from both tables. Use EXISTS or IN subqueries to filter by the existence of related rows. The optimiser often produces the same plan; choose the one that expresses the intent clearly.

Learn: Subqueries
09What is a user-defined function, and when does it hurt performance?

A scalar or table-valued function written in T-SQL. Inline table-valued functions are expanded like views and perform well. Multi-statement and older scalar functions run row by row and can hide expensive work.

Learn: User-Defined Functions
10What does a transaction guarantee?

Atomicity: all statements commit or all roll back. Use BEGIN TRAN, COMMIT and ROLLBACK with TRY…CATCH and SET XACT_ABORT ON so any error rolls back cleanly. Keep transactions short to avoid blocking.

Learn: Transactions
11Which constraints keep data valid?

PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK (Price >= 0), DEFAULT and NOT NULL. Constraints are enforced for every application that writes to the table, unlike validation in one app.

Learn: Constraints
12Natural keys vs surrogate keys?

A natural key comes from the data (email, ISBN); a surrogate key is generated (INT IDENTITY or GUID). Surrogates are stable and compact, so they usually make the primary key, with a UNIQUE constraint on the natural key.

Learn: Primary and Foreign Keys

Experienced questions (7)

01Explain transaction isolation levels.

READ UNCOMMITTED allows dirty reads; READ COMMITTED (default) prevents them; REPEATABLE READ prevents non-repeatable reads; SERIALIZABLE prevents phantoms; SNAPSHOT uses row versioning so readers don’t block writers.

Learn: Transactions
02How do you tune a slow query?

Read the actual execution plan, look for scans on large tables, key lookups, implicit conversions and bad estimates; add or adjust indexes, make predicates SARGable, update statistics and avoid functions on indexed columns in WHERE.

Learn: Query Optimization
03Why can triggers be problematic?

They run hidden logic on every insert/update/delete, can cascade, make debugging harder and hurt bulk performance. Prefer explicit logic in procedures or the application unless auditing truly requires triggers.

Learn: Triggers
04How do you read an execution plan?

Read right to left. Look for scans where seeks are expected, key lookups, large differences between estimated and actual rows, expensive sorts, spills to tempdb and warnings. Compare logical reads with SET STATISTICS IO ON.

Learn: Execution Plans
05What is parameter sniffing?

SQL Server compiles a plan using the first parameter values it sees and reuses it. If those values were unusual, the cached plan can be terrible for others. Fixes include OPTION (RECOMPILE), OPTIMIZE FOR, better indexes or Query Store plan forcing.

Learn: Query Optimization
06How do you secure a SQL Server database used by an app?

Give the app a dedicated login with least privilege (often only EXECUTE on procedures or specific schemas), never use sa, parameterise all queries, encrypt connections, use Always Encrypted or TDE for sensitive data and audit access.

Learn: SQL Security
07What are window function frames?

ROWS or RANGE BETWEEN … defines which rows a window aggregate sees. SUM(Amount) OVER (ORDER BY OrderDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) is a running total; ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is a 7-row moving sum.

Learn: Window Functions
Progress is saved in this browser. Sign in to sync.