Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF inside where clause - SQL

Can I have a if statement inside a where clause as in the follwing.

SELECT DISTINCT *
FROM product p
          INNER JOIN product_to_vendor pv
        ON pv.product_id = p.product_id
WHERE pv.vendor_id = @vendorId AND p.site_id = @siteId AND
            IF (@productStatus < 4)
        BEGIN 
            p.[rank] = @productStatus 
        END

thanks

like image 375
NilushiH Avatar asked Jun 09 '26 20:06

NilushiH


1 Answers

SELECT DISTINCT *
FROM product p
INNER JOIN product_to_vendor pv
        ON pv.product_id = p.product_id
WHERE     pv.vendor_id = @vendorId 
      AND p.site_id = @siteId 
      AND (@productStatus < 4 AND p.[rank] = @productStatus)

I not sure about your requirements, but here it is showing how if-else can be constructed from boolean logic. Just assume the if (condition) is just another statement for AND.

like image 152
cctan Avatar answered Jun 11 '26 22:06

cctan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!