문제
Write a solution to find all customers who never order anything.
Return the result table in any order.
The result format is in the following example.
아무것도 주문하지 않은 사용자를 출력하면 된다.
쿼리
#1 NOT IN
SELECT
NAME AS CUSTOMERS
FROM
CUSTOMERS
WHERE
ID NOT IN (
SELECT
CUSTOMERID
FROM
ORDERS
);
#2 JOIN + IS NULL
SELECT
A.NAME AS CUSTOMERS
FROM
CUSTOMERS A
LEFT JOIN
ORDERS B
ON A.ID = B.CUSTOMERID
WHERE
B.CUSTOMERID IS NULL;
#3 NOT EXISTS
SELECT
NAME AS CUSTOMERS
FROM
CUSTOMERS A
WHERE
NOT EXISTS (
SELECT
1
FROM
ORDERS B
WHERE
B.CUSTOMERID = A.ID
);
NOT IN은 내부 서브 쿼리에서 하나라도 NULL이 있으면 전체 결과가 0이 되기 때문에 DB가 복잡한 로직을 자동으로 추가한다고 한다.
그래서 JOIN + IS NULL을 쓰거나 NOT EXISTS를 권장한다고 한다.
문제 출처
https://leetcode.com/problems/customers-who-never-order/
'Study > SQL' 카테고리의 다른 글
| [LeetCode] 185. Department Top Three Salaries (0) | 2025.11.27 |
|---|---|
| [LeetCode] 184. Department Highest Salary (0) | 2025.11.25 |
| [LeetCode] 182. Duplicate Emails (0) | 2025.11.25 |
| [LeetCode] 180. Consecutive Numbers (0) | 2025.11.19 |
| [LeetCode] 178. Rank Scores (0) | 2025.11.13 |