MS SQL Server queries asking in interviews

 Here's a comprehensive list of SQL Server queries that are often asked in interviews. These queries cover a broad spectrum of SQL functionalities and scenarios:

Basic Queries

  1. Select All Columns from a Table

    SELECT * FROM Employees;
  2. Select Specific Columns from a Table

    SELECT FirstName, LastName FROM Employees;
  3. Select with a WHERE Clause

    SELECT * FROM Employees WHERE Department = 'Sales';
  4. Select with a LIKE Operator

    SELECT * FROM Employees WHERE LastName LIKE 'S%';
  5. Select with IN Operator

    SELECT * FROM Employees WHERE Department IN ('Sales', 'HR');
  6. Select with BETWEEN Operator

    SELECT * FROM Employees WHERE Salary BETWEEN 50000 AND 70000;
  7. Select with IS NULL

    SELECT * FROM Employees WHERE ManagerID IS NULL;
  8. Order by a Single Column

    SELECT * FROM Employees ORDER BY LastName ASC;
  9. Order by Multiple Columns

    SELECT * FROM Employees ORDER BY Department ASC, LastName DESC;
  10. Select Distinct Values

    SELECT DISTINCT Department FROM Employees;
  11. Count Rows in a Table

    SELECT COUNT(*) FROM Employees;
  12. Count Rows with a Condition

    SELECT COUNT(*) FROM Employees WHERE Department = 'Sales';
  13. Sum Values in a Column

    SELECT SUM(Salary) FROM Employees;
  14. Average Values in a Column

    SELECT AVG(Salary) FROM Employees;
  15. Find the Minimum Value in a Column

    SELECT MIN(Salary) FROM Employees;
  16. Find the Maximum Value in a Column

    SELECT MAX(Salary) FROM Employees;
  17. Group By a Single Column

    SELECT Department, COUNT(*) FROM Employees GROUP BY Department;
  18. Group By with Aggregates

    SELECT Department, AVG(Salary) FROM Employees GROUP BY Department;
  19. Filter Groups with HAVING

    SELECT Department, COUNT(*) FROM Employees GROUP BY Department HAVING COUNT(*) > 5;
  20. Select Top N Rows

    SELECT TOP 5 * FROM Employees ORDER BY Salary DESC;

Intermediate Queries

  1. Inner Join Two Tables

    SELECT e.FirstName, d.DepartmentName
    FROM Employees e INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID;
  2. Left Join Two Tables

    SELECT e.FirstName, d.DepartmentName
    FROM Employees e LEFT JOIN Departments d ON e.DepartmentID = d.DepartmentID;
  3. Right Join Two Tables

    SELECT e.FirstName, d.DepartmentName
    FROM Employees e RIGHT JOIN Departments d ON e.DepartmentID = d.DepartmentID;
  4. Full Outer Join Two Tables

    SELECT e.FirstName, d.DepartmentName
    FROM Employees e FULL OUTER JOIN Departments d ON e.DepartmentID = d.DepartmentID;
  5. Self Join

    SELECT e1.FirstName AS Employee, e2.FirstName AS Manager
    FROM Employees e1 INNER JOIN Employees e2 ON e1.ManagerID = e2.EmployeeID;
  6. Union of Two Queries

    SELECT FirstName FROM Employees
    MS SQL Server queries asking in interviews
    UNION SELECT ManagerName FROM Managers;
  7. Union All of Two Queries

    SELECT FirstName FROM Employees
    UNION ALL SELECT ManagerName FROM Managers;
  8. Subquery in SELECT Clause

    SELECT FirstName, (SELECT AVG(Salary) FROM Employees) AS AvgSalary
    FROM Employees;
  9. Subquery in WHERE Clause

    SELECT * FROM Employees
    WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE DepartmentName = 'Sales');
  10. Update Data in a Table

    UPDATE Employees
    SET Salary = Salary * 1.1 WHERE Department = 'Sales';
  11. Delete Data from a Table

    DELETE FROM Employees
    WHERE Department = 'Outsourcing';
  12. Insert Data into a Table

    INSERT INTO Employees (FirstName, LastName, Department, Salary)
    VALUES ('John', 'Doe', 'Engineering', 60000);
  13. Create a Table

    CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY, FirstName NVARCHAR(50), LastName NVARCHAR(50), Department NVARCHAR(50), Salary DECIMAL(18, 2) );
  14. Drop a Table

    DROP TABLE Employees;
  15. Alter a Table to Add a Column

    ALTER TABLE Employees
    ADD DateOfBirth DATE;
  16. Alter a Table to Drop a Column

    ALTER TABLE Employees
    DROP COLUMN DateOfBirth;
  17. Create an Index

    CREATE INDEX IX_Employees_Department
    ON Employees (Department);
  18. Drop an Index

    DROP INDEX IX_Employees_Department ON Employees;
  19. Create a View

    CREATE VIEW EmployeeView AS
    SELECT FirstName, LastName, Department FROM Employees WHERE Salary > 50000;
  20. Drop a View

    DROP VIEW EmployeeView;

Advanced Queries

  1. Common Table Expression (CTE)

    WITH DepartmentCTE AS (
    SELECT DepartmentID, DepartmentName FROM Departments ) SELECT * FROM DepartmentCTE;
  2. Recursive CTE

    WITH RecursiveCTE AS (
    SELECT EmployeeID, ManagerID, FirstName FROM Employees WHERE ManagerID IS NULL UNION ALL SELECT e.EmployeeID, e.ManagerID, e.FirstName FROM Employees e INNER JOIN RecursiveCTE r ON e.ManagerID = r.EmployeeID ) SELECT * FROM RecursiveCTE;
  3. Row Number Window Function

    SELECT FirstName, LastName,
    ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum FROM Employees;
  4. Rank Window Function

    SELECT FirstName, LastName,
    RANK() OVER (ORDER BY Salary DESC) AS Rank FROM Employees;
  5. Dense Rank Window Function

    SELECT FirstName, LastName,
    DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank FROM Employees;
  6. NTILE Window Function

    SELECT FirstName, LastName,
    NTILE(4) OVER (ORDER BY Salary DESC) AS Quartile FROM Employees;
  7. Lead and Lag Window Functions

    SELECT FirstName, LastName, Salary,
    LEAD(Salary, 1) OVER (ORDER BY Salary) AS NextSalary, LAG(Salary, 1) OVER (ORDER BY Salary) AS PreviousSalary FROM Employees;
  8. Common Table Expression with Aggregates

    WITH DepartmentSalary AS (
    SELECT Department, SUM(Salary) AS TotalSalary FROM Employees GROUP BY Department ) SELECT * FROM DepartmentSalary;
  9. Pivot Data

    SELECT *
    FROM (SELECT Department, Salary FROM Employees) AS SourceTable PIVOT (SUM(Salary) FOR Department IN ([Sales], [HR], [Engineering])) AS PivotTable;
  10. Unpivot Data

    SELECT Department, Salary
    FROM (SELECT EmployeeID, Sales, HR, Engineering FROM EmployeeSalaries) AS PivotTable UNPIVOT (Salary FOR Department IN (Sales, HR, Engineering)) AS UnpivotedTable;
  11. Transaction Management

    BEGIN TRANSACTION;
    UPDATE Employees SET Salary = Salary * 1.1 WHERE Department = 'Sales'; IF @@ERROR <> 0 BEGIN ROLLBACK TRANSACTION; END ELSE BEGIN COMMIT TRANSACTION; END
  12. Using TRY...CATCH for Error Handling

    BEGIN TRY
    BEGIN TRANSACTION; UPDATE Employees SET Salary = Salary * 1.1 WHERE Department = 'Sales'; COMMIT TRANSACTION; END TRY BEGIN CATCH ROLLBACK TRANSACTION; -- Error handling code here END CATCH;
  13. Create a Stored Procedure

    CREATE PROCEDURE GetEmployeeByDepartment
    @Department NVARCHAR(50) AS BEGIN SELECT * FROM Employees WHERE Department = @Department; END;
  14. Execute a Stored Procedure

    EXEC GetEmployeeByDepartment @Department = 'Sales';
  15. Create a Function

    CREATE FUNCTION CalculateBonus (@Salary DECIMAL(18, 2))
    RETURNS DECIMAL(18, 2) AS BEGIN RETURN @Salary * 0.1; END;
  16. Use a Function

    SELECT FirstName, Salary, dbo.CalculateBonus(Salary) AS Bonus
    FROM Employees;
  17. Create a Trigger

    CREATE TRIGGER trgAfterInsert
    ON Employees AFTER INSERT AS BEGIN PRINT 'New employee added'; END;
  18. Create an Index with Included Columns

    CREATE INDEX IX_Employees_Department
    ON Employees (Department) INCLUDE (FirstName, LastName);
  19. Show Execution Plan

    SET SHOWPLAN_ALL ON;
    SELECT * FROM Employees; SET SHOWPLAN_ALL OFF;
  20. Optimize a Query Using Hints

    SELECT * FROM Employees WITH (NOLOCK);
  21. Check Table Schema

    EXEC sp_help 'Employees';
  22. Find the Last Modified Date of a Table

    SELECT name AS TableName, modify_date
    FROM sys.tables WHERE name = 'Employees';
  23. List All Tables in a Database

    SELECT * FROM INFORMATION_SCHEMA.TABLES;
  24. List All Columns in a Table

    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Employees';
  25. List All Indexes on a Table

    EXEC sp_helpindex 'Employees';
  26. Check for Missing Indexes

    SELECT *
    FROM sys.dm_db_missing_index_details;
  27. Find Long-Running Queries

    SELECT *
    FROM sys.dm_exec_requests WHERE status = 'running';
  28. Get SQL Server Version

    SELECT @@VERSION;
  29. Generate Database Schema Script

    EXEC sp_helpdb 'YourDatabaseName';
  30. Backup a Database

    BACKUP DATABASE YourDatabaseName
    TO DISK = 'C:\Backup\YourDatabaseName.bak';
  31. Restore a Database

    RESTORE DATABASE YourDatabaseName
    FROM DISK = 'C:\Backup\YourDatabaseName.bak';
  32. Check Database Size

    EXEC sp_spaceused;
  33. Find Active Sessions

    SELECT * FROM sys.dm_exec_sessions;
  34. Find Active Connections

    SELECT * FROM sys.dm_exec_connections;
  35. Check SQL Server Configuration

    EXEC sp_configure;
  36. Monitor SQL Server Performance

    EXEC sp_monitor;
  37. List All Views in a Database

    SELECT * FROM INFORMATION_SCHEMA.VIEWS;
  38. List All Stored Procedures in a Database

    SELECT * FROM INFORMATION_SCHEMA.ROUTINES
    WHERE ROUTINE_TYPE = 'PROCEDURE';
  39. Find Orphaned Users

    EXEC sp_change_users_login 'Report';
  40. Synchronize Orphaned Users

    EXEC sp_change_users_login 'Auto_Fix', 'username';
  41. Get Database File Locations

    SELECT name, physical_name
    FROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName');
  42. List All Triggers in a Database

    SELECT * FROM sys.triggers;
  43. Find Queries with High CPU Usage

    SELECT *
    FROM sys.dm_exec_query_stats ORDER BY total_worker_time DESC;
  44. Find Queries with High Disk I/O

    SELECT *
    FROM sys.dm_exec_query_stats ORDER BY total_logical_reads DESC;
  45. Find Slow-Running Queries

    SELECT *
    FROM sys.dm_exec_query_stats WHERE total_elapsed_time > 1000;
  46. Check for Blocking Sessions

    SELECT *
    FROM sys.dm_exec_requests WHERE blocking_session_id <> 0;
  47. Find Deadlocks

    SELECT *
    FROM sys.dm_tran_locks WHERE request_status = 'WAIT';
  48. List All SQL Server Agents Jobs

    EXEC sp_help_job;
  49. Check SQL Server Agent Job Status

    EXEC msdb.dbo.sp_help_jobhistory @job_name = 'YourJobName';
  50. Create a Full-Text Index

    CREATE FULLTEXT INDEX ON Employees (FirstName, LastName)
    KEY INDEX PK_Employees;
  51. Perform a Full-Text Search

    SELECT * FROM Employees
    WHERE CONTAINS(FirstName, 'John');
  52. Find Expired Indexes

    SELECT *
    FROM sys.dm_db_index_usage_stats WHERE database_id = DB_ID('YourDatabaseName');
  53. Monitor SQL Server Resource Usage

    SELECT *
    FROM sys.dm_os_performance_counters;
  54. Get Execution Plan for a Query

    SET SHOWPLAN_XML ON;
    SELECT * FROM Employees; SET SHOWPLAN_XML OFF;
  55. Rebuild an Index

    ALTER INDEX IX_Employees_Department ON Employees REBUILD;
  56. Reorganize an Index

    ALTER INDEX IX_Employees_Department ON Employees REORGANIZE;
  57. Check Index Fragmentation

    SELECT *
    FROM sys.dm_db_index_physical_stats(DB_ID('YourDatabaseName'), OBJECT_ID('Employees'), NULL, NULL, 'DETAILED');
  58. Check for Long Transactions

    SELECT *
    FROM sys.dm_tran_active_transactions;
  59. Find Database Growth

    SELECT *
    FROM sys.dm_db_log_space_usage;
  60. Query Plan Cache Information

    SELECT * FROM sys.dm_exec_query_plan_stats;

  61. Query for SQL Server Wait Stats

    SELECT * FROM sys.dm_os_wait_stats;

  62. Query for SQL Server Locks

    SELECT * FROM sys.dm_tran_locks;

  63. Check SQL Server Service Accounts

    EXEC xp_servicecontrol 'QUERYSTATE', 'MSSQLSERVER';

  64. Get Current User in SQL Server

    SELECT SYSTEM_USER;

  65. List All Databases

    SELECT name FROM sys.databases;

These queries cover a wide range of SQL Server functionalities, from basic data manipulation to advanced performance tuning and database management. Practicing these can help prepare for a variety of SQL Server interview questions.



Post a Comment

Previous Post Next Post