Your query is well-structured and accomplishes the goal of listing groups a user has with their respective roles, but it could be considered somewhat complex and potentially "grotesque" due to its length and multiple CTEs (Common Table Expressions). However, it's not necessarily bad - it's actually quite clever in how it handles the different types of user-group relationships.
Here's my analysis:
Strengths:
- It properly handles the different ways a user can be associated with groups (roles, members, followers)
- It uses a ranking system to prioritize the most significant relationship for each group
- It includes pagination support (LIMIT/OFFSET)
- It returns a total count which is useful for pagination
- The ordering makes sense (by role importance then by group ID)
Potential improvements:
- The query could be simplified by using a single CTE with a UNION ALL and a CASE expression to determine the role and rank
- The role_rank values could be defined as constants at the top for better maintainability
- You might consider adding comments to explain the purpose of each CTE
Here's a slightly more concise version that maintains all functionality:
WITH user_groups AS (
-- User with 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,
'role' as source_type
FROM user_group_roles ugr
JOIN sports_groups sg ON sg.id = ugr.group_id
WHERE ugr.user_id = $1
UNION ALL
-- Active members
SELECT
sg.id, sg.name, sg.description, sg.logo_filename, sg.group_photo_filename,
'member' as role,
5 as role_rank,
'member' as source_type
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
-- Followers
SELECT
sg.id, sg.name, sg.description, sg.logo_filename, sg.group_photo_filename,
'follower' as role,
6 as role_rank,
'follower' as source_type
FROM user_followed_groups ufg
JOIN sports_groups sg ON sg.id = ufg.group_id
WHERE ufg.user_id = $1
),
ranked_groups AS (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY role_rank) as rn
FROM user_groups
)
SELECT
id, name, description, logo_filename, group_photo_filename, role, role_rank,
COUNT(*) OVER()::bigint as total
FROM ranked_groups
WHERE rn = 1
ORDER BY role_rank, id
LIMIT $2 OFFSET $3;
Conclusion:
The query isn't "too long" for its purpose, but it could be slightly more concise. It's actually a good example of how to handle complex relationships in SQL. The main thing to consider is whether the performance is acceptable with your dataset size. If it is, then the query is perfectly fine as is.