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
Select All Columns from a Table
SELECT * FROM Employees;Select Specific Columns from a Table
SELECT FirstName, LastName FROM Employees;Select with a WHERE Clause
SELECT * FROM Employees WHERE Department = 'Sales';Select with a LIKE Operator
SELECT * FROM Employees WHERE LastName LIKE 'S%';Select with IN Operator
SELECT * FROM Employees WHERE Department IN ('Sales', 'HR');Select with BETWEEN Operator
SELECT * FROM Employees WHERE Salary BETWEEN 50000 AND 70000;Select with IS NULL
SELECT * FROM Employees WHERE ManagerID IS NULL;Order by a Single Column
SELECT * FROM Employees ORDER BY LastName ASC;Order by Multiple Columns
SELECT * FROM Employees ORDER BY Department ASC, LastName DESC;Select Distinct Values
SELECT DISTINCT Department FROM Employees;Count Rows in a Table
SELECT COUNT(*) FROM Employees;Count Rows with a Condition
SELECT COUNT(*) FROM Employees WHERE Department = 'Sales';Sum Values in a Column
SELECT SUM(Salary) FROM Employees;Average Values in a Column
SELECT AVG(Salary) FROM Employees;Find the Minimum Value in a Column
SELECT MIN(Salary) FROM Employees;Find the Maximum Value in a Column
SELECT MAX(Salary) FROM Employees;Group By a Single Column
SELECT Department, COUNT(*) FROM Employees GROUP BY Department;Group By with Aggregates
SELECT Department, AVG(Salary) FROM Employees GROUP BY Department;Filter Groups with HAVING
SELECT Department, COUNT(*) FROM Employees GROUP BY Department HAVING COUNT(*) > 5;Select Top N Rows
SELECT TOP 5 * FROM Employees ORDER BY Salary DESC;
Intermediate Queries
Inner Join Two Tables
SELECT e.FirstName, d.DepartmentNameFROM Employees e INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID;
Left Join Two Tables
SELECT e.FirstName, d.DepartmentNameFROM Employees e LEFT JOIN Departments d ON e.DepartmentID = d.DepartmentID;
Right Join Two Tables
SELECT e.FirstName, d.DepartmentNameFROM Employees e RIGHT JOIN Departments d ON e.DepartmentID = d.DepartmentID;
Full Outer Join Two Tables
SELECT e.FirstName, d.DepartmentNameFROM Employees e FULL OUTER JOIN Departments d ON e.DepartmentID = d.DepartmentID;
Self Join
SELECT e1.FirstName AS Employee, e2.FirstName AS ManagerFROM Employees e1 INNER JOIN Employees e2 ON e1.ManagerID = e2.EmployeeID;
Union of Two Queries
Union All of Two Queries
SELECT FirstName FROM EmployeesUNION ALL SELECT ManagerName FROM Managers;
Subquery in SELECT Clause
SELECT FirstName, (SELECT AVG(Salary) FROM Employees) AS AvgSalaryFROM Employees;
Subquery in WHERE Clause
SELECT * FROM EmployeesWHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE DepartmentName = 'Sales');
Update Data in a Table
UPDATE EmployeesSET Salary = Salary * 1.1 WHERE Department = 'Sales';
Delete Data from a Table
DELETE FROM EmployeesWHERE Department = 'Outsourcing';
Insert Data into a Table
INSERT INTO Employees (FirstName, LastName, Department, Salary)VALUES ('John', 'Doe', 'Engineering', 60000);
Create a Table
CREATE TABLE Employees (EmployeeID INT PRIMARY KEY, FirstName NVARCHAR(50), LastName NVARCHAR(50), Department NVARCHAR(50), Salary DECIMAL(18, 2) );
Drop a Table
DROP TABLE Employees;Alter a Table to Add a Column
ALTER TABLE EmployeesADD DateOfBirth DATE;
Alter a Table to Drop a Column
ALTER TABLE EmployeesDROP COLUMN DateOfBirth;
Create an Index
CREATE INDEX IX_Employees_DepartmentON Employees (Department);
Drop an Index
DROP INDEX IX_Employees_Department ON Employees;Create a View
CREATE VIEW EmployeeView ASSELECT FirstName, LastName, Department FROM Employees WHERE Salary > 50000;
Drop a View
DROP VIEW EmployeeView;
Advanced Queries
Common Table Expression (CTE)
WITH DepartmentCTE AS (SELECT DepartmentID, DepartmentName FROM Departments ) SELECT * FROM DepartmentCTE;
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;
Row Number Window Function
SELECT FirstName, LastName,ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum FROM Employees;
Rank Window Function
SELECT FirstName, LastName,RANK() OVER (ORDER BY Salary DESC) AS Rank FROM Employees;
Dense Rank Window Function
SELECT FirstName, LastName,DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank FROM Employees;
NTILE Window Function
SELECT FirstName, LastName,NTILE(4) OVER (ORDER BY Salary DESC) AS Quartile FROM Employees;
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;
Common Table Expression with Aggregates
WITH DepartmentSalary AS (SELECT Department, SUM(Salary) AS TotalSalary FROM Employees GROUP BY Department ) SELECT * FROM DepartmentSalary;
Pivot Data
SELECT *FROM (SELECT Department, Salary FROM Employees) AS SourceTable PIVOT (SUM(Salary) FOR Department IN ([Sales], [HR], [Engineering])) AS PivotTable;
Unpivot Data
SELECT Department, SalaryFROM (SELECT EmployeeID, Sales, HR, Engineering FROM EmployeeSalaries) AS PivotTable UNPIVOT (Salary FOR Department IN (Sales, HR, Engineering)) AS UnpivotedTable;
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
Using TRY...CATCH for Error Handling
BEGIN TRYBEGIN 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;
Create a Stored Procedure
CREATE PROCEDURE GetEmployeeByDepartment@Department NVARCHAR(50) AS BEGIN SELECT * FROM Employees WHERE Department = @Department; END;
Execute a Stored Procedure
EXEC GetEmployeeByDepartment @Department = 'Sales';Create a Function
CREATE FUNCTION CalculateBonus (@Salary DECIMAL(18, 2))RETURNS DECIMAL(18, 2) AS BEGIN RETURN @Salary * 0.1; END;
Use a Function
SELECT FirstName, Salary, dbo.CalculateBonus(Salary) AS BonusFROM Employees;
Create a Trigger
CREATE TRIGGER trgAfterInsertON Employees AFTER INSERT AS BEGIN PRINT 'New employee added'; END;
Create an Index with Included Columns
CREATE INDEX IX_Employees_DepartmentON Employees (Department) INCLUDE (FirstName, LastName);
Show Execution Plan
SET SHOWPLAN_ALL ON;SELECT * FROM Employees; SET SHOWPLAN_ALL OFF;
Optimize a Query Using Hints
SELECT * FROM Employees WITH (NOLOCK);Check Table Schema
EXEC sp_help 'Employees';Find the Last Modified Date of a Table
SELECT name AS TableName, modify_dateFROM sys.tables WHERE name = 'Employees';
List All Tables in a Database
SELECT * FROM INFORMATION_SCHEMA.TABLES;List All Columns in a Table
SELECT COLUMN_NAMEFROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Employees';
List All Indexes on a Table
EXEC sp_helpindex 'Employees';Check for Missing Indexes
SELECT *FROM sys.dm_db_missing_index_details;
Find Long-Running Queries
SELECT *FROM sys.dm_exec_requests WHERE status = 'running';
Get SQL Server Version
SELECT @@VERSION;Generate Database Schema Script
EXEC sp_helpdb 'YourDatabaseName';Backup a Database
BACKUP DATABASE YourDatabaseNameTO DISK = 'C:\Backup\YourDatabaseName.bak';
Restore a Database
RESTORE DATABASE YourDatabaseNameFROM DISK = 'C:\Backup\YourDatabaseName.bak';
Check Database Size
EXEC sp_spaceused;Find Active Sessions
SELECT * FROM sys.dm_exec_sessions;Find Active Connections
SELECT * FROM sys.dm_exec_connections;Check SQL Server Configuration
EXEC sp_configure;Monitor SQL Server Performance
EXEC sp_monitor;List All Views in a Database
SELECT * FROM INFORMATION_SCHEMA.VIEWS;List All Stored Procedures in a Database
SELECT * FROM INFORMATION_SCHEMA.ROUTINESWHERE ROUTINE_TYPE = 'PROCEDURE';
Find Orphaned Users
EXEC sp_change_users_login 'Report';Synchronize Orphaned Users
EXEC sp_change_users_login 'Auto_Fix', 'username';Get Database File Locations
SELECT name, physical_nameFROM sys.master_files WHERE database_id = DB_ID('YourDatabaseName');
List All Triggers in a Database
SELECT * FROM sys.triggers;Find Queries with High CPU Usage
SELECT *FROM sys.dm_exec_query_stats ORDER BY total_worker_time DESC;
Find Queries with High Disk I/O
SELECT *FROM sys.dm_exec_query_stats ORDER BY total_logical_reads DESC;
Find Slow-Running Queries
SELECT *FROM sys.dm_exec_query_stats WHERE total_elapsed_time > 1000;
Check for Blocking Sessions
SELECT *FROM sys.dm_exec_requests WHERE blocking_session_id <> 0;
Find Deadlocks
SELECT *FROM sys.dm_tran_locks WHERE request_status = 'WAIT';
List All SQL Server Agents Jobs
EXEC sp_help_job;Check SQL Server Agent Job Status
EXEC msdb.dbo.sp_help_jobhistory @job_name = 'YourJobName';Create a Full-Text Index
CREATE FULLTEXT INDEX ON Employees (FirstName, LastName)KEY INDEX PK_Employees;
Perform a Full-Text Search
SELECT * FROM EmployeesWHERE CONTAINS(FirstName, 'John');
Find Expired Indexes
SELECT *FROM sys.dm_db_index_usage_stats WHERE database_id = DB_ID('YourDatabaseName');
Monitor SQL Server Resource Usage
SELECT *FROM sys.dm_os_performance_counters;
Get Execution Plan for a Query
SET SHOWPLAN_XML ON;SELECT * FROM Employees; SET SHOWPLAN_XML OFF;
Rebuild an Index
ALTER INDEX IX_Employees_Department ON Employees REBUILD;Reorganize an Index
ALTER INDEX IX_Employees_Department ON Employees REORGANIZE;Check Index Fragmentation
SELECT *FROM sys.dm_db_index_physical_stats(DB_ID('YourDatabaseName'), OBJECT_ID('Employees'), NULL, NULL, 'DETAILED');
Check for Long Transactions
SELECT *FROM sys.dm_tran_active_transactions;
Find Database Growth
SELECT *FROM sys.dm_db_log_space_usage;
Query Plan Cache Information
SELECT * FROM sys.dm_exec_query_plan_stats;Query for SQL Server Wait Stats
SELECT * FROM sys.dm_os_wait_stats;Query for SQL Server Locks
SELECT * FROM sys.dm_tran_locks;Check SQL Server Service Accounts
EXEC xp_servicecontrol 'QUERYSTATE', 'MSSQLSERVER';Get Current User in SQL Server
SELECT SYSTEM_USER;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