CASE Priority Ordering In Order By

Sort tickets by urgency: a CASE expression returns the numeric priority used as the leading ORDER BY key, and ELSE catches unlisted statuses.

SqlData Fetching

Code

snippet
-- 业务优先级排序:状态不按字母序,而按紧急度序
-- CASE 返回的数字作为第一排序键,同优先级内再按 created_at 兜底
SELECT
    ticket_id,
    status,
    created_at
FROM tickets
ORDER BY
    CASE status
        WHEN 'outage'  THEN 0
        WHEN 'blocked' THEN 1
        WHEN 'open'    THEN 2
        WHEN 'review'  THEN 3
        ELSE 4
    END,
    created_at;

-- 分组报表里同样适用:未列出的新状态统一落进 ELSE 桶,不打乱顺序
SELECT
    status,
    COUNT(*) AS tickets
FROM tickets
GROUP BY status
ORDER BY
    CASE status
        WHEN 'outage' THEN 0
        ELSE 1
    END,
    tickets DESC;

Inside the snippet

Several statements share this file — SELECT, with tickets among the objects involved.

What the statements actually assemble: COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Using it

The tickets table is the working surface here.

Key statements

SELECT
status,
COUNT(*) AS tickets
FROM tickets
GROUP BY status
ORDER BY
CASE status
WHEN 'outage' THEN 0
ELSE 1
END,
tickets DESC;
SELECT
ticket_id,
status,
created_at
FROM tickets
ORDER BY
CASE status
WHEN 'outage'  THEN 0
WHEN 'blocked' THEN 1
WHEN 'open'    THEN 2
WHEN 'review'  THEN 3
ELSE 4
END,
created_at;

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`tickets`.