Write a SQL Query to Generate an Employee Payroll Report with Overtime Calculations

Generating payroll reports is a common use case in HR and payroll management systems. In this tutorial, we will demonstrate how to write an SQL query to calculate an employee’s payroll, including basic salary, overtime pay, and deductions, and present the data in a detailed report format.


Scenario Description

Imagine a table named employee_salaries with the following structure:

Column NameData TypeDescription
employee_idINTUnique identifier for the employee
nameVARCHAR(50)Employee name
basic_salaryDECIMAL(10,2)The base salary for the employee
hraDECIMAL(10,2)House Rent Allowance
daDECIMAL(10,2)Dearness Allowance
overtime_hoursINTTotal overtime hours worked in the month
overtime_rateDECIMAL(10,2)Hourly rate for overtime
deductionsDECIMAL(10,2)Total deductions for the month

Query

The query below calculates the total salary by including overtime pay and deducting the specified deductions:

sqlCopy codeSELECT  
    employee_id,  
    name,  
    basic_salary,  
    hra,  
    da,  
    (overtime_hours * overtime_rate) AS overtime_pay,  
    (basic_salary + hra + da + (overtime_hours * overtime_rate) - deductions) AS net_salary  
FROM  
    employee_salaries  
ORDER BY  
    net_salary DESC;  

Explanation

  1. Columns:
    • overtime_pay is calculated as the product of overtime_hours and overtime_rate.
    • net_salary is computed by adding the basic salary, HRA, DA, and overtime pay, then subtracting deductions.
  2. Sorting:
    • The result is ordered by net_salary in descending order, so the highest earners appear first.

Output

Assuming the following data in the employee_salaries table:

employee_idnamebasic_salaryhradaovertime_hoursovertime_ratedeductions
1John Doe50000.0010000500010200.003000.00
2Jane Doe45000.009000400015250.004000.00

The output would be:

employee_idnamebasic_salaryhradaovertime_paynet_salary
1John Doe50000.001000050002000.0065000.00
2Jane Doe45000.00900040003750.0061750.00

Conclusion

This SQL query provides a complete payroll report by including overtime calculations. It’s efficient and can be modified to suit additional payroll requirements. Add this to your SQL toolkit to make payroll management easier!

Leave a comment