How does the CASE expression work in SQL and where can you use it?
How does the CASE expression work in SQL and where can you use it?
CASE is SQL's conditional expression (not a statement): it returns the value of the first matching branch. If nothing matches and there is no ELSE, the result is NULL.
-- searched CASE: arbitrary conditions
SELECT name,
CASE WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
ELSE 'C'
END AS grade
FROM students;
-- simple CASE: compare one expression with values
SELECT CASE status WHEN 'P' THEN 'Pending' WHEN 'D' THEN 'Done' ELSE 'Unknown' END FROM tasks;
SELECT: derive labels and buckets.ORDER BY: custom order, for example pinned rows first:ORDER BY CASE WHEN status = 'urgent' THEN 0 ELSE 1 END, created_at
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.