Post

[MySQL] SELECT 결과가 비어있을 때 NULL을 반환하는 방법

일반 SELECT를 사용하면 결과가 없는 경우는 아예 출력되지 않는다.

결과 값이 없는 경우에도 빈 테이블이 아닌 NULL을 반환하고 싶다면, 다음과 같이 SELECT 절 안에 subquery를 넣는 중첩 SELECT 문을 사용해야 한다.


관련 문제: https://leetcode.com/problems/biggest-single-number/

1
2
3
4
5
6
7
SELECT (
    SELECT num
    FROM MyNumbers
    GROUP BY num
    HAVING COUNT(*) = 1
    ORDER BY num DESC LIMIT 1
) AS num;


관련 문제: https://leetcode.com/problems/second-highest-salary/

1
2
3
4
5
6
SELECT (
    SELECT DISTINCT salary
    FROM Employee
    ORDER BY salary DESC
    LIMIT 1, 1
) AS SecondHighestSalary;
This post is licensed under CC BY 4.0 by the author.