Combine Two Tables

Anush krishna .V
2 min readNov 30, 2020

--

SQL Leet Code Series — Easy

Source: https://unsplash.com/photos/1K6IQsQbizI

SQL Schema

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

Approach :

From the title, it's pretty clear that we are expected to get data from multiple tables from a database.

From the given information PearsonId and AddressId are Primary keys

We are asked to create a SQL Query that will provide FirstName, LastName, City, State for each person in the Person table regardless if there is an address for each of those people.

Using Left Join would be the best option to go for since we want every row from the first table, regardless of whether there is a matching row from the second table.

Solution:

Note: The solution might slightly differ from DataBase to DataBase the concept and the approach are often the same. Solution for Oracle Sql 11.2.

SELECT P.FirstName,
P.LastName,
A.City,
A.State
FROM Person P
LEFT JOIN Address A
ON P.PersonId = A.PersonId;

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Anush krishna .V
Anush krishna .V

Written by Anush krishna .V

MS Data Science @RIT | Ex-Data Engineer @Metabob | Global Finalist IBM CFC | Data Engineering & Science | Looking for an internship

No responses yet

Write a response