I need help reviewing two SQL queries for a staff database system. I’m concerned about performance and correctness issues.
First Query - Staff Reporting Chain
This query shows employee info (job title, first name, last name) plus their supervisor’s title by self-joining the staff table. The supervisor column stores full names as “FirstName LastName” format.
SELECT
emp.JobTitle,
emp.FirstName,
emp.LastName,
mgr.JobTitle AS SupervisorTitle
FROM
staff_data AS emp
INNER JOIN
staff_data AS mgr
ON emp.ManagerName = mgr.FirstName + ' ' + mgr.LastName
WHERE
emp.ManagerName IS NOT NULL
ORDER BY
mgr.JobTitle ASC,
emp.JobTitle ASC;
Second Query - Department Pay Analysis
This analyzes total compensation by department, finds highest paid person per department, and calculates what percentage the top earner represents.
WITH DeptPayCTE AS
(
SELECT DepartmentID, SUM(Compensation) AS TotalDeptPay
FROM staff_records_2024
GROUP BY DepartmentID
),
HighestPaidCTE AS
(
SELECT DepartmentID, EmployeeName, Compensation,
ROW_NUMBER() OVER (PARTITION BY DepartmentID ORDER BY Compensation DESC) AS RankNum
FROM staff_records_2024
),
TopEarnerCTE AS
(
SELECT DepartmentID, EmployeeName AS HighestPaidName, Compensation AS MaxPay
FROM HighestPaidCTE
WHERE RankNum = 1
)
SELECT
dp.DepartmentID,
dp.TotalDeptPay,
te.HighestPaidName,
te.MaxPay,
ROUND(CAST(te.MaxPay AS DECIMAL(12, 4)) / dp.TotalDeptPay * 100, 4) AS PayPercentage,
CASE
WHEN te.MaxPay < 0.5 * dp.TotalDeptPay THEN 'Yes'
ELSE 'No'
END AS HasOptimizationOpportunity
FROM
DeptPayCTE dp
JOIN
TopEarnerCTE te ON dp.DepartmentID = te.DepartmentID
ORDER BY
dp.DepartmentID ASC;
Main concerns:
- Is the string concatenation join in the first query problematic for performance?
- Could the decimal casting cause precision or division errors?
- Should I use DENSE_RANK instead of ROW_NUMBER for handling salary ties?
- Are there better approaches for these requirements?
The first query seems slow and the name matching feels unreliable. The second query works but I’m worried about edge cases with zero values.