SQL
Conditional Data Ordering with CASE Statement
Implement complex sorting logic in SQL using the `CASE` statement to prioritize or categorize records based on multiple conditions for display in search results or lists.
SELECT
id,
name,
status,
priority
FROM
tasks
ORDER BY
CASE status
WHEN 'urgent' THEN 1
WHEN 'pending' THEN 2
WHEN 'completed' THEN 3
ELSE 4
END,
priority DESC,
name ASC;
How it works: This snippet demonstrates how to apply custom sorting logic using a `CASE` statement within the `ORDER BY` clause. It assigns a numerical priority to different task statuses, ensuring 'urgent' tasks appear first, followed by 'pending', then 'completed', and finally any other status. Subsequent `ORDER BY` clauses (`priority DESC`, `name ASC`) provide secondary and tertiary sorting criteria for tasks within the same status group.