Skip to content
Advertisement

My custom order by in criteria query/jpql

Is it possible to do my custom order by using criteria query or jpql in Java? In my table, I have a column – number type(for now, this column includes numbers such as 1, 2, 3, 5, 10). I would like to sort result in this order 2, 5, 1, 10, 3.

How can I do it?

Advertisement

Answer

You have to use a CASE expression in your ORDER BY clause to implement this kind of “sort indirection”. In SQL and JPQL, this would be:

With the criteria API, using CriteriaBuilder.selectCase()

Of course, a much better solution is to normalise these values in a separate table that you can join just for the ordering:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement