0

I have two tables, EMPLOYEE & DEPENDENT. The employee PK is SSN and the foreign key for the dependent table is ESSN. I am trying to retrieve the name of all employees and the names of their dependent. If an employee does not have a dependent, I just need to display a blank value in the dependent column.

To retrieve the name of employees who have dependents, this is the statement I use:

SELECT 
      firstName AS "First Name", 
      lastName AS "Last Name",
      dependent_name AS "Dependent Name" 
FROM employee,dependent 
WHERE ssn=essn;

If somebody could guide me in the right direction, that would be greatly appreciated.

1

1 Answer 1

2

Use a left join to get all rows from the first table even if there are no matching in the second:

SELECT 
  firstName AS "First Name", 
  lastName AS "Last Name", 
  dependent_name AS "Dependent Name" 
FROM employee
LEFT JOIN dependent ON dependent.essn = employee.ssn;

I changed your implicit old-style join to an ANSI compliant explicit join too.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a bunch. This worked like I wanted it to. I am going to dig into what a LEFT JOIN does to expand my knowledge. Will vote as best answer once I am able to.
@dhint4 The link that eggyal provided is a really good explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.