Tuesday, 3 November 2026

Find employees who have the same salary as their manager.

To find employees who earn the exact same salary as their manager, you need to perform a Self-Join. This means you join the employees table to itself—treating one instance as the "Employee table" and the second instance as the "Manager table."
The Query
The join links the employee's manager_id to the manager's employee_id, and the WHERE clause filters for matching salary values:
sql
SELECT 
    e.employee_id AS emp_id,
    e.employee_name AS emp_name,
    e.salary AS emp_salary,
    m.employee_name AS manager_name,
    m.salary AS manager_salary
FROM employees e
INNER JOIN employees m ON e.manager_id = m.employee_id
WHERE e.salary = m.salary;
Use code with caution.
How It Works
  • employees e: Represents the table context looking down at the regular employees.
  • employees m: Represents the table context looking up at the managers.
  • ON e.manager_id = m.employee_id: Establishes the relationship path between the employee and their boss.
  • WHERE e.salary = m.salary: Isolates the records where both parties make the exact same amount of money.

Complete Playground Script (Schema + Test Data)
Copy and execute this script to test the logic live:
sql
-- 1. CREATE TABLE SCHEMA
CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100),
    salary DECIMAL(10, 2),
    manager_id INT,
    FOREIGN KEY (manager_id) REFERENCES employees(employee_id)
);

-- 2. INSERT SAMPLE DATA
-- Top levels (No managers)
INSERT INTO employees (employee_id, employee_name, salary, manager_id) VALUES
(1, 'Fiona Gallagher', 120000.00, NULL), -- CEO
(2, 'Alice Smith', 95000.00, NULL);     -- VP

-- Reports
INSERT INTO employees (employee_id, employee_name, salary, manager_id) VALUES
(3, 'Bob Jones', 75000.00, 1),      -- Reports to Fiona (Diff Salary)
(4, 'Charlie Brown', 95000.00, 2),  -- Reports to Alice (SAME Salary - Matches!)
(5, 'Diana Prince', 95000.00, 2),   -- Reports to Alice (SAME Salary - Matches!)
(6, 'Evan Wright', 60000.00, 3);    -- Reports to Bob (Diff Salary)

-- 3. EXECUTE THE SELF-JOIN QUERY
SELECT 
    e.employee_name AS employee_name,
    e.salary AS employee_salary,
    m.employee_name AS manager_name
FROM employees e
INNER JOIN employees m ON e.manager_id = m.employee_id
WHERE e.salary = m.salary;
Use code with caution.
Expected Query Output
employee_nameemployee_salarymanager_name
Charlie Brown95000.00Alice Smith
Diana Prince95000.00Alice Smith

No comments:

Post a Comment

Note: only a member of this blog may post a comment.