Problem 175

Abstract / Summary

Retrieve all rows from one table and matching rows from another using their shared key.

Note

The full problem description, including helpful examples, can be found on LeetCode.

MySQL 0175.sql

SELECT p.firstName, p.lastName, a.city, a.state
  FROM Person p LEFT JOIN Address a ON (p.personId = a.personId)
2 lines | 115 bytes | submitted September 6, 2023 | GitHub  

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 80% (2+ million submissions).

Typical patterns to solve this problem:
  • Database
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The query retrieves personal identifiers together with location details, preserving every person record even when a matching address is absent. It combines data from two tables, Person and Address, using a left outer join to ensure that the result set contains all rows from the Person table while optionally attaching address information.

Key Steps

Column Selection

The SELECT clause enumerates the fields that will appear in the output. The chosen columns are the first name and last name from the Person table and the city and state from the Address table.

SELECT p.firstName, p.lastName, a.city, a.state

Join Operation

The LEFT JOIN clause links each person to an address based on a shared identifier. The join condition matches the personId column from both tables, allowing rows from Person that lack a corresponding entry in Address to still appear with NULL values for the address fields.

FROM Person p LEFT JOIN Address a ON (p.personId = a.personId)

Result Construction

After the join, the query assembles the selected columns into a single result set. Because the join is left-outer, any person without an address will have NULL for a.city and a.state, while persons with one or more matching address rows will produce a row for each address match.

Edge Cases Handled

When a person does not have a related address record, the join condition fails to find a match, yet the left-outer semantics guarantee that the person’s name fields are still returned with NULL placeholders for city and state. This behavior prevents loss of person data in scenarios where address information is incomplete or optional.

If the Address table contains multiple rows for the same personId, the join will generate multiple result rows for that person, each paired with a distinct address. This multiplicity is inherent to the relational model and is correctly reflected in the output without causing errors.

The query also tolerates NULL values in the firstName or lastName columns of the Person table; such rows are included unchanged, and the presence of NULL in these fields does not affect the join operation because the join predicate references only the personId columns.

Performance Optimizations

The join predicate relies on equality between p.personId and a.personId. When both tables have indexes on the personId column, the database engine can perform an index-nested-loop or hash join efficiently, reducing the amount of data scanned.

A covering index on Address that includes personId, city, and state allows the join to be satisfied entirely from the index without accessing the full table rows, minimizing I/O and improving throughput.

Because the query selects only a subset of columns, the optimizer can apply a projection early in the execution plan, trimming unnecessary data before the join phase. This early projection reduces the volume of intermediate rows that must be processed.

The left-outer join is appropriate when address data is optional; using it avoids the need for a separate query to fetch persons without addresses, thereby eliminating an extra round-trip and consolidating the logic into a single execution path.

Overall, the combination of indexed join keys, potential covering indexes, and early column projection contributes to a streamlined execution that scales well with larger data volumes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a big collection of index cards that hold information about all the people in a giant city. Some of these cards have their names written on the front, and some of the cards have their home addresses attached to them. This code is like a magical robot helper that walks over to the cabinet to find this information. It looks at the pile of name cards first. Then, it carefully checks if each person has a matching address card that belongs to them based on a special secret number printed on both. It pulls the first name, last name, city, and state off these cards and lays them out side by side on a table so everything is easy to see at once. Even if a person does not have an address card in the pile, the robot still brings over their name so no one gets left out of the final list.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.41 | σ = 1.64

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python C++ Java TS
WalkCCC SQL
leetcode.ca SQL Python
LeetcodeHelp Python C++ Java
Progiez Python C++ Java
github everthis SQL
fsq SQL
gaosq0604 Python
keineahnung2345 SQL
lzl124631x SQL
muhammadfarhankt SQL
suxrobGM SQL
trung-hn SQL
AlgoMonster C++, Python, Java, TypeScript
WalkCCC SQL
leetcode.ca Python, SQL
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
everthis SQL
fsq SQL
gaosq0604 Python
keineahnung2345 SQL
lzl124631x SQL
muhammadfarhankt SQL
suxrobGM SQL
trung-hn SQL
21 links | 13 authors | 5 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'LeetCode 175: Combine Two Tables [SQL]'
Frederik Müller 9 mins
LeetCode 175: Combine Two Tables [SQL]
YouTube video 'Leetcode Problem 175. Combine Two Tables | Leetcode SQL Interview Problem with Solution'
The Engineer Guy 2.0 8 mins
Leetcode Problem 175. Combine Two Tables | Leetcode SQL Interview Problem with Solution
YouTube video 'Combine Two Tables | LeetCode Problem |'
GeekCoders 8 mins
Combine Two Tables | LeetCode Problem |
YouTube video 'Leetcode 175 Combine Two Tables (Python and SQL) [EASY]'
Ryan & Matt Data Science 7 mins
Leetcode 175 Combine Two Tables (Python and SQL) [EASY]
YouTube video '[MySQL] Leetcode 175. Combine Two Tables [SQL #5]'
Eric Programming 5 mins
[MySQL] Leetcode 175. Combine Two Tables [SQL #5]
YouTube video 'Leetcode 175 | Combine Two Tables | JOIN Interview Question'
Big Tech Mindset 5 mins
Leetcode 175 | Combine Two Tables | JOIN Interview Question
YouTube video 'Leetcode 175 - Combine Two Tables | Pandas Hands-on | #leetcode #python #pandas'
Anindya Dey 10 mins
Leetcode 175 - Combine Two Tables | Pandas Hands-on | #leetcode #python #pandas
YouTube video 'SQL LeftJoinVideo - Solution to LeetCode 175 - Combine Two Tables'
LEETCODE MASTER 4 mins
SQL LeftJoinVideo - Solution to LeetCode 175 - Combine Two Tables
YouTube video 'LeetCode SQL Interview Question: 175. Combine Two Tables'
DataFrenchy 4 mins
LeetCode SQL Interview Question: 175. Combine Two Tables
YouTube video 'How to Solve "175 Combine Two Tables" on LeetCode? - MySQL'
Becoming A Better Dev (with David) 5 mins
How to Solve "175 Combine Two Tables" on LeetCode? - MySQL
YouTube video 'Leetcode SQL 175 - Combine Two Tables'
Taniya Saini 5 mins
Leetcode SQL 175 - Combine Two Tables
YouTube video '175. Combine Two Tables (LeetCode, SQL)'
hakunamatasq 3 mins
175. Combine Two Tables (LeetCode, SQL)
YouTube video 'Combine Two Tables - SQL - MySQL - LeetCode'
Rowadz 5 mins
Combine Two Tables - SQL - MySQL - LeetCode
YouTube video 'Leetcode 175: Combine Two Tables Solution | SQL | Leetcode Interview Question'
The Knowledge Academy 3 mins
Leetcode 175: Combine Two Tables Solution | SQL | Leetcode Interview Question
YouTube video 'Leetcode |  175. Combine Two Tables | Time: O(N+M) | SQL'
Software Interviews Prep 4 mins
Leetcode | 175. Combine Two Tables | Time: O(N+M) | SQL
YouTube video 'Leetcode | Easy | 175. Combine Two Tables | SQL'
Software Interviews Prep 7 mins
Leetcode | Easy | 175. Combine Two Tables | SQL
YouTube video 'LeetCode 175 | Combine Two Tables | left join | SQL'
Sleepy Cracker 4 mins
LeetCode 175 | Combine Two Tables | left join | SQL
YouTube video 'Combine Two Tables SQL Solution – LeetCode 175 Explained (PostgreSQL Tutorial)'
Sumanshu Nankana 6 mins
Combine Two Tables SQL Solution – LeetCode 175 Explained (PostgreSQL Tutorial)
YouTube video '175. Combine Two Tables - SQL Problem - Leetcode Easy'
Vedanth Codes 5 mins
175. Combine Two Tables - SQL Problem - Leetcode Easy
YouTube video 'How to Solve Leetcode Database Problem 175 Combine Two Tables'
First Coast Math Clinic 10 mins
How to Solve Leetcode Database Problem 175 Combine Two Tables
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

25 easy 22 medium 5 hard
53 solutions   September 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality