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.
Code
-- 报表按流程语义排序,而不是按字母序: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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Case ConverterConvert text between lowercase, uppercase, title, sentence, camelCase, snake_case, and kebab-case while preserving Unicode letters and numbers.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables does this file reference?
- `tickets` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.