Similar Problems

Similar Problems not available

Combine Two Tables - Leetcode Solution


LeetCode:  Combine Two Tables Leetcode Solution

Difficulty: Easy

Topics: database  

The Combine Two Tables problem on Leetcode is a SQL problem that requires you to combine and present data from two tables. The problem statement is as follows:

"Table: Person

+-------------+---------+ | Column Name | Type | +-------------+---------+ | PersonId | int | | FirstName | varchar | | LastName | varchar | +-------------+---------+ PersonId is the primary key column for this table.

Table: Address

+-------------+---------+ | Column Name | Type | +-------------+---------+ | AddressId | int | | PersonId | int | | City | varchar | | State | varchar | +-------------+---------+ AddressId is the primary key column for this table.

Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:

FirstName, LastName, City, State"

Now let's see how we can solve this problem.


To combine data from two separate tables, we will use the LEFT JOIN clause in SQL. This will allow us to display all the records from the Person table and matching records from the Address table. However, these may not have corresponding records in the Address table.

To obtain the desired output, we will use the SELECT statement to retrieve the required columns from both tables and use the LEFT JOIN clause to join them. The final SQL query will look like this:

SELECT FirstName, LastName, City, State
FROM Person
ON Person.PersonId = Address.PersonId;

The above query will return all the rows from the Person table along with matching rows from the Address table. If there is no matching record in the Address table, the City and State fields will be null.

Note: In this example, Person.PersonId is the foreign key that connects the two tables.

The above SQL query will output the desired results. You can test this query on Leetcode's SQL editor and the output will match the expected output.

In conclusion, combining data from multiple tables in SQL requires the use of JOIN clauses. In the Combine Two Tables problem on Leetcode, we use the LEFT JOIN clause to obtain data from both tables.

Combine Two Tables Solution Code