0% found this document useful (0 votes)
4 views

SQL Interview Questions

The document provides comprehensive answers to SQL Server interview questions across basic, intermediate, and advanced levels, covering topics such as SQL Server definitions, types of SQL statements, joins, window functions, and data integrity concepts. It includes explanations of key SQL concepts like primary keys, foreign keys, normalization, stored procedures, and various types of joins, along with practical examples. Additionally, it discusses window functions and their applications, including RANK(), LEAD(), and LAG(), as well as performance optimization techniques.

Uploaded by

cryptoboybahadur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

SQL Interview Questions

The document provides comprehensive answers to SQL Server interview questions across basic, intermediate, and advanced levels, covering topics such as SQL Server definitions, types of SQL statements, joins, window functions, and data integrity concepts. It includes explanations of key SQL concepts like primary keys, foreign keys, normalization, stored procedures, and various types of joins, along with practical examples. Additionally, it discusses window functions and their applications, including RANK(), LEAD(), and LAG(), as well as performance optimization techniques.

Uploaded by

cryptoboybahadur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Here are the detailed answers to the provided SQL Server interview questions:

Basic Level

1. What is SQL Server?

SQL Server is a relational database management system (RDBMS) developed by Microsoft. It stores and
manages data in a structured format using tables and provides tools for querying, updating, and managing
data.

Purpose:

 Manage large datasets efficiently.

 Enable secure data storage and access.

 Support various applications like business intelligence and analytics.

2. What are the different types of SQL statements?

 DDL (Data Definition Language): Defines database structures.

o Example: CREATE, ALTER, DROP

 DML (Data Manipulation Language): Manipulates data in tables.

o Example: INSERT, UPDATE, DELETE

 DCL (Data Control Language): Controls user permissions.

o Example: GRANT, REVOKE

 TCL (Transaction Control Language): Manages transactions.

o Example: COMMIT, ROLLBACK, SAVEPOINT

 DQL (Data Query Language): Retrieves data from the database.

o Example: SELECT

3. What is the difference between DELETE and TRUNCATE?

Feature DELETE TRUNCATE

Operation Deletes rows one by one. Removes all rows instantly.

Logging Fully logged. Minimal logging.

Triggers Activates triggers. Does not activate triggers.

Rollback Can be rolled back. Can be rolled back (if in a transaction).

Performance Slower for large datasets. Faster for large datasets.


4. What are the primary key and foreign key?

 Primary Key: Uniquely identifies each record in a table.

 Foreign Key: Enforces referential integrity by linking two tables.

Example:

CREATE TABLE Department (

DeptID INT PRIMARY KEY,

DeptName NVARCHAR(50)

);

CREATE TABLE Employee (

EmpID INT PRIMARY KEY,

EmpName NVARCHAR(50),

DeptID INT,

FOREIGN KEY (DeptID) REFERENCES Department(DeptID)

);

5. What are constraints in SQL Server?

Constraints enforce rules on table data to maintain data integrity.

Types:

 Primary Key: Ensures unique and non-null values.

 Foreign Key: Maintains relationships between tables.

 Unique: Ensures unique values in a column.

 Check: Enforces conditions on column values.

 Default: Provides default values.

 Not Null: Ensures column cannot have NULL values.

6. What are joins in SQL Server?

Joins combine data from multiple tables based on related columns.

Types:

 INNER JOIN: Returns matching rows.


 LEFT JOIN: Returns all rows from the left table, and matching rows from the right.

 RIGHT JOIN: Returns all rows from the right table, and matching rows from the left.

 FULL OUTER JOIN: Returns all rows when there is a match in either table.

 CROSS JOIN: Returns the Cartesian product.

7. What is a view, and why do we use it?

A view is a virtual table based on the result of a query.

Advantages:

 Simplifies complex queries.

 Provides data security.

 Enhances reusability.

Example:

CREATE VIEW EmployeeView AS

SELECT EmpID, EmpName, DeptName

FROM Employee E

JOIN Department D ON E.DeptID = D.DeptID;

8. What is the difference between WHERE and HAVING clauses?

 WHERE: Filters rows before grouping.

 HAVING: Filters groups after grouping.

Example:

SELECT Department, COUNT(*)

FROM Employees

WHERE Salary > 50000

GROUP BY Department

HAVING COUNT(*) > 10;

9. What is normalization?

Normalization organizes data to minimize redundancy and improve integrity.

Forms:

 1NF: Eliminates duplicate columns and ensures atomicity.


 2NF: Removes partial dependencies.

 3NF: Removes transitive dependencies.

 BCNF: Resolves non-key dependencies.

10. What are indexes?

Indexes improve the speed of data retrieval.

Types:

 Clustered Index: Reorders the table data.

 Non-Clustered Index: Creates a separate structure with pointers to data.

Intermediate Level

1. What are stored procedures, and why are they used?

Stored procedures are precompiled SQL queries.

Advantages:

 Faster execution.

 Reusability.

 Centralized logic.

2. What are triggers?

Triggers execute automatically on specific events like INSERT, UPDATE, DELETE.

Types:

 AFTER: Executes after the event.

 INSTEAD OF: Replaces the event.

3. What is the difference between a temporary table and a table variable?

Feature Temporary Table Table Variable

Scope Session-level. Batch/procedure-level.

Performance Slower. Faster for small data.

4. What is the difference between UNION and UNION ALL?

 UNION: Removes duplicates.


 UNION ALL: Includes duplicates.

5. How do you handle NULL values in SQL Server?

 Use IS NULL or IS NOT NULL.

 Replace with ISNULL or COALESCE.

6. What is a CTE (Common Table Expression)?

A temporary result set defined using WITH.

Example:

WITH EmployeeCTE AS (

SELECT EmpID, Name FROM Employees WHERE Salary > 50000

SELECT * FROM EmployeeCTE;

7. What are the ACID properties in a transaction?

 Atomicity: All operations are completed or none.

 Consistency: Maintains database integrity.

 Isolation: Transactions do not interfere.

 Durability: Changes are permanent.

8. What is a subquery?

A query inside another query.

Types:

 Correlated: Depends on the outer query.

 Non-Correlated: Independent of the outer query.

9. What is the difference between RANK(), DENSE_RANK(), and ROW_NUMBER()?

 ROW_NUMBER: Unique numbers.

 RANK: Allows gaps.

 DENSE_RANK: No gaps.
10. What is a cursor?

Cursors allow row-by-row data processing.

Disadvantage: Slower than set-based operations.

Advanced Level

1. Clustered vs. Non-Clustered Indexes

 Clustered: Orders data.

 Non-Clustered: Separate structure.

2. Partitioning

Divides data for faster management.

3. Database Replication

Copies data for availability.

Types:

 Transactional, Merge, Snapshot.

4. Transaction Log

Ensures recoverability and durability.

5. Query Execution Plans

Used to analyze and optimize queries.

6. SQL Profiler

Monitors performance.

7. Isolation Levels

Control concurrency.

8. NOLOCK vs. READ COMMITTED

 NOLOCK: Dirty reads.


 READ COMMITTED: No dirty reads.

9. Deadlocks

Blocked processes. Prevent using consistent access order.

10. User-Defined Functions

Reusable logic.

Let me know if you'd like to dive deeper into any of these!

Here are interview questions specifically related to window functions for a Data Analyst role using SQL
Server, along with detailed explanations and examples.

Basic Level Questions

1. What are window functions in SQL Server?

Window functions perform calculations across a set of table rows related to the current row, but they do
not reduce the number of rows returned like aggregate functions.

Example:

SELECT EmpID, Department, Salary,

RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS Rank

FROM Employees;

 RANK() is a window function.

 The OVER clause defines the window (group of rows) to apply the function.

2. What is the difference between window functions and aggregate functions?

Feature Window Functions Aggregate Functions

Row Count Returns the same number of rows as the input. Reduces rows based on the aggregation.

Usage Calculates results across a specific "window" of rows. Aggregates values across a group.

Example RANK(), ROW_NUMBER(), SUM() OVER(...). SUM(), AVG(), COUNT() (without OVER).
3. Explain the purpose of the OVER clause.

The OVER clause defines a window or a set of rows for the window function. It can include:

 PARTITION BY: Divides rows into groups (optional).

 ORDER BY: Specifies the row order in the window (optional).

Example:

SELECT EmpID, Salary,

SUM(Salary) OVER (PARTITION BY Department) AS TotalSalaryByDept

FROM Employees;

 PARTITION BY Department: Groups employees by department.

 SUM(Salary): Computes the sum of salaries within each department.

4. What are some common window functions in SQL Server?

Function Purpose

ROW_NUMBER() Assigns a unique number to each row.

RANK() Assigns a rank with gaps in case of ties.

DENSE_RANK() Assigns a rank without gaps in case of ties.

NTILE(n) Divides rows into n groups and assigns a group number.

LEAD() Returns the value of a column for the next row.

LAG() Returns the value of a column for the previous row.

FIRST_VALUE() Returns the first value in the window.

LAST_VALUE() Returns the last value in the window.

SUM() Calculates the sum of a column over the window.

AVG() Calculates the average of a column over the window.

Intermediate Level Questions

5. What is the difference between ROW_NUMBER(), RANK(), and DENSE_RANK()?

Function Description Example

ROW_NUMBER() Assigns a unique number to each row. Rows: 1, 2, 3, 4, etc.

RANK() Assigns ranks with gaps for ties. Ties: 1, 2, 2, 4 (gap after ties).

DENSE_RANK() Assigns ranks without gaps for ties. Ties: 1, 2, 2, 3 (no gap after ties).
Example:

SELECT EmpID, Salary,

ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNumber,

RANK() OVER (ORDER BY Salary DESC) AS Rank,

DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank

FROM Employees;

6. What is the use of LEAD() and LAG() functions?

 LEAD(): Fetches the value from the next row.

 LAG(): Fetches the value from the previous row.

Example:

SELECT EmpID, Salary,

LAG(Salary) OVER (ORDER BY Salary DESC) AS PreviousSalary,

LEAD(Salary) OVER (ORDER BY Salary DESC) AS NextSalary

FROM Employees;

 LAG(Salary): Gets the salary of the previous employee.

 LEAD(Salary): Gets the salary of the next employee.

7. Explain the NTILE() function.

The NTILE(n) function divides rows into n buckets, assigning each row a bucket number.

Example:

SELECT EmpID, Salary,

NTILE(4) OVER (ORDER BY Salary DESC) AS Quartile

FROM Employees;

 Divides employees into 4 quartiles based on salary.

8. What is the difference between FIRST_VALUE() and LAST_VALUE()?

Function Description

FIRST_VALUE() Returns the first value in the window.

LAST_VALUE() Returns the last value in the window.

Example:
SELECT EmpID, Salary,

FIRST_VALUE(Salary) OVER (PARTITION BY Department ORDER BY Salary DESC) AS HighestSalary,

LAST_VALUE(Salary) OVER (PARTITION BY Department ORDER BY Salary DESC ROWS BETWEEN


UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LowestSalary

FROM Employees;

 FIRST_VALUE(Salary): Gets the highest salary (first in descending order).

 LAST_VALUE(Salary): Gets the lowest salary.

Advanced Level Questions

9. How can window functions be used to calculate a running total?

Example:

SELECT EmpID, Salary,

SUM(Salary) OVER (ORDER BY Salary ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS RunningTotal

FROM Employees;

 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Includes all rows from the start to
the current row.

10. What is the difference between ROWS and RANGE in a window function?

Feature ROWS RANGE

Definition Refers to specific rows. Refers to rows with the same value in the ORDER BY clause.

Use Case Precise row-based calculations. Range-based calculations.

Example:

-- Using ROWS

SUM(Salary) OVER (ORDER BY Salary ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)

-- Using RANGE

SUM(Salary) OVER (ORDER BY Salary RANGE BETWEEN 1000 PRECEDING AND CURRENT ROW)

11. How do you use multiple window functions in a query?

You can apply multiple window functions in a single query by using different OVER clauses.

Example:
SELECT EmpID, Salary,

ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary DESC) AS RowNumber,

SUM(Salary) OVER (PARTITION BY Department) AS TotalSalary

FROM Employees;

12. How would you optimize window functions in a query?

 Indexing: Use indexes on columns in the PARTITION BY and ORDER BY clauses.

 Limit Rows: Use ROWS instead of RANGE for better performance.

 Avoid Unnecessary Calculations: Only include the required columns in the SELECT statement.

Scenario-Based Questions

13. How would you calculate the top 3 salaries per department?

SELECT EmpID, Department, Salary

FROM (

SELECT EmpID, Department, Salary,

RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS Rank

FROM Employees

) AS Ranked

WHERE Rank <= 3;

14. How would you find consecutive months with revenue growth using window functions?

SELECT Month, Revenue,

Revenue - LAG(Revenue) OVER (ORDER BY Month) AS RevenueGrowth

FROM MonthlyRevenue

WHERE Revenue > LAG(Revenue) OVER (ORDER BY Month);

15. How would you calculate the percentage of total sales by product?

SELECT ProductID, SalesAmount,

SalesAmount * 100.0 / SUM(SalesAmount) OVER () AS PercentageOfTotal

FROM Sales;
These questions cover both theoretical concepts and practical scenarios to test a candidate's knowledge
and application of window functions in SQL Server. Let me know if you'd like to explore any question
further!

Here are some commonly asked SQL Server interview questions related to joins, tailored for a Data
Analyst role, along with examples and detailed explanations.

Basic Level Questions

1. What are joins in SQL?

A join in SQL combines rows from two or more tables based on a related column between them.

2. What are the different types of joins in SQL Server?

Type Description

INNER JOIN Returns rows with matching values in both tables.

LEFT JOIN (OUTER) Returns all rows from the left table, and matching rows from the right table.

RIGHT JOIN (OUTER) Returns all rows from the right table, and matching rows from the left table.

FULL OUTER JOIN Returns all rows when there is a match in either table.

CROSS JOIN Returns the Cartesian product of two tables (all combinations of rows).

SELF JOIN A table joins to itself.

3. What is an INNER JOIN?

An INNER JOIN returns rows where there is a match in both tables.

Example:

SELECT E.EmpID, E.EmpName, D.DeptName

FROM Employees E

INNER JOIN Departments D

ON E.DeptID = D.DeptID;

 Returns employees and their department names where there is a match between
Employees.DeptID and Departments.DeptID.

4. What is a LEFT JOIN?


A LEFT JOIN returns all rows from the left table and the matching rows from the right table. If no match is
found, NULL is returned for columns of the right table.

Example:

SELECT E.EmpID, E.EmpName, D.DeptName

FROM Employees E

LEFT JOIN Departments D

ON E.DeptID = D.DeptID;

 Includes all employees even if they are not assigned to a department.

5. What is a RIGHT JOIN?

A RIGHT JOIN returns all rows from the right table and the matching rows from the left table. If no match is
found, NULL is returned for columns of the left table.

Example:

SELECT E.EmpID, E.EmpName, D.DeptName

FROM Employees E

RIGHT JOIN Departments D

ON E.DeptID = D.DeptID;

 Includes all departments even if no employees are assigned to them.

6. What is a FULL OUTER JOIN?

A FULL OUTER JOIN returns all rows from both tables, with NULL for unmatched rows on either side.

Example:

SELECT E.EmpID, E.EmpName, D.DeptName

FROM Employees E

FULL OUTER JOIN Departments D

ON E.DeptID = D.DeptID;

 Includes all employees and all departments, even if no matches exist.

7. What is a CROSS JOIN?

A CROSS JOIN returns the Cartesian product of two tables, meaning every row in the first table is combined
with every row in the second table.

Example:
SELECT E.EmpName, D.DeptName

FROM Employees E

CROSS JOIN Departments D;

 Combines all employees with all departments, regardless of any relationship.

8. What is a SELF JOIN?

A SELF JOIN is a join of a table with itself.

Example:

SELECT E1.EmpName AS Employee, E2.EmpName AS Manager

FROM Employees E1

INNER JOIN Employees E2

ON E1.ManagerID = E2.EmpID;

 Returns employees and their managers by joining the Employees table to itself.

Intermediate Level Questions

9. What is the difference between INNER JOIN and OUTER JOIN?

Feature INNER JOIN OUTER JOIN (LEFT/RIGHT/FULL)

Matching Returns only matching Returns all rows from one or both tables, with NULL for non-
Rows rows. matching rows.

Excludes unmatched
Result Includes unmatched rows.
rows.

10. How do you join more than two tables in SQL Server?

Multiple tables can be joined by chaining JOIN statements.

Example:

SELECT E.EmpName, D.DeptName, P.ProjectName

FROM Employees E

INNER JOIN Departments D ON E.DeptID = D.DeptID

INNER JOIN Projects P ON E.EmpID = P.EmpID;

 Joins employees with their departments and projects.


11. What is an equi-join?

An equi-join uses the = operator to match rows between tables.

Example:

SELECT E.EmpName, D.DeptName

FROM Employees E

INNER JOIN Departments D

ON E.DeptID = D.DeptID;

12. What is a non-equi join?

A non-equi join uses operators other than = (like <, >, <=, >=, !=).

Example:

SELECT E.EmpName, S.Grade

FROM Employees E

JOIN SalaryGrades S

ON E.Salary BETWEEN S.MinSalary AND S.MaxSalary;

 Matches employees to salary grades based on a range.

13. What happens if there is no ON clause in a join?

If no ON clause is specified, it results in a CROSS JOIN, producing the Cartesian product.

Example:

SELECT E.EmpName, D.DeptName

FROM Employees E, Departments D;

14. What is the difference between NATURAL JOIN and INNER JOIN?

 NATURAL JOIN: Automatically matches columns with the same name and datatype.

 INNER JOIN: Requires an explicit condition using ON.

Note: SQL Server does not directly support NATURAL JOIN.

15. Can we use joins with aggregate functions?

Yes, joins can be used with aggregate functions like SUM(), AVG(), etc.

Example:
SELECT D.DeptName, COUNT(E.EmpID) AS EmployeeCount

FROM Departments D

LEFT JOIN Employees E

ON D.DeptID = E.DeptID

GROUP BY D.DeptName;

 Counts employees in each department.

Advanced Level Questions

16. What is the difference between JOIN and UNION?

Feature JOIN UNION

Combines columns from two or more


Purpose Combines rows from two or more result sets.
tables.

Output Horizontal combination. Vertical combination.

Removes duplicates by default (UNION ALL keeps


Duplicates Keeps duplicates unless specified.
duplicates).

17. How do you optimize joins in SQL Server?

 Use indexed columns in ON conditions.

 Minimize the number of rows using WHERE clauses.

 Avoid unnecessary FULL OUTER JOIN if a simpler join suffices.

 Use appropriate JOIN types based on requirements.

 Analyze execution plans for bottlenecks.

18. How would you handle a many-to-many relationship in joins?

Use a junction table to handle many-to-many relationships.

Example:

CREATE TABLE EmployeeProjects (

EmpID INT,

ProjectID INT

);
SELECT E.EmpName, P.ProjectName

FROM Employees E

INNER JOIN EmployeeProjects EP ON E.EmpID = EP.EmpID

INNER JOIN Projects P ON EP.ProjectID = P.ProjectID;

19. What are common pitfalls when using joins?

 Missing ON clause: Causes a Cartesian product.

 Incorrect join conditions: Leads to mismatches or incorrect results.

 Performance issues: Using joins on non-indexed columns or with large datasets.

 Duplicate rows: Occurs when joining tables with a one-to-many or many-to-many relationship
without handling duplicates.

20. Scenario-Based Question:

How would you retrieve employees who do not belong to any department?

SELECT E.EmpID, E.EmpName

FROM Employees E

LEFT JOIN Departments D

ON E.DeptID = D.DeptID

WHERE D.DeptID IS NULL;

 Uses a LEFT JOIN to identify employees with no matching department.

These questions test your understanding of joins, their types, and real-world applications as a Data Analyst.
Let me know if you'd like to dive deeper into any question!

You might also like