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
``````

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

### 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
``````

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

## 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.