glog : cupucharm

[MySQL] 조건문 CASE 문 (LeetCode 1934) 본문

SQL

[MySQL] 조건문 CASE 문 (LeetCode 1934)

오이호박참외 2024. 10. 4. 13:00

👑 CASE 문

조건에 따라 다른 값을 반환할 수 있는 기능을 제공한다. 주로 SELECT, UPDATE, DELETE 문에서 사용한다.

문법은 아래와 같다.

CASE 
    WHEN 조건1 THEN 결과1
    WHEN 조건2 THEN 결과2
    ...
    ELSE 기본결과
END

🚨 주의 사항

✅ CASE 문은 반드시 END 로 끝나야 한다. (END로 종료되지 않으면 SQL 구문 오류 발생)

✅ ELSE 절은 선택 사항이지만, 생략할 경우 모든 조건이 만족하지 않을 때 NULL을 반환한다.

✅ 조건이 만족하는 경우, 해당 결과를 반환하고 이후 조건은 무시된다. (조건은 위에서 아래롤 평가됨)

✅ CASE 문에서 반환하는 모든 결과는 동일한 데이터 타입이어야 한다.

✅ CASE 문은 SELECT, WHERE, ORDER BY, UPDATE 등 다양한 위치에서 사용할 수 있다.


리트코드 LeetCode 1934

https://github.com/cupucharm/LeetCode/tree/b7c7d807abe30f6dd29a0dd4ce5c8b64298059d4/1934-confirmation-rate

 

LeetCode/1934-confirmation-rate at b7c7d807abe30f6dd29a0dd4ce5c8b64298059d4 · cupucharm/LeetCode

Collection of LeetCode questions to ace the coding interview! - Created using [LeetHub v3](https://github.com/raphaelheinz/LeetHub-3.0) - cupucharm/LeetCode

github.com

https://leetcode.com/problems/confirmation-rate/description/?envType=study-plan-v2&envId=top-sql-50

CASE WHEN c.action = 'confirmed' THEN 1 ELSE 0 END