Your current query absolutely works and is quite clear in spelling out each “source” of group-membership (roles, active membership, followers), but it is on the long side. You can make it more concise without losing readability by:
- Collapsing your three “source” CTEs into one UNION ALL
- Replacing the windowed ROW_NUMBER() trick with Postgres’s DISTINCT ON
- Keeping your total‐count window if you still need it
Here’s a refactored version:
-- Single CTE that unions all three sources
WITH all_sources AS (
-- 1) explicit roles
SELECT
sg.id
, sg.name
, sg.description
, sg.logo_filename
, sg.group_photo_filename
, ugr.role::text AS role
, CASE ugr.role
WHEN 'admin' THEN 1
WHEN 'organiser' THEN 2
WHEN 'treasurer' THEN 3
ELSE 4
END AS role_rank
FROM user_group_roles ugr
JOIN sports_groups sg ON sg.id = ugr.group_id
WHERE ugr.user_id = $1
UNION ALL
-- 2) active members
SELECT
sg.id
, sg.name
, sg.description
, sg.logo_filename
, sg.group_photo_filename
, 'member' AS role
, 5 AS role_rank
FROM group_members gm
JOIN sports_groups sg ON sg.id = gm.group_id
WHERE gm.user_id = $1
AND gm.status = 'active'
UNION ALL
-- 3) followers
SELECT
sg.id
, sg.name
, sg.description
, sg.logo_filename
, sg.group_photo_filename
, 'follower' AS role
, 6 AS role_rank
FROM user_followed_groups ufg
JOIN sports_groups sg ON sg.id = ufg.group_id
WHERE ufg.user_id = $1
)
SELECT
DISTINCT ON (id)
id
, name
, description
, logo_filename
, group_photo_filename
, role
, role_rank
, COUNT(*) OVER()::bigint AS total
FROM all_sources
ORDER BY
id -- pick one row per group
, role_rank -- lowest rank = highest priority
LIMIT $2
OFFSET $3;
Why this is “nicer”:
• You still see exactly how each source contributes rows (roles vs members vs followers).
• Only one CTE instead of four, which makes the “meat” of the query easier to scan.
• DISTINCT ON + ORDER BY replaces ROW_NUMBER(), which is a very common Postgres idiom for “pick the top-priority row per key.”
If you’re comfortable with JOINs, an even more advanced approach is to bring everything into one big SELECT with multiple LEFT JOINs and a single CASE/LEAST(…) to pick the highest-priority role, but that can get tricky to read.
In short:
– Your current version is correct and clear, but a bit verbose.
– The refactored version is shorter and uses well-known Postgres shortcuts (UNION ALL + DISTINCT ON).
– Pick whichever style your team finds most maintainable.