1

I have a column in a database table that may contain one of a limited amount of strings: ["Recht", "Abteilung", "Strecke", "Stelle", "Gemarkung", ...].

I want to perform queries to the table that order the result according to this column, but not alphanumerical but user-defined, i.e. "Recht" before "Abteilung" followed by "Strecke" ...

Is it possible to use a user-defined order like this?

2
  • 1
    order by case when column='Recht' then 1 when column='Abteilung' then 2 end case Something like this Commented Jun 4, 2021 at 7:45
  • No need to downvote though, this is a valid question with a useful answer. Commented Jun 4, 2021 at 7:48

1 Answer 1

2

A simple way to do this in Postgres uses arrays:

order by array_position(array['Recht', 'Abteilung', 'Strecke', 'Stelle', 'Gemarkung'], 'a_column') nulls last

The use of an array makes the logic quite concise -- and more maintainable. The array can also be passed in as a parameter, which can be quite convenient.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.