Combine Two Tables

Combine Two Tables

Table: Person

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| personId    | int     |
| lastName    | varchar |
| firstName   | varchar |
+-------------+---------+
personId is the primary key (column with unique values) 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 |
+-------------+---------+
addressId is the primary key (column with unique values) for this table.
Each row of this table contains information about the city and state of one person with ID = PersonId.

Write a solution 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 result format is in the following example.

LeetCode Problem - 175

-- Select the columns firstName, lastName, city, and state from the combined result of the Person and Address tables
SELECT firstName, lastName, city, state 
FROM Person
-- Perform a LEFT JOIN to include all records from the Person table and the matching records from the Address table
LEFT JOIN Address
-- Specify the condition for joining: match the personId in the Person table with the personId in the Address table
ON Person.personId = Address.personId;

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!