I have a query which looks like this (actual query & tables are more complicated):
SELECT item.other_uuid, item.uuid, category.name
FROM item, category
WHERE ...
ORDER BY array_position(ARRAY[{'CDX', 'KDJ', 'PLM', 'OLA', 'OWK', 'CAT'}]::uuid[], item.uuid), category.name;
That gives me a list of category names in a particular order (uuid order passed by the array). For example:
789 CDX "Cat D"
123 KDJ "Cat A"
456 PLM "Cat B"
123 OLA "Cat F"
456 OWK "Cat X"
123 CAT "Cat Z"
What I'd like to do is add a DISTINCT ON 'item.other_uuid' to that query. So the resulting list would be:
789 CDX "Cat D"
123 KDJ "Cat A"
456 CAT "Cat B"
How can I achieve this? Postgres wants ORDER BY & DISTINCT to match but that wouldn't be the right order for my query.
I've tried to make that a subquery and use DISTINCT in the main query but the order isn't maintained...