SQL Server Queries for Employee Data Management

Managing employee data efficiently requires a strong understanding of SQL queries. Below are 32 essential SQL Server queries that cover common use cases, such as fetching, filtering, updating, and analyzing employee records.

-- 01. Fetch all employees whose salary is greater than 50,000.

SELECT * FROM Employees WHERE Salary > 50000;


-- 02. Fetch all employees working in the "IT" department.

SELECT * FROM Employees WHERE Department = 'IT';


-- 03. Fetch employee names and their departments.

SELECT Name, Department FROM Employees;


-- 04. Fetch the top 3 highest-paid employees.

SELECT TOP 3 * FROM Employees ORDER BY Salary DESC;


-- 05. Fetch employees whose names start with the letter "A".

SELECT * FROM Employees WHERE Name LIKE 'A%';


-- 06. Fetch employees who were hired in the year 2022.

SELECT * FROM Employees WHERE YEAR(HireDate) = 2022;


-- 07. Count the total number of employees in each department.

SELECT Department, COUNT(*) AS TotalEmployees FROM Employees GROUP BY Department;


-- 08. Find the average salary of employees in the "Finance" department.

SELECT AVG(Salary) AS AvgSalary FROM Employees WHERE Department = 'Finance';


-- 09. Fetch employees with salaries between 30,000 and 60,000.

SELECT * FROM Employees WHERE Salary BETWEEN 30000 AND 60000;


-- 10. Fetch all employees who do not belong to the "HR" department.

SELECT * FROM Employees WHERE Department <> 'HR';


-- 11. Fetch the details of employees who have not been assigned a department (NULL department).

SELECT * FROM Employees WHERE Department IS NULL;


-- 12. Fetch employee details sorted by their salaries in descending order.

SELECT * FROM Employees ORDER BY Salary DESC;


-- 13. Fetch duplicate employee names from the employee table.

SELECT Name, COUNT(*) FROM Employees GROUP BY Name HAVING COUNT(*) > 1;


-- 14. Fetch the department name and the highest salary in each department.

SELECT Department, MAX(Salary) AS HighestSalary FROM Employees GROUP BY Department;


-- 15. Update the salary of employees in the "IT" department by 10%.

UPDATE Employees SET Salary = Salary * 1.10 WHERE Department = 'IT';


-- 16. Delete employees whose salaries are below 20,000.

DELETE FROM Employees WHERE Salary < 20000;


-- 17. Insert a new employee into the table.

INSERT INTO Employees (Name, Department, Salary, HireDate, Email, ManagerID) 

VALUES ('New Employee', 'IT', 55000, '2024-01-31', 'new.employee@company.com', NULL);


-- 18. Fetch employees whose names contain the substring "Ajay".

SELECT * FROM Employees WHERE Name LIKE '%Ajay%';


-- 19. Fetch employees whose email IDs end with "@sqldbanow.com".

SELECT * FROM Employees WHERE Email LIKE '%@sqldbanow.com';


-- 20. Find the total salary paid to employees in each department.

SELECT Department, SUM(Salary) AS TotalSalary FROM Employees GROUP BY Department;


-- 21. Fetch the employee with the second-highest salary.

SELECT * FROM Employees WHERE Salary = (SELECT MAX(Salary) FROM Employees WHERE Salary < (SELECT MAX(Salary) FROM Employees));


-- 22. Fetch the number of employees hired in each year.

SELECT YEAR(HireDate) AS Year, COUNT(*) AS TotalEmployees FROM Employees GROUP BY YEAR(HireDate);


-- 23. Fetch employees who share the same salary as another employee.

SELECT * FROM Employees WHERE Salary IN (SELECT Salary FROM Employees GROUP BY Salary HAVING COUNT(*) > 1);


-- 24. Fetch employees along with their manager's name (using self-join).

SELECT e1.Name AS Employee, e2.Name AS Manager FROM Employees e1 LEFT JOIN Employees e2 ON e1.ManagerID = e2.EmployeeID;


-- 25. Fetch employees with the same department and job title as "John Doe."

SELECT * FROM Employees WHERE Department = (SELECT Department FROM Employees WHERE Name = 'John Doe') 

AND JobTitle = (SELECT JobTitle FROM Employees WHERE Name = 'John Doe');


-- 26. Find the maximum and minimum salary of employees.

SELECT MAX(Salary) AS MaxSalary, MIN(Salary) AS MinSalary FROM Employees;


-- 27. Fetch employees who were hired in the last 6 months.

SELECT * FROM Employees WHERE HireDate >= DATEADD(MONTH, -6, GETDATE());


-- 28. Fetch employees who have worked for more than 5 years.

SELECT * FROM Employees WHERE DATEDIFF(YEAR, HireDate, GETDATE()) > 5;


-- 29. Fetch all employees who do not have a manager assigned.

SELECT * FROM Employees WHERE ManagerID IS NULL;


-- 30. Fetch the first name, last name, and full name of employees.

SELECT FirstName, LastName, CONCAT(FirstName, ' ', LastName) AS FullName FROM Employees;


-- 31. Fetch employees grouped by department and sorted by the total salary in descending order.

SELECT Department, SUM(Salary) AS TotalSalary FROM Employees GROUP BY Department ORDER BY TotalSalary DESC;


-- 32. Fetch all employees whose salaries are more than the average salary.

SELECT * FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees);


How to Improve Database Backup Speed in SQL Server

 Efficient database backups are crucial for maintaining data integrity and minimizing downtime. Below are several steps you can take to improve the speed of your database backups.

1. Backup Compression

Using compression can significantly reduce the size of the backup file and the time required to create it. Here is an example command:

BACKUP DATABASE BackMeUp TO
DISK = 'C:\Backups\MyFile_1.bak' WITH COMPRESSION;

2. Split Backup

Splitting the backup across multiple files can speed up the process by leveraging parallel writes.

BACKUP DATABASE BackMeUp TO
DISK = 'C:\Backups\MyFile_1.bak',
DISK = 'C:\Backups\MyFile_2.bak';

3. Use BUFFERCOUNT and MAXTRANSFERSIZE

Tuning these parameters can optimize the I/O operations during the backup.

BACKUP DATABASE BackMeUp TO
DISK = 'C:\Backups\MyFile_1.bak',
DISK = 'C:\Backups\MyFile_2.bak'
WITH COMPRESSION, BUFFERCOUNT = 575, MAXTRANSFERSIZE = 2097152;
  • BLOCKSIZE: Specifies the physical block size in bytes. Supported sizes range from 512 to 65536 (64 KB).

  • BUFFERCOUNT: Specifies the total number of I/O buffers for the backup. Large numbers can cause "out of memory" errors, so adjust carefully.

  • MAXTRANSFERSIZE: Specifies the largest unit of transfer in bytes, up to 4194304 bytes (4 MB).

4. Use the Fastest RAID Configurations

RAID configurations can greatly impact backup speeds. Prioritize using:

  • RAID 0

  • RAID 1

  • RAID 10

  • RAID 5

5. Use Locally Attached Disks

Backing up to locally attached disks can be faster than backing up across a network.

6. Utilize SAN Technologies

For enterprise setups, SAN technologies such as snapshot and split mirror backups can significantly enhance backup speed and reliability.

7. Optimize Network Backups

If you need to backup to other machines:

  • Use the fastest network cards and switches available.

  • Segment backup traffic from regular network traffic to reduce I/O bottlenecks.

By implementing these steps, you can achieve faster and more efficient database backups, ensuring better performance and reliability.

Managing SQL Server ERRORLOG File Growth to Prevent Space Issues

 Problem Overview:

In one of our smaller production environments, the SQL Server ERRORLOG file size unexpectedly grew to almost 60 GB. This caused a critical space crunch on the C:\ drive, leading to application timeout errors. The ERRORLOG file was located at:

C:\Program Files\Microsoft SQL Server\MSSQL14.INST1\MSSQL\Log

Challenges:

Active ERRORLOG File: The current ERRORLOG file could not be deleted directly because it was actively being used by SQL Server.

Time Constraints: Restarting the SQL Server instance to create a new ERRORLOG file required approval from the client and the change management team, which could be time-consuming.

Resolution Steps:

Step 1: Cycle the ERRORLOG File Without Restarting SQL Server

To address the issue without a service restart, we used the following command:

EXEC sp_cycle_errorlog;

GO

This command immediately created a new ERRORLOG file. The active log was cycled, and the previous ERRORLOG file was moved to the same directory with a numbered suffix (e.g., ERRORLOG.1).

Step 2: Relocate and Manage Old ERRORLOG Files

The old ERRORLOG file, which was consuming significant space, was manually moved to a different drive with sufficient free space. This provided temporary relief for the space issue on the C:\ drive. After a few days, we deleted the old log files to reclaim space permanently.

Step 3: Identify and Fix the Root Cause

Upon investigation, we discovered that one of the SQL Server Agent jobs was generating excessive logs in the ERRORLOG file. The problematic statement in the job's code was identified and removed to prevent further excessive logging.

Key Takeaways:

Proactive Monitoring: Regular monitoring of SQL Server ERRORLOG file size and disk space utilization is crucial to avoid unexpected space issues.

Efficient Log Management: Use the sp_cycle_errorlog procedure periodically to cycle logs and prevent single ERRORLOG files from growing too large.

Root Cause Analysis: Always investigate the underlying cause of excessive logging to implement a permanent fix.

How to save and then restore permissions after refreshing a database

The blog post provides a detailed guide on how to save and restore permissions after refreshing a SQL Server database. It introduces stored procedures for capturing and reapplying user and role permissions efficiently, ensuring minimal disruption during a database refresh. This method is particularly helpful when automating database refresh processes.

  • GenerateUserRoleScripts: This procedure generates the SQL scripts to create users and assign roles for the specified database and stores them in the UserRoleScripts table.

  • ExecuteUserRoleScripts: This procedure retrieves the scripts stored in UserRoleScripts and executes them on the specified database.
  • Stored Procedure 1: GenerateUserRoleScripts

    This procedure will generate and store the user-role scripts in the DBA..UserRoleScripts table for the specified database.

    Automating SQL Server Stored Procedure Execution Across Multiple Databases with PowerShell

     In many enterprise environments, database administrators (DBAs) often need to execute scripts across multiple databases on several SQL Server instances. Doing this manually can be time-consuming and error-prone, especially when managing a large number of servers. Automating this task using PowerShell can significantly streamline the process, ensuring consistency and saving valuable time.

    In this post, we'll walk through a PowerShell script that automates the execution of a stored procedure (sp_read) across all databases on multiple SQL Server instances. The script also captures the execution output and logs the status (success or failure) for each database in a detailed log file.