WITH var(prm_product_idT,prm_product_color_idT,prm_date_beforeT,prm_currency_idT) AS (SELECT 1001509266::bigint,1000000238813::bigint,'2011-01-01'::date,1::bigint) SELECT "PriceDetail".* FROM "PriceDetail" JOIN "PriceType" ON"PriceTypeID" = "PriceType"."ID" CROSS JOIN var v WHERE "ProductID" = v.prm_product_idT AND CASE WHEN v.prm_product_color_idT IS NOT NULL THEN "ProductColorID" = v.prm_product_color_idT ELSE "ProductColorID" IS NULL END AND "PriceTypeID" IN (12,13,14,15) AND "Price">0 ORDER BY "PriceTypeID" LIMIT 1;