Close

Employee couples – SQL Puzzle

Given a table schema of employees like the following. Employee id, employee name, and spouse id if their spouse is also working in the same company. spouse id will be null if only one person is working.

IdNameSpouse id
100Sachin101
101Anjali100
102Virat103
103Anushka102
104Sanju
Sample employee data

Given a table like the above, the question is to find the number of couples working in that office.

You might be overthinking about this problem if you are considering a self-join because spouse id is a reference to id column of the same table. In fact we don’t need a join at all for the given problem. We know that join will be a costly operation of the table is considerably big. We just need the following query to get the result.

SELECT 
  COUNT(1)/2 AS COUPLES
FROM
  employees
WHERE
  spouse_id IS NOT NULL

However if you need to print the names of the couples also, then you need a self join some thing like the following.

SELECT 
    a.name as employee, 
    b.name as spouse 
FROM 
    test.emp1 as a JOIN test.emp1 as b 
    ON a.id = b.spouse_id;

The above query prints the couple names twice. It is an interesting challenge to the readers if we want to see each couple row only once! If you are looking for a clue, we just need to add one more condition to the above query. Give it a try 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *