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,
Try this using CTE:
WITH user_data AS (
SELECT *,
LOWER(COALESCE(user_number, customer_number)) AS lower_number
FROM users
)
SELECT
CASE WHEN lower_number LIKE 'vip%' THEN NULL
ELSE COALESCE(user_badge, customer_badge)
END AS normal_badge,
CASE WHEN lower_number LIKE 'vip%' THEN NULL
ELSE expiration_date
END AS expiration_date,
CASE WHEN lower_number LIKE 'vip%' THEN NULL
ELSE COALESCE(user_number, customer_number)
END AS coalesced_number
FROM user_data;