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.
Code
-- 业务优先级排序:状态不按字母序,而按紧急度序
-- 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
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 objects does the SQL touch?
- `tickets`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.