Description
Table: Person
| Column Name | Type |
|---|---|
| personId | int |
| lastName | varchar |
| firstName | varchar |
personIdis the primary key column for this table.- This table contains information about the ID of some persons and their first and last names.
Table: Address
| Column Name | Type |
|---|---|
| addressId | int |
| personId | int |
| city | varchar |
| state | varchar |
addressIdis the primary key column for this table.- Each row of this table contains information about the
cityandstateof one person withID = PersonId.
Problem Statement:
Write an SQL query to report the first name, last name, city, and state of each person in the Person table. If the address of a personId is not present in the Address table, report null instead.
Return the result table in any order.
The query result format is in the following example.
Example 1:
Input:
Persontable:
| personId | lastName | firstName |
|---|---|---|
| 1 | Wang | Allen |
| 2 | Alice | Bob |
Addresstable:
| addressId | personId | city | state |
|---|---|---|---|
| 1 | 2 | New York City | New York |
| 2 | 3 | Leetcode | California |
Output:
| firstName | lastName | city | state |
|---|---|---|---|
| Allen | Wang | Null | Null |
| Bob | Alice | New York City | New York |
Explanation:
- There is no address in the
Addresstable for thepersonId = 1so we returnnullin theircityandstate. addressId = 1contains information about the address ofpersonId = 2.
Solution
In this case person and address information are stored in two separate normalized tables. This is quite common design in the real world. In this question, we need information from both tables (i.e. firstName, lastName from the Person table and city, state from the Address table). Therefore, it is clear that we need a join between these two tables.
Now, the problem states that even if the person does not have an address, we still need to output the person information. This indicates that we need a LEFT OUTER JOIN with the Address table. This will ensure that you include the person information even if they do not have an address.
Below is one way to solve this problem.
1SELECT firstName, lastName, city, state FROM Person
2 LEFT OUTER JOIN Address ON Person.personId = Address.personId;


Comments