DEV Community

Cover image for Find Customer Referee | LeetCode | MSSQL
Retiago Drago
Retiago Drago

Posted on

Find Customer Referee | LeetCode | MSSQL

The Problem

The challenge involves a table, Customer.

Customer table:

id (PK) name referee_id
int varchar int

The goal is to write an SQL query to report the names of the customers that were not referred by the customer with id = 2.

Explanation

Here's an example for better understanding:

Input:

Customer table:

id name referee_id
1 Will null
2 Jane null
3 Alex 2
4 Bill null
5 Zack 1
6 Mark 2

Output:

name
Will
Jane
Bill
Zack

Will, Jane, Bill, and Zack were not referred by the customer with id = 2.

The Solution

We'll explore two SQL solutions that solve this problem with subtle differences. We'll discuss their differences, strengths, weaknesses, and structures.

Source Code 1

The first solution selects customers whose referee_id is not 2 or is null.

SELECT name
FROM Customer
WHERE
  referee_id != 2
  OR
  referee_id IS NULL
Enter fullscreen mode Exit fullscreen mode

This solution has a runtime of 740ms, outperforming 91.47% of other submissions.

solution1

Source Code 2

The second solution closely resembles the first. The only difference is the order of conditions in the WHERE clause. It first checks for null referee_ids before checking for referee_ids not equal to 2.

SELECT name
FROM Customer
WHERE
  referee_id IS NULL
  OR
  referee_id != 2
Enter fullscreen mode Exit fullscreen mode

The runtime for this solution is 741ms, beating 91.35% of other submissions.

solution2

Conclusion

Both solutions yield the desired outcome, but the first solution performs marginally better. Consequently, the ranking of solutions based on overall performance, from best to worst, is as follows: Source Code 1 > Source Code 2.

Your choice should depend on your specific requirements and performance expectations.

You can find the original problem at LeetCode.

For more insightful solutions and tech-related content, connect with me on my Beacons page.

ranggakd - Link in Bio & Creator Tools | Beacons

@ranggakd | center details summary summary Oh hello there I m a an Programmer AI Tech Writer Data Practitioner Statistics Math Addict Open Source Contributor Quantum Computing Enthusiast details center.

favicon beacons.ai

Top comments (0)