0

A database table "myTable" has the field "category";

SELECT DISTINCT "category" FROM "myTable" ORDER BY "category" ASC;
   A-Class
   T-Class
   Z-Class

OK, now I have to add a line 'undefined', e.g.

SELECT DISTINCT "category" FROM "myTable"  
UNION SELECT '>undefined<' 
ORDER BY "category" ASC;
   A-Class
   T-Class
   >undefined<
   Z-Class

I need the 'undefined' as first entry in the list and tried several characters like .,-_<>! at the first place, but all are ignored and the u is taken for the order.

Is there any simple option to achieve this, without showing a second column in the query?

2 Answers 2

1

Just use a subquery or a CTE:

with sortme as (
  select distinct category, category as category_sort 
    from "myTable"
  union 
  select 'undefined', ''
)
select category
  from sortme
 order by category_sort;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, perfect!!
0

You can type

order by case "category" when 'undefined' then 1 else 0 end, "category";

With special characters such as > before undefined, you could also cast category to bytea or use explicit collation.

1 Comment

Thank you, order by case is a good proposal and shorter.Unfurtunately, in some of my cases the text to be ORDERed is a SubSELECT of another table and I could not get this to work in combination with the UNION.

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.