Comparison in the WHERE condition

  • Hi all,

    I would like to add some condition to the query but not for how it will be correct.

    For example, my query:

    SELECT Product_Id, Product_Name, Created_Date

    FROM Product

    I want to add condition: if product_id are 1 and 2 them created_date < 20220301, if not - any filtering.

    Could you please help me?

     

  • WHERE (ProductId in (1,2) AND Created_Date < '20220301') OR ProductId NOT IN (1,2)

    If you haven't even tried to resolve your issue, please don't expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.

  • Lets break this down into sets.

    You are combining two sets of data from this table:

    1. All Product rows where [product_id] > 2
    2. All Product rows where [product_id] is 1 or 2 and created_date < 20220301

    There's an intersection: Regardless of product_id, all rows with created_date < 20220301 are to be selected.

    SELECT ...
    FROM Product
    WHERE Product_Id > 2 OR create_date < '2022-03-01'

    Eddie Wuerch
    MCM: SQL

  • The code is simple enough so why not do it in a UNION ALL between two queries to get rid of the "OR"?

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.
    "Change is inevitable... change for the better is not".

    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)
    Intro to Tally Tables and Functions

  • Eddie Wuerch wrote:

    Lets break this down into sets.

    You are combining two sets of data from this table:

    1. All Product rows where [product_id] > 2
    2. All Product rows where [product_id] is 1 or 2 and created_date < 20220301

    There's an intersection: Regardless of product_id, all rows with created_date < 20220301 are to be selected.

    SELECT ...
    FROM Product
    WHERE Product_Id > 2 OR create_date < '2022-03-01'

    What happens if the ProductID is (for example) 10 and the date is also less than '2022-03-01'?

    Heh... never mind.  I see it.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.
    "Change is inevitable... change for the better is not".

    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)
    Intro to Tally Tables and Functions

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply