SQL Server Interview Questions and Answers
Basic Level
1. What is SQL Server?
Microsoft SQL Server is a Relational Database Management System (RDBMS) developed by Microsoft. It's designed to store, retrieve, and manage data in a relational database format, using Structured Query Language (SQL). Applications and tools interact with SQL Server to access and modify data, using Transact-SQL (T-SQL), which is Microsoft's version of SQL.
2. What is a table?
A table is a structured container for storing data. It organizes data into rows (records) and columns (fields), much like a spreadsheet. Each row represents a unique piece of information, and each column holds a specific attribute or piece of data about that information. Tables are fundamental to relational databases, allowing you to store and manage data in a well-organized and efficient manner. .
3. What is a primary key?
A column (or set of columns) that uniquely identifies each row in a table.
4. What is a foreign key?
A column that creates a relationship between two tables.
5. What is normalization?
Normalization is the process of organizing data in a database. It includes creating tables and establishing relationships between those tables according to rules designed both to protect the data and to make the database more flexible by eliminating redundancy and inconsistent dependency.
6. What is denormalization?
Denormalization, on the other hand, is the process of combining tables to reduce the complexity of database queries. This can introduce redundancy but may lead to improved performance by reducing the number of joins required..
7. What is a clustered index?
Clustered indexes sort and store the data rows in the table or view based on their key values. These key values are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be stored in only one order.
8. What is a non-clustered index?
A non-clustered index in SQL is an index structure that is separate from the actual data table. It stores a copy of the indexed columns and a pointer to the data row where the actual data is located. This allows for multiple non-clustered indexes on a single table, unlike clustered indexes which can only have one per table.
9. What is a view?

In SQL, a view is a virtual table based on the result-set of an SQL statement. It's like a table in that it has rows and columns, but it doesn't store any data itself. Instead, it acts like a filter on one or more underlying tables, presenting data as if it were a single table.

Here's a more detailed breakdown:
  • Virtual Table: A view doesn't physically store data; it's a stored query.
  • Based on a Query: The data in a view is derived from the results of a SELECT statement that defines the view.
  • Like a Table: You can query, insert, update, and delete data through a view as if it were a regular table.
  • Security and Simplification: Views can be used for security purposes by limiting user access to specific data subsets. They can also simplify complex queries by combining multiple tables into a single, user-friendly view.
  • Dynamic Updates: Changes to the underlying tables are reflected in the view's data.
10. What is a stored procedure?
A SQL stored procedure is a pre-compiled group of SQL statements that are stored in a database and can be executed as a single unit. It allows for reusability, modularity, and improved security. Stored procedures can accept input parameters and return multiple output values, making them versatile for various database operations..
Intermediate Level
11. What is a trigger?

In SQL Server, a trigger is a special type of stored procedure that automatically executes when a specific event occurs within the database. These events are typically data manipulation language (DML) operations like INSERT, UPDATE, or DELETE on a table. Triggers help automate tasks, enforce data integrity, and maintain accurate records of database activities.

Elaboration
  • Purpose: Triggers are designed to respond to specific events within the database, allowing you to automatically execute code in reaction to those events.
  • DML Triggers: These are the most common type of trigger and are associated with tables or views. They fire when a DML operation is performed on that table or view.
  • Event-Driven: Triggers are event-driven, meaning they are activated by a specific event occurring in the database.
  • Data Integrity and Business Rules: Triggers can be used to enforce business rules and data integrity by automatically executing code that validates or modifies data during an INSERT, UPDATE, or DELETE operation.
Examples
  • Automatically updating an audit log table whenever data is modified in another table.
  • Preventing invalid data from being inserted into a table by checking constraints within the trigger.
  • Triggering a notification when a specific event occurs, such as a large number of orders being placed.
.
12. Difference between DELETE and TRUNCATE?

In SQL Server, DELETE and TRUNCATE are both used to remove data from a table, but they differ in their approach and impact. DELETE removes rows based on specified conditions and logs each deleted row, allowing for rollback within a transaction. TRUNCATE removes all rows from a table faster by deallocating data pages, doesn't log individual deletions, and is typically not rollbackable.

Key Differences
Deletion Method
  • DELETE: Removes individual rows based on a WHERE clause condition. Logs each deleted row, allowing for rollbacks within a transaction.
  • TRUNCATE: Removes all rows in the table by deallocating the data pages. It does not log individual row deletions and is not typically rollbackable.
Logging
  • DELETE: Logs each deleted row, consuming more transaction log space.
  • TRUNCATE: Logs only the page deallocation, using less transaction log space.
Speed
  • DELETE: Slower due to row-by-row deletion and transaction logging.
  • TRUNCATE: Faster as it deallocates the entire table's data pages in one operation.
Rollback
  • DELETE: Can be rolled back within a transaction.
  • TRUNCATE: Typically not rollbackable.
Triggers
  • DELETE: Triggers defined on the table are fired for each deleted row.
  • TRUNCATE: Triggers are not fired.
Constraints
  • DELETE: Respects constraints (e.g., foreign keys) during deletion.
  • TRUNCATE: Bypasses constraints, making it faster.
Use Cases
  • DELETE: Used for removing specific rows or subsets of data based on conditions.
  • TRUNCATE: Used for resetting a table to an empty state or for quickly removing all data when rollback is not needed.
Summary

DELETE is more flexible for removing specific rows, while TRUNCATE is faster for removing all rows when rollback is not a concern.

13. What are the types of joins?

In SQL Server, there are several types of joins, each designed to combine data from two or more tables based on a specific relationship. The main types are: Inner Join, Left Outer Join, Right Outer Join, Full Outer Join, and Cross Join. Additionally, Self Join, while not a distinct join type, can be implemented using any of the joins mentioned above.

Join Types Breakdown

Inner Join

Returns only the rows where the join condition is met in both tables.

Left Outer Join (or Left Join)

Returns all rows from the left table and the matching rows from the right table. If a match isn't found, NULL values are returned for the right table columns.

Right Outer Join (or Right Join)

Returns all rows from the right table and the matching rows from the left table. If a match isn't found, NULL values are returned for the left table columns.

Full Outer Join (or Full Join)

Returns all rows from both tables. If a match is found, the matching values are returned; otherwise, NULL values are used for the missing columns.

Cross Join

Returns the Cartesian product of the two tables, meaning all possible combinations of rows from both tables.

Self Join

Joins a table to itself. This is useful for comparing rows within the same table. A Self Join can be implemented using Inner Join, Outer Join, or Cross Join depending on the specific requirements.

14. What is the difference between WHERE and HAVING?

In SQL Server, WHERE and HAVING are both used for filtering data, but they apply to different stages of the query process. WHERE filters rows before any grouping or aggregation, while HAVING filters grouped data after aggregation. In essence, WHERE works on individual rows, and HAVING works on groups of rows.

Detailed Breakdown
WHERE Clause
  • Filters rows based on conditions that apply to individual rows in the table.
  • Applies before the GROUP BY clause.
  • Used with standard operators and comparisons.
  • Examples:
    • WHERE salary > 50000
    • WHERE department = 'IT'
HAVING Clause
  • Filters groups of rows based on conditions that apply to aggregated values (e.g., SUM(), AVG(), COUNT()).
  • Applies after the GROUP BY clause.
  • Must be used with aggregate functions.
  • Examples:
    • HAVING AVG(salary) > 60000
    • HAVING COUNT(*) > 5
In Simpler Terms
  • Think of WHERE as filtering the data before you group it.
  • Think of HAVING as filtering the groups after they are created.
  • If you want to filter rows based on individual column values, use WHERE.
  • If you want to filter groups based on aggregate values of those groups, use HAVING.
15. What is indexing?

In SQL Server, indexing refers to creating special lookup tables that speed up data retrieval operations. These indexes act like a table of contents, allowing the database server to quickly locate data within a table without scanning every row. By using indexes, you can significantly improve query performance, especially for tables with large amounts of data.

Key Concepts
Purpose

Indexes help the database engine quickly find the specific rows that match a query's criteria.

Speed

Without indexes, the database would have to scan every row in a table to find the data you're looking for, which can be slow for large tables.

Structure

Indexes are typically implemented as B-tree structures, which are efficient data structures for searching.

Columns

Indexes are usually created on columns that are frequently used in WHERE clauses or JOIN conditions in queries.

Types

SQL Server supports various index types, including:

  • Clustered Indexes
  • Nonclustered Indexes

How It Works
  1. Data Organization: An index stores a sorted representation of the indexed columns, along with pointers to the actual data rows in the table.
  2. Efficient Search: When a query uses a column that is indexed, the database engine can use the index to quickly find the rows that match the query’s criteria.
  3. Reduced Full Table Scans: Indexes help avoid scanning the entire table, saving time and system resources.
Benefits of Using Indexes
  • Faster Query Performance: Significantly reduces the time it takes to retrieve data.
  • Improved Application Responsiveness: Faster queries lead to a better user experience.
  • Reduced Disk I/O: Less data needs to be read from disk when using indexes.
Considerations
Over-Indexing

Adding too many indexes can slow down INSERT, UPDATE, and DELETE operations and consume extra storage.

Maintenance

Indexes need to be maintained. They can become fragmented or outdated if the underlying data changes frequently, which may require regular rebuilding or reorganizing.

16. What is a CTE (Common Table Expression)?
A temporary result set used within a query.
17. What is a temp table?
A temporary table used to store data temporarily.
18. Difference between temp table and table variable?
#TempTable supports indexes and transactions. TableVariable is stored in memory, faster for small data.
19. Difference between UNION and UNION ALL?
UNION removes duplicates. UNION ALL keeps duplicates.
20. What is a transaction?
A sequence of operations performed as a single logical unit.
21. What are ACID properties?
Atomicity, Consistency, Isolation, Durability
22. What is SQL Profiler?
A tool to monitor SQL Server events.
23. Difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?
ROW_NUMBER(): Unique values
RANK(): Gaps in ranking
DENSE_RANK(): No gaps
24. What is a schema in SQL Server?
A container that holds database objects like tables and views.
25. What are constraints in SQL Server?
NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT
Advanced Level
26. What is an execution plan?
A visual representation of how SQL Server executes a query.
27. How do you optimize a SQL query?
Use indexes, avoid SELECT *, use joins appropriately, review execution plans.
28. What is partitioning in SQL Server?
Dividing large tables into smaller, manageable pieces.
29. How can deadlocks be avoided?
Access objects in the same order, keep transactions short, use appropriate isolation levels.
30. What are isolation levels?
Read Uncommitted, Read Committed, Repeatable Read, Serializable, Snapshot
31. What is a correlated subquery?
A subquery that depends on the outer query.
32. What are the system databases in SQL Server?
master, model, msdb, tempdb, resource
33. How to handle errors in SQL Server?
Use TRY...CATCH blocks.
34. Difference between CHAR and VARCHAR?
CHAR: Fixed length, VARCHAR: Variable length
35. What are DBCC commands?
Database Console Commands used for maintenance and validation.
36. What is log shipping?
A disaster recovery method by shipping logs to a secondary server.
37. What is replication in SQL Server?
Copying and distributing data across servers.
38. Difference between synchronous and asynchronous replication?
Synchronous: Waits for commit. Asynchronous: Doesn’t wait.
39. What is Always On availability groups?
A high availability feature for database failover.
40. What is the use of WITH(NOLOCK)?
Reads data without locking, allowing dirty reads.

🔹 Miscellaneous / Scenario-Based

41. How do you improve the performance of a slow-running query?
Use indexing, check execution plans, optimize joins and subqueries.
42. How do you migrate a database to a new server?
Backup/Restore, Detach/Attach, or use SSMS export tools.
43. What is SQL Server Agent?
A tool to schedule jobs and automate tasks.
44. What are Linked Servers?
Allow queries to be run on external databases.
45. How to schedule a job in SQL Server?
Use SQL Server Agent jobs and define steps/triggers.
46. How to find the size of a database?
sp_helpdb 'DatabaseName'
47. How to kill a running query in SQL Server?
KILL <SPID>
48. How to list all active connections in SQL Server?
sp_who2
49. What is tempdb used for?
Stores temporary tables, variables, and intermediate query results.
50. How do you find and fix blocking issues?
Use sp_who2, sys.dm_exec_requests, and review lock chains.