patternMajor
ORDER BY using custom priorities for text columns
Viewed 0 times
ordercolumnstextcustomprioritiesforusing
Problem
This is a sample table:
Both
What ways are possible? I could extract
name | cat
----------
hugo | sal
bob | mgr
mike | dev
jeff | mgr
john | devBoth
name and cat being Varchar.cat reflects a category for these names, but I like to assign a priority to them, followed by a query to list them all, ordered by this priority.What ways are possible? I could extract
cat into a second table, build a foreign key etc. But given my app is very simple and the structure might be non-changeable: What possibilities do I have to list the mgr names first, followed by the dev names, followed by the sal names?Solution
Assuming you can't change your structure, you can use a CASE statement in your ORDER BY:
If you can change your structure, however, you can create a
ORDER BY case cat when 'mgr' then 1 when 'dev' then 2 else 3If you can change your structure, however, you can create a
Category table including the category code and a ranking, join your sample table to the Category table and sort by this ranking.Code Snippets
ORDER BY case cat when 'mgr' then 1 when 'dev' then 2 else 3Context
StackExchange Database Administrators Q#83, answer score: 23
Revisions (0)
No revisions yet.