I have this postgres query that is validating if the columns are null or not based on one codition, this is a normal query that is not requiring function, could be overkill a functional approach because this is unique scenario in the collection.
The query is working as expected but I want to shrink the logic if is possible.
CASE WHEN LOWER(COALESCE(users.user_number, users.customer_number)) LIKE 'vip%' THEN NULL
ELSE COALESCE(users.user_badge, users.customer_badge) END AS normal_badge,
CASE WHEN LOWER(COALESCE(users.user_number, users.customer_number)) LIKE 'vip%' THEN NULL
ELSE users.expiration_date END AS expiration_date,
CASE WHEN LOWER(COALESCE(users.user_number, users.customer_number)) LIKE 'vip%' THEN NULL
ELSE COALESCE(users.user_number, users.customer_number) END AS standard_user,
2
Answers
Try this using CTE:
You can pull the information out to a generated column or consider storing it in a separate one in the first place: Demo at db<>fiddle
Note that you can use
ilike
instead oflower() like lower()
to make it case-insensitive.If you flip the check in your
case when (condition) then null else (field) end
construct, you can save a few characters.case when not(condition)then(field)end
achieves the same because a missingelse
leads tonull
.You can also attach sets of fields with a
left join lateral
, all of which you nullify at once using a single join condition:Note that in all cases, if you don’t have
vip
prefix in non-nulluser_number
, but you do incustomer_number
, the user isn’t consideredvip
: coalesce picks and check only the first one.