Open In App

SQL Server Interview Questions

Last Updated : 16 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Data is growing every day, and it plays a big part in making important decisions. To manage this data, we need reliable databases, and SQL Server is one of the most popular options out there. Learning SQL Server can lead to exciting careers as an SQL Specialist or SQL Developer. If you’re preparing for an SQL Server interview, then it is very important to know the common questions you might face during the SQL Server interviews. In this blog, we’ll go over some of the most frequently asked SQL Server interview questions to help you feel confident. Let’s dive in!

This interview preparation guide cover everything from SQL Server basics to complex query-based problems, this article will help you gain the confidence and knowledge needed to succeed.

Beginner SQL Server Interview Questions

Understanding the fundamentals is crucial. SQL Server basics include core concepts such as architecture, databases, and normalization, which often appear in initial interview rounds.

1. What is SQL Server?

SQL Server is a relational database management system (RDBMS) developed by Microsoft, designed for enterprise-level applications. It manages data efficiently, from storage to retrieval, and supports a wide range of data types, ensuring high availability, security, and performance.

2. Explain the Difference Between SQL and T-SQL.

Basis of Comparison

SQL

T-SQL

Stands For

Structured Query Language

Transact - SQL

Definition

Used for querying and manipulating data stored in a database.

It's an extension of SQL that is primarily used in Microsoft SQL Server databases and software.

Feature

SQL is open-source.

T-SQL is developed and owned by Microsoft.

Functions

Basic functions provided by SQL standards

Additional functions provided by Microsoft SQL Server

Triggers

Supported, but specifics may vary between database systems

Supported, with specific syntax and features in Microsoft SQL Server

Error Handling

Basic error handling capabilities provided by SQL standards

Enhanced error handling features available in T-SQL

3. What are the Different Data Types Used in SQL Server?

In SQL Server, there are several data types used to define the type of data that can be stored in a column. Here are some of the commonly used data types:

  • Numeric Data Types: INT, BIGINT, DECIMAL, NUMERIC, FLOAT, REAL
  • Character Data Types: CHAR, VARCHAR, TEXT
  • Date and Time Data Types: DATE, TIME, DATETIME, DATETIME2, SMALLDATETIME, TIMESTAMP
  • Binary Data Types: BINARY, VARBINARY, IMAGE
  • Boolean Data Type: BIT
  • Other Data Types: XML, JSON, HIERARCHYID, UNIQUEIDENTIFIER

4. How to Create a Table in SQL Server?

To create a table in SQL Server, you can use the CREATE TABLE statement followed by the table name and a list of column definitions.

CREATE TABLE TableName (
Column1 DataType1 [Constraint],
Column2 DataType2 [Constraint],
...
ColumnN DataTypeN [Constraint]
);

In addition, we can directly create the table using SQL Server Management Studio (SSMS).

5. What is the Purpose of an Alias in a Query?

In SQL Server, an alias is used to provide a temporary name for columns or tables to make queries easier to read, especially when they are complex. Aliases are often used in JOIN operations or when selecting calculated fields. Example:

SELECT first_name AS "First Name", last_name AS "Last Name"
FROM employees AS e

The primary purposes of using aliases in a query are:

  • Improved Readability: Aliases can make queries easier to read and understand.
  • Avoiding Ambiguity: When a query involves multiple tables with columns having the same name, using aliases can help avoid ambiguity.
  • Shortening Column Names: Alias allows us to give a shorter, more concise name for a column in the query result.

6. What is the Difference Between INNER JOIN and LEFT JOIN?

In SQL Server, INNER JOIN and LEFT JOIN are both types of join operations used to retrieve data from multiple tables based on a specified condition.

Inner-Join-vs-left-Join

INNER JOIN

  • An INNER JOIN returns only the rows where there is a match between the columns in both tables.
  • It only returns rows where there is a match in both tables based on the specified join condition.

LEFT JOIN

  • A LEFT JOIN returns all the rows from the left table, along with matching rows from the right table.
  • If there is no matching row in the right table, NULL values will be returned for the columns from the right table.

Example:

SELECT e.EmployeeName, d.DepartmentName
FROM Employees e
LEFT JOIN Departments d ON e.DepartmentID = d.DepartmentID;

7. How to Insert, Update, and Delete Data From a Table?

Insert Data

To insert data into a table, you use the INSERT INTO statement

INSERT INTO table_name (column1, column2,...) 
VALUES (value1, value2,...);

Update Data

To update existing data in a table, you use the UPDATE statement

UPDATE TableName
SET Column1 = NewValue1, Column2 = NewValue2
WHERE Condition; -- Always use WHERE to avoid updating all rows

Delete Data

To delete data from a table, you use the DELETE FROM statement

DELETE FROM TableName
WHERE Condition;

8. How to Grant Permissions to a User?

In SQL Server, you can grant permissions to a user using the GRANT statement. Permissions can be granted at various levels such as database level, schema level, table level, and even specific stored procedures or functions.

GRANT permission_type 
ON [target]
TO user_name;

we can also grant permission using SQL Server Management Studio.

9. How to Create a Stored Procedure?

To create a stored procedure in SQL Server, we can use the CREATE PROCEDURE statement followed by the procedure name and its definition.

CREATE PROCEDURE procedure_name
@parameter1 data_type,
@parameter2 data_type,
...
AS
BEGIN
-- SQL statements
END;

10. What are the Basic Aggregate Functions?

In SQL Server, aggregate functions are used to perform a calculation on a set of values and return a single value. Here are some of the basic aggregate functions:

  1. COUNT(): This function counts the number of rows in a result set or the number of non-null values in a column.
  2. MAX(): This function returns highest value in a column.
  3. MIN(): This function returns lowest value in a column.
  4. SUM(): This function returns the sum of all values in a numeric column.
  5. AVG(): This function calculates the average value of a numeric column.

11. How to Use the LIKE Operator for Pattern Matching?

In SQL Server, the LIKE operator is used for pattern matching in string values. It allows you to search for strings that match a specified pattern, which may include wildcard characters.

SELECT column1, column2, ...
FROM table_name
WHERE column_name LIKE pattern;

12. What is the Difference Between a Scalar Function and a Table-Valued Function?

Scalar Function

  • A scalar function is a user-defined function that returns a single scalar value (such as integer, string, or date) based on the input parameters.
  • It operates on a single row of data at a time and returns a single value.
  • They can be built-in, such as GETDATE(), LEN() or UPPER() or user-defined.

Table-valued Functions

  • A table-valued function is a user-defined function that returns a table as its output.
  • It operates on a set of input parameters and can return multiple rows of data.

13. Explain the Basic Concept of User-Defined Functions (UDFs).

  • User-defined functions (UDFs) are procedures that accept arguments, do complicated procedures, and then return the result-set or the value.
  • UDFs, three types of them, are user-defined scalar functions, table-valued functions and system functions.

We can use UDFs for the following reasons:

  1. They can be created, stored, and called at any number of times.
  2. They allow faster execution because UDFs don’t need to be reparsed or reoptimized.
  3. They minimize network traffic as it reduces the number of rows sent to the client.

14. How to Check the Execution Plan of a Query?

  1. On the toolbar, select Database Engine Query. we can also open an existing query and display the estimated execution plan by selecting the Open File toolbar button and locating the existing query.
  2. Enter the query for which we would like to display the estimated execution plan.
  3. On the Query menu, select Display Estimated Execution Plan or select the Display Estimated Execution Plan toolbar button. The estimated execution plan is displayed on the Execution Plan tab in the results pane.
ExecutionPlan
Display Estimated Execution

15. Explain the Difference Between Clustered and Non-Clustered Indexes.

Feature

Clustered Index

Non - Clustered Index

Definition

It describes the order in which data is stored in tables physically.

It doesn’t sort tables physically inside a table but creates a logical order for stored data.

Key Structure

Contains the actual data rows.

Contains only pointers to the data rows

Index Key Columns

Each table will have only one clustered index.

There could be many non-clustered indexes for a table.

Data Accessing

Fast

Slow

16. When would We Create an Index?

We would typically create an index to improve the performance of queries that frequently search or filter data based on certain columns.

  • Frequent Searches: Creating an index on columns used for filtering data can greatly improve query performance. It helps SQL Server quickly find the relevant rows needed for the query.
  • Join Columns: Creating indexes on columns used for joining tables can speed up the join operation. It helps SQL Server efficiently locate matching rows, improving performance.
  • Query Optimization: The SQL Server query optimizer uses indexes to determine the best way to execute a query. Building indexes helps the optimizer choose the most effective execution plan for our queries, improving performance.
  • Aggregation: Aggregate functions (SUM, AVG, and COUNT) are optimized when applied on indexed columns.

Intermediate SQL Server Interview Questions

This section delves into commonly encountered interview questions for intermediate users. Test your knowledge on topics like joins, functions, and performance optimization to impress your interviewer.

17. How to Determine If an Index is Effective?

  • Execution Plans: Analyze the execution plans of queries that use the index. Look for Index Seek operations instead of Index Scan operations. Seek operations indicate that the index is effectively narrowing down the rows being retrieved.
  • Query Performance: Measure the query execution time with and without the index. If the query performs significantly better with the index, it indicates that the index is effective.
  • Index Usage Statistics: SQL Server maintains statistics about index usage. You can query dynamic management views like sys.dm_db_index_usage_stats to see how frequently an index is being used. If an index is rarely or never used, it might not be effective and could potentially be dropped.
  • Index Design: Evaluate the design of the index itself. Consider factors such as the columns included in the index, their data types, and the order of columns.

18. Can We Write a Query to find Unused Indexes?

We can find unused indexes by querying the dynamic management views (DMVs) provided by SQL Server. Here's a query to find unused indexes:

SELECT
OBJECT_NAME(s.[object_id]) AS TableName,
i.name AS IndexName,
i.type_desc AS IndexType,
s.user_seeks,
s.user_scans,
s.user_lookups,
s.user_updates
FROM
sys.dm_db_index_usage_stats AS s
INNER JOIN
sys.indexes AS i ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id
WHERE
OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
AND s.database_id = DB_ID()
AND (s.user_seeks + s.user_scans + s.user_lookups) = 0
ORDER BY
TableName,
IndexName;

This query retrieves information about indexes along with their usage statistics. Unused indexes will have NULL values for user seeks, scans, and lookups but non-NULL values for user updates.

19. What are the Benefits of using Views in SQL Server?

  • Simplicity and Abstraction: Views provide a way to abstract complex SQL queries into a single, easy-to-use object.
  • Data Security: Views can be used to restrict access to certain columns or rows of a table. By granting users access to views rather than the underlying tables, you can implement security policies to control what data users can see.
  • Performance Optimization: Views can help optimize query performance by precomputing joins, aggregations, or complex calculations.
  • Simplified Data Access: Views can simplify data access by combining data from multiple tables into a single virtual table. This can eliminate the need for complex joins in application code, making queries more straightforward and easier to manage.

20. How to Create a View with Joins and Aggregates?

Here we have created a view named loss_summary_view with columns week, from_code, to_code, count_a, sum_x, sum_y, and sum_z. The view is constructed by selecting data from tables history and calendar and performing joins and aggregate functions.

CREATE VIEW loss_summary_view (week, from_code, to_code, count_a, sum_x, sum_y, sum_z)
AS
SELECT c.week, h.from_code, h.to_code, COUNT(h.a) AS count_a, SUM(h.x) AS sum_x, SUM(h.y) AS sum_y, SUM(h.z) AS sum_z
FROM history AS h
JOIN calendar AS c ON c.month = 100610 AND c.day = h.day
GROUP BY c.week, h.from_code, h.to_code;

21. How to Update Data through a View?

Create a view showing customers from Paris using the WITH CHECK OPTION statement.

CREATE VIEW vwCustomersParis
AS
SELECT CompanyName, ContactName, Phone, City
FROM Customers
WHERE City = 'Paris'
WITH CHECK OPTION

Update the above created view by moving everyone from Paris to Lyons.

UPDATE vwCustomersParis
SET City = 'Lyons'

The above statement update data by moving everyone from Paris to Lyons will fail because Lyons does not meet the criteria defined in the view.

22. Explain the Security Implications of using Views.

  • Data Restriction: Views can restrict access to sensitive data by exposing only specific columns or rows from underlying tables. This allows administrators to control who can see what data, enhancing overall data security.
  • Access Control: By granting permissions on views rather than underlying tables, administrators can implement fine-grained access control. This means users can be given access to specific views without needing direct access to the underlying tables, reducing the risk of unauthorized data access.
  • Data Masking: Views can be used to apply data masking techniques, such as replacing sensitive data with masked values or aggregating data to provide a summarized view while protecting underlying details. This helps prevent unauthorized users from accessing sensitive information.

23. How to Identify Performance Bottlenecks in a Query?

  • To identify performance bottlenecks, start by monitoring our queries for execution time, resource consumption, and query plan.
  • Tools like SQL Server Profiler can help capture and analyze query metrics, highlighting queries that are slow, resource-intensive, or have suboptimal plans.
  • Use SQL Server Management Studio (SSMS) or another database management tool to execute the query and view its execution plan. Look for areas with high estimated or actual costs, such as table scans, index scans, key lookups, or sorts.

24. What are some Techniques for Query Optimization?

  • Query Execution Plans: The query execution plan in SQL Server details how a query is executed. It shows which tables are accessed, how they are accessed, how they are joined, and any other operations performed.
  • Statistics: Regularly update statistics to ensure the query optimizer has accurate information for generating efficient execution plans. Use the UPDATE STATISTICS command or enable auto-update statistics.
  • Query Rewriting: Rewrite queries to use more efficient syntax or to optimize joins, filters, and subqueries. Simplify complex queries to improve performance.
  • Avoid Cursors: Avoid using cursors whenever possible, as they can lead to poor performance. Instead, use set-based operations like SELECT, INSERT, UPDATE, and DELETE to manipulate data.

25. Explain the Role of Statistics in Query Optimization.

  • Query Plan Generation: When SQL Server receives a query, the query optimizer evaluates various execution plans to determine the most efficient way to retrieve the required data. Statistics provide the optimizer with estimates of the number of rows and data distribution, helping it choose the optimal plan.
  • Index Selection: Statistics help the optimizer decide whether to use indexes or perform a table scan.
  • Join Order and Join Type Selection: Statistics provide information about the size and selectivity of tables involved in join operations.

26. How can we Use Partitioning to Improve Performance?

  • For very large databases and tables, such as one with 27 billion rows, table partitioning can significantly improve query performance. By partitioning a table, queries can be applied to only the relevant partitions, making them more efficient and faster.
  • Partitioning simplifies data management by logically dividing large tables or indexes into smaller, more manageable partitions. This can lead to faster data loads, deletes, and index rebuilds, as operations are performed on smaller subsets of data.
  • Partitioning can increase parallelism by allowing SQL Server to process multiple partitions concurrently. This can lead to faster query execution times, especially for CPU-bound queries that can benefit from parallel processing.

27. Describe Different Authentication Modes in SQL Server.

In SQL Server, there are two different kinds of authentication modes:

  • Windows Authentication Mode: In Windows Authentication mode, SQL Server uses the Windows username for authentication, and the SQL Server username and password boxes are disabled. Authentication is based on Windows credentials rather than SQL Server credentials.
  • Mixed Mode: SQL Server supports both Windows and SQL Server authentication modes. we can require a username and password for authentication, allowing users to connect through either Windows authentication or SQL Server authentication. Administrators can maintain user accounts in SQL Server.

28. How can we Implement Role-Based Access Control (RBAC) in SQL Server?

1. Identify Roles: Determine the roles needed for our application or system.

2. Create Database Roles: Use the CREATE ROLE statement to create database roles that correspond to the identified roles.

CREATE ROLE SalesRole;
CREATE ROLE HRRole;

3. Assign Permissions to Roles: Grant appropriate permissions to each role using the GRANT statement.

GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.SalesTable TO SalesRole;
GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.EmployeeTable TO HRRole;

4. Assign Users to Roles: Add users to the appropriate roles using the ALTER ROLE statement or the sp_addrolemember stored procedure.

ALTER ROLE SalesRole ADD MEMBER SalesUser;
EXEC sp_addrolemember 'HRRole', 'HRUser';

5. Use Role-Based Security: Modify our application or system to utilize role-based security. Instead of directly granting permissions to users, check their roles and grant permissions based on their roles.

IF USER_IN_ROLE('SalesRole')
BEGIN
-- Allow access to sales-related functionality
END
ELSE IF USER_IN_ROLE('HRRole')
BEGIN
-- Allow access to HR-related functionality
END

29. What are Stored Procedures and How can they Improve Security?

Stored procedures in SQL Server are precompiled sets of SQL statements that can be reused.

Storedprocedure

Stored procedures can improve security in several ways:

  • Access Control: Granting permissions to execute stored procedures instead of directly on tables controls data access tightly.
  • Parameterized Queries: Stored procedures accept parameters, preventing SQL injection attacks.
  • Transaction Management: They manage transactions, ensuring data integrity by grouping SQL statements into atomic operations.

30. Explain Different Types of Replication in SQL Server.

In SQL Server, three different types of replications are available:

  • Snapshot replication: Snapshot replication is ideal for replicating data that changes infrequently and is easy to maintain. For example, it can be used to distribute lists that are updated once per day from a main server to branch servers.
  • Transactional replication: Transactional replication is a method of data distribution from a publisher to a subscriber. It is suitable for scenarios where data changes frequently.
  • Merge replication: Merge replication consolidates data from various sources into a single centralized database. It is used when central and branch databases need to update information simultaneously.

31. When would we use Transactional Replication Versus Merge Replication?

Transactional Replication:

  • For near real-time data distribution from a publisher to subscribers.
  • One-way replication with minimal latency.

Merge Replication:

  • For bidirectional synchronization of frequently changing data.
  • Suitable for scenarios with disconnected or mobile clients.

Advanced SQL Server Interview Questions

Elevate your interview preparation by deep diving into advanced SQL Server interview question section. Be ready to showcase your expertise with complex queries, performance optimization strategies, and intricate server administration tasks.

32. How do we Configure and Manage Replication in SQL Server?

Configuring and managing replication in SQL Server involves several steps. Here's a general overview:

  1. Identify Publisher and Distributor.
  2. Choose replication type: Snapshot, Transactional, or Merge.
  3. Set up publication to specify data to replicate.
  4. Define subscriptions for where replicated data will be delivered.
  5. Monitor replication status and performance using SSMS or Replication Monitor.
  6. Handle maintenance tasks such as index maintenance and backup/restoration.

33. Explain Different High Availability Solutions in SQL Server (e.g., Always On Availability Groups).

Always On Availability Groups:

  • Provides data protection and availability.
  • Allows multiple readable secondary replicas.
  • Supports automatic failover.

Failover Clustering:

  • Offers high availability at the instance level.
  • Uses shared storage and multiple servers for failover.

Database Mirroring:

  • Provides high availability at the database level.
  • Being deprecated in favor of Always On Availability Groups.

Log Shipping:

  • Copies transaction log backups to secondary databases.
  • Supports manual failover.

Replication:

  • Replicates data from one database to another.
  • Supports data distribution and scalability but not automatic failover.

34. How to Configure And Manage Always On Availability Groups?

Configuring and managing Always On Availability Groups (AGs) in SQL Server involves several steps. Here's a general guide:

  • Preparation
  • Enable Always On Availability Groups
  • Create an Availability Group
  • Add Databases to the Availability Group
  • Configure Availability Group Replicas
  • Join Secondary Replicas
  • Configure Listener
  • Test Failover
  • Monitor Availability Groups
  • Maintenance and Troubleshooting

Always On Availability Groups provide high availability and disaster recovery solutions for SQL Server databases.

35. What are the Considerations For Disaster Recovery in SQL Server?

  • Implement regular backups and store them offsite.
  • Use high availability solutions like Always On Availability Groups or Failover Clustering.
  • Set up database mirroring or log shipping for standby servers.
  • Plan for point-in-time recovery with transaction log backups.
  • Develop and test a comprehensive disaster recovery plan.
  • Monitor systems for early detection of issues.
  • Ensure security and compliance in disaster recovery plans.
  • Document procedures and key contacts for quick response.

36. Can we Write a Script to Import Data from a Flat File into a Table in SQL Server?

Yes, we can write a script to import data from a flat file into a table in SQL Server. Here's an example script using the BULK INSERT statement:

BULK INSERT TableName
FROM 'C:\Path\To\Your\File.csv'
WITH
(
FIELDTERMINATOR = ',', -- Specify the field terminator
ROWTERMINATOR = '\n', -- Specify the row terminator
FIRSTROW = 2 -- Specify the first row to start importing data
);

In this script, replace TableName with the name of your SQL Server table and 'C:\Path\To\Your\File.csv' with the path to your flat file. Adjust FIELDTERMINATOR and ROWTERMINATOR as per your file format.

37. Explain how to Loop through a Result Set using Cursors in SQL Server.

To loop through a result set using cursors in SQL Server, you can follow these steps:

  • Declare Cursor: Declare a cursor and specify the SELECT statement that defines the result set.
  • Open Cursor: Open the cursor to start fetching rows from the result set.
  • Fetch Rows: Use a loop to fetch rows one by one from the cursor.
  • Process Rows: Inside the loop, process each fetched row as needed.
  • Close Cursor: After looping through the result set, close the cursor to release resources.
  • Deallocate Cursor: Optionally, deallocate the cursor to free memory resources.

38. How can we use Error Handling in T-SQL scripts?

In T-SQL scripts, error handling can be implemented using the TRY...CATCH construct.

BEGIN TRY
-- T-SQL statements that might raise an error
-- For example:
SELECT 1/0; -- This will raise a divide by zero error
END TRY
BEGIN CATCH
-- Catch block to handle the error
-- we can capture information about the error using functions like ERROR_NUMBER(), ERROR_MESSAGE(), etc.
PRINT 'An error occurred: ' + ERROR_MESSAGE(); -- Print the error message
-- Additional error handling logic can be implemented here
END CATCH;

Functions like ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_STATE(), ERROR_SEVERITY(), and ERROR_PROCEDURE() can be used to retrieve information about the error.

39. Explain the Basic Components of SSIS packages.

The important component in SSIS package are:

  • Data flow: The Data Flow is a key part of an SSIS package that moves and changes data from one place to another. It has three main parts: Source, Transformation, and Destination.
  • Control flow: The Control Flow is where we define the order and execution of tasks in an SSIS package. It includes tasks like SQL and script execution, looping, conditional execution, and managing workloads.
  • Package Explorer: The Package Explorer in SSIS helps developers navigate and manage package components. It shows a hierarchy of the package, including control flow tasks, data flow components, connection managers, variables, and event handlers.
  • Event handler: An Event Handler in SSIS lets a package react to certain events as it runs. These events can be errors, warnings, task completion, package start, package end, and more. Event Handlers are useful for custom error handling, logging, notifications, or other actions based on specific events during package execution.
SQL-Server-Interview-Questions
SQL Server Interview Questions

Query Based SQL Server Interview Questions

For our better understanding, we will considering the following tables to write queries.

Employee Table:

Employee-Table
Employee Table

Departments Table:

Departments-Table
Departments Table

Sales Table:

SALES-TABLE
Sales Table

Order Table:

OrderTable
Order Table

40. Write a SQL Query to Find the nth Highest Salary from an Employee Table.

SELECT DISTINCT TOP 1 Salary AS NthHighestSalary
FROM (
SELECT TOP 1 Salary
FROM Employees
ORDER BY Salary DESC
) AS NthHighestSalaries
ORDER BY Salary ASC;

Output:

nth-highest-salary
Highest salary

41. Write a SQL Query to Retrieve the Names of Employees who are also Managers.

SELECT e.emp_name 
FROM Employees e
JOIN Employees m ON e.manager_name = m.emp_name;

Output:

retrieve-the-names-of-employees-who-are-also-managers
Output

42. Write a SQL Query to Find the Second Highest Salary from an Employee table.

SELECT MAX(Salary) AS salary 
FROM Employees
WHERE Salary < (SELECT MAX(Salary) FROM Employees);

Output:

second-highest-salary-from-an-Employee-table
Second highest salary

43. Write a Query to Calculate the Total Number of Orders Placed by each Customer.(order table)

SELECT cust_ID, COUNT(*) AS TotalOrders 
FROM Orders
GROUP BY cust_ID;

Output:

OrderPlacedbyEachCustomer
Output

44. Write a Query to Find Employees who have the Same Job Title but Different Salaries.

SELECT e1.emp_id , e1.emp_name, e1.JobTitle, e1.Salary 
FROM Employees e1
JOIN Employees e2 ON e1.JobTitle= e2.JobTitle
WHERE e1.emp_id <> e2.emp_id AND e1.Salary <> e2.Salary
ORDER BY e1.job_title, e1.emp_id;

Output:

find-employees-who-have-the-same-job-title
Output

45. Write a SQL Query to get the Top 5 Highest-Paid Employees.

SELECT TOP 5 * FROM Employees 
ORDER BY Salary DESC;

Output:

top-5-highest-paid-employees
Output

46. Write a Query to Find All Employees who Joined in the Last Month.

SELECT * FROM Employees
WHERE JoinDate>= DATEADD(MONTH, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
AND JoinDate< DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0);

Output:

No employees are there who joined in the last month.

find-all-employees-who-joined-in-the-last-month
Output

47. Write a SQL Query to Find Duplicate Records in a Table.

SELECT emp_name, COUNT(*) AS DuplicateCount 
FROM Employees
GROUP BY emp_name
HAVING COUNT(*) > 1;

Output:

find-duplicate-records-in-a-table
Output

48. Write a Query to Calculate the Average Salary of Employees in Each Department.

SELECT d.dept_name, AVG(e.Salary) AS AvgSalary 
FROM Employees e
JOIN
Departments d ON e.dept_id = d.dept_id
GROUP BY d.dept_name;

Output:

averageSalaryinEachDept
Output

49. Write a SQL Query to Find the Total Number of Products Sold each month.

SELECT 
YEAR,
MONTH,
COUNT(*) AS TotalProductsSold
FROM
Sales
GROUP BY
YEAR,
MONTH
ORDER BY
YEAR,
MONTH;

Output:

TotalProductsSolds
Output

50. Write a SQL Query to Identify Employees who have Duplicate Manager Names.

SELECT e1.emp_ID, e1.emp_name, e1.manager_name FROM Employees e1
JOIN Employees e2 ON e1.manager_name = e2.manager_name
WHERE e1.emp_ID <> e2.emp_ID
AND e1.emp_name <> e2.emp_name
ORDER BY e1.manager_name, e1.emp_ID;

Output:

identify-employees-who-have-duplicate-manager-names
Output

51. Write a Query to Fetch the Names of Employees Along with their Department Names.

SELECT e.emp_name, d.dept_name 
FROM Employees e
JOIN Departments d ON e.dept_ID = d.dept_ID;

Output:

employeeWithDepartmentName
Output


Conclusion

Mastering SQL Server interview questions involves understanding basic concepts, intermediate features, and advanced techniques. Whether it's query-based questions, performance tuning, or scenario-based SQL Server challenges, this guide provides the foundation you need to showcase your SQL Server skills confidently.


Next Article

Similar Reads