68. Employees With or Without Salary Records
An HR system stores employee details and salary information in separate tables.
Due to synchronization issues:
- Some employees may be missing salary records.
- Some salary records may not have matching employee details.
Given two tables
Employees
āāāāāāāāāāāāāāā¦āāāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā employee_id ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā name ā varchar ā āāāāāāāāāāāāāāā©āāāāāāāāāāā
- employee_id is the primary key.
- Each row represents an employee.
Salaries
āāāāāāāāāāāāāāā¦āāāāāāāāāāā ā Column Name ā Type ā ā āāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā employee_id ā int ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā salary ā int ā āāāāāāāāāāāāāāā©āāāāāāāāāāā
- employee_id is the primary key.
- Each row represents a salary record.
Write an SQL query to return all employee IDs, including:
- Employees who have a salary
- Employees who do not have a salary
- Salary records that do not have a matching employee
For each row, return:
- employee_id
- name
- salary
Return the result ordered by employee_id in ascending order.
Example 1:
Input:
Employees:
āāāāāāāāāāāāāāā¦āāāāāāāāāāā ā employee_id ā name ā ā āāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā 1 ā Aarav ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā 2 ā Neha ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā 3 ā Rohan ā āāāāāāāāāāāāāāā©āāāāāāāāāāā
Salaries:
āāāāāāāāāāāāāāā¦āāāāāāāāāāā ā employee_id ā salary ā ā āāāāāāāāāāāāāā¬āāāāāāāāāā⣠ā 1 ā 50000 ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā ā 4 ā 65000 ā āāāāāāāāāāāāāāā©āāāāāāāāāāā
Output:
āāāāāāāāāāāāāāā¦āāāāāāāāāāā¦āāāāāāāāāāā ā employee_id ā name ā salary ā ā āāāāāāāāāāāāāā¬āāāāāāāāāāā¬āāāāāāāāāā⣠ā 1 ā Aarav ā 50000 ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā¼āāāāāāāāāāā ā 2 ā Neha ā NULL ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā¼āāāāāāāāāāā ā 3 ā Rohan ā NULL ā āāāāāāāāāāāāāāā¼āāāāāāāāāāā¼āāāāāāāāāāā ā 4 ā NULL ā 65000 ā āāāāāāāāāāāāāāā©āāāāāāāāāāā©āāāāāāāāāāā
Explanation
- Employee 1 has both records, full data
- Employees 2 and 3 have no salary, salary is NULL
- Salary record for employee 4 has no employee, name is NULL
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.