HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Order by certain enum values first

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
orderenumfirstvaluescertain

Problem

I've got a table like:

╔═══╦════════════════════╦═════════════╗
║ID ║ type (enum)        ║ updated_at  ║
╠═══╬════════════════════╬═════════════╣
║ 1 ║ friend_request     ║  ║
║ 2 ║ new_article        ║  ║
║ 3 ║ article_read       ║  ║
║ 4 ║ article_invitation ║  ║
╚═══╩════════════════════╩═════════════╝


I would like to order the retrieved results by the value of the enum type.

Records with value friend_request and article_invitation for the type column should come first, then the rest. Everything together should be ordered by updated_at DESC.

Now, I know I can chain multiple order by properties, so f.e.

order by type desc, updated_at desc


will order for me by type and the result of that by the updated_at values. But how do I specify for certain values of the type column? Is that even possible?

Solution

You can use a CASE expression:

order by case "type"
            when 'article_invitation' then 1
            when 'new_article' then 2
            when 'article_read' then 3
            when 'friend_request' then 4
         end, 
         updated_at desc

Code Snippets

order by case "type"
            when 'article_invitation' then 1
            when 'new_article' then 2
            when 'article_read' then 3
            when 'friend_request' then 4
         end, 
         updated_at desc

Context

StackExchange Database Administrators Q#274386, answer score: 11

Revisions (0)

No revisions yet.