41. What is a Common Table Expression (CTE)?
Answer: A temporary result set you can reference within a SELECT, INSERT, UPDATE, or DELETE.
Example:
WITH EmployeeCTE AS (
SELECT Name, DepartmentID
FROM Employees
WHERE Salary > 50000
)
SELECT * FROM EmployeeCTE;
42. What is Recursive CTE?
Answer: A CTE that refers to itself to solve hierarchical problems (e.g., manager-employee structure).
Example:
43. What is the difference between Stored Procedure and Function?
Answer:
Aspect | Stored Procedure | Function |
---|---|---|
Returns value | Optional | Must return value |
Can call | Functions, Procedures | Only functions |
Can modify DB | Yes | No (except inline Table Functions) |
44. What are CROSS APPLY and OUTER APPLY?
Answer: Used to join a table to a table-valued function.
Example:
SELECT e.Name, d.DepartmentName
FROM Employees e
CROSS APPLY GetDepartments(e.ID) d;
45. What is a Filtered Index?
Answer: An index with a WHERE clause to improve performance for specific queries.
Example:
46. What is Partitioned Table?
Answer: Large tables split into smaller partitions based on key values for better performance.
47. Explain Sequence Object.
Answer: Used to generate a sequence of numeric values, similar to identity but more flexible.
Example:
48. What is an Optimistic Concurrency Control?
Answer: Assumes multiple transactions can complete without affecting each other and checks conflicts at commit time.
49. What is Rowversion (Timestamp) in SQL Server?
Answer: A mechanism to automatically generate a unique binary number when a row is modified.
Example: ALTER TABLE Employees ADD RowVer ROWVERSION;
50. How to find the second highest salary in a table?
Answer:
Using TOP and ORDER BY:
SELECT TOP 1 Salary
FROM (
SELECT DISTINCT TOP 2 Salary
FROM Employees
ORDER BY Salary DESC
) AS Temp
ORDER BY Salary ASC;
Or using DENSE_RANK():
WITH SalaryCTE AS (
SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS RankNo
FROM Employees
)
SELECT Salary
FROM SalaryCTE
WHERE RankNo = 2;
Top 50 Basic Level SQL Interview Questions and Answers with Examples
Top 50 Intermediate SQL Interview Questions You Must Practice [With Examples]
1 thought on “Top 50 Advanced SQL Questions asked in Top Companies (with Answers + Examples)”