ORDER BY CASE Encodes Status Rank

Sort rows by workflow meaning instead of alphabet: ORDER BY CASE maps each status to an explicit rank, with an ELSE bucket for unknown values.

SqlData Fetching

Code

snippet
-- 报表按流程语义排序,而不是按字母序:CASE 给每个状态一个显式位次
SELECT
    ticket_id,
    status,
    assignee
FROM tickets
ORDER BY
    CASE status
        WHEN 'open'     THEN 0   -- 新工单排最前
        WHEN 'progress' THEN 1
        WHEN 'blocked'  THEN 2
        WHEN 'done'     THEN 3   -- 已完成沉底
        ELSE 4                   -- 未知状态统一兜底,排序可预期
    END,
    ticket_id;

-- 注意:搜索式 CASE(无基础表达式)漏写 ELSE 时得到 NULL
-- ASC 排序下 NULL 默认排最后(NULLS LAST),未知项自然沉底

How the snippet works

The statement is SELECT, touching tickets.

What the statements actually assemble: an ORDER BY that fixes the output order.

Applying it

The tickets table is the working surface here.

Statements that matter

SELECT
    ticket_id,
    status,
    assignee
FROM tickets
ORDER BY
    CASE status
        WHEN 'open'     THEN 0   -- 新工单排最前
        WHEN 'progress' THEN 1
        WHEN 'blocked'  THEN 2
        WHEN 'done'     THEN 3   -- 已完成沉底
        ELSE 4                   -- 未知状态统一兜底,排序可预期
    END,
    ticket_id;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`tickets` — referenced directly, no join needed.