MySQL 0607.sql
SELECT name
FROM SalesPerson
WHERE sales_id NOT IN (SELECT o.sales_id
FROM Orders o, Company c
WHERE o.com_id = c.com_id
AND c.name = 'RED')
Difficulty
and has an acceptance rate of about 66% (600k+ submissions).
Typical patterns to solve this problem:
- Database
AI Disclaimer
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.
Code Walkthrough
Overview
The provided SQL statement retrieves the names of salespeople whose sales_id does not appear in any order placed with a company named RED. It does this by filtering the SalesPerson table against a sub-query that extracts all sales_id values linked to orders for the target company. The logic is expressed in a single SELECT statement with a NOT IN predicate that references a derived set of identifiers.
Key Steps
The first step selects the name column from the SalesPerson table. This is the outer query that defines the result set.
SELECT name
FROM SalesPerson
The second step applies a filter that excludes any salesperson whose identifier is present in the sub-query result. The NOT IN operator implements this exclusion.
WHERE sales_id NOT IN ( ... )
The sub-query builds the list of sales_id values that must be excluded. It joins the Orders table with the Company table using the com_id foreign key, then restricts the rows to those where the company name equals RED.
SELECT o.sales_id
FROM Orders o, Company c
WHERE o.com_id = c.com_id
AND c.name = 'RED'
The combination of the outer filter and the inner selection yields the final list of salesperson names that have never been associated with an order for the specified company.
Edge Cases Handled
When the Orders table contains rows with a sales_id that is NULL, the NOT IN predicate automatically excludes those NULL values from the comparison set, preventing unintended matches. If the sub-query returns an empty result set because no orders exist for RED, the NOT IN condition evaluates to true for every row in SalesPerson, thereby returning all salesperson names. The query also correctly handles the situation where multiple orders reference the same sales_id; the sub-query’s result set is deduplicated by the database engine, ensuring that each identifier is considered only once in the exclusion test. Additionally, the use of an explicit equality comparison on c.name guarantees that only rows with an exact match to the literal string RED are considered, avoiding partial or case-insensitive matches unless the database collation dictates otherwise.
Performance Optimizations Observed
The query leverages a non-correlated sub-query, allowing the database optimizer to materialize the list of sales_id values once and reuse it for the NOT IN comparison, which reduces repeated scanning of the Orders and Company tables. The join condition o.com_id = c.com_id can be satisfied efficiently if indexes exist on the foreign key columns Orders.com_id and Company.com_id. An index on Company.name further accelerates the filtering of rows where the company name equals RED, limiting the number of rows that need to be examined in the join. Because the outer query only accesses the SalesPerson table and filters on its primary key sales_id, an index on SalesPerson.sales_id enables rapid exclusion of matching identifiers. The use of the NOT IN construct, when the sub-query result set is guaranteed to be free of NULLs, permits the optimizer to transform the predicate into a semi-join operation, which can be executed with hash or merge join strategies for large data volumes. These index choices and the non-correlated nature of the sub-query together provide a solid foundation for efficient execution without additional query rewriting.
ELI5 - Simplified Explanation
Imagine a big toy box filled with files about all the folks who sell toys. The code acts like a detective looking for a specific group of people. First, the detective goes to the list of companies to find the one named RED. Once the detective finds that company, it looks at all the orders to see which sellers helped that specific company. After making a list of those sellers, the detective goes back to the master book of all salespeople and picks out everyone whose name is not on the list of people who worked with RED. It is just like asking to see the names of all the helpers who have never played with the red building blocks.
Code Quality
Complexity Analysis
Other Solutions
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 | C++ | Java | Python | TS | |
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| LeetcodeHelp | C++ | Java | Python | |||
| Progiez | C++ | Java | Python | |||
| github | everthis | SQL | ||||
| lzl124631x | SQL | |||||
| suxrobGM | SQL | |||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| LeetcodeHelp | C++, Java, Python | |||||
| Progiez | C++, Java, Python | |||||
| everthis | SQL | |||||
| lzl124631x | SQL | |||||
| suxrobGM | SQL |
Videos
Solved On The Same Day
- problem 175: Combine Two Tables
- problem 181: Employees Earning More Than Their Managers
- problem 182: Duplicate Emails
- problem 183: Customers Who Never Order
- problem 193: Valid Phone Numbers
- problem 196: Delete Duplicate Emails
- problem 197: Rising Temperature
- problem 203: Remove Linked List Elements
- problem 511: Game Play Analysis I
- problem 577: Employee Bonus
- problem 584: Find Customer Referee
- problem 586: Customer Placing the Largest Number of Orders
- problem 595: Big Countries
- problem 596: Classes With at Least 5 Students
- problem 610: Triangle Judgement
- problem 619: Biggest Single Number
- problem 620: Not Boring Movies
- problem 627: Swap Sex of Employees
- problem 1050: Actors and Directors Who Cooperated At Least Three Times
- problem 1068: Product Sales Analysis I
- problem 1075: Project Employees I
- problem 1084: Sales Analysis III
- problem 1141: User Activity for the Past 30 Days I
- problem 1148: Article Views I
- problem 1179: Reformat Department Table
- problem 176: Second Highest Salary
- problem 177: Nth Highest Salary
- problem 178: Rank Scores
- problem 180: Consecutive Numbers
- problem 184: Department Highest Salary
- problem 192: Word Frequency
- problem 194: Transpose File
- problem 550: Game Play Analysis IV
- problem 570: Managers with at Least 5 Direct Reports
- problem 585: Investments in 2016
- problem 602: Friend Requests II: Who Has the Most Friends
- problem 608: Tree Node
- problem 626: Exchange Seats
- problem 725: Split Linked List in Parts
- problem 1045: Customers Who Bought All Products
- problem 1070: Product Sales Analysis III
- problem 1164: Product Price at a Given Date
- problem 1174: Immediate Food Delivery II
- problem 1193: Monthly Transactions I
- problem 1204: Last Person to Fit in the Bus
- problem 1321: Restaurant Growth
- problem 1393: Capital Gain/Loss
- problem 174: Dungeon Game
- problem 185: Department Top Three Salaries
- problem 218: The Skyline Problem
- problem 262: Trips and Users
- problem 601: Human Traffic of Stadium
Extra
- 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