TransWikia.com

Filter with Combining and Negating Conditions with AND, OR, and NOT in T-SQL

Stack Overflow Asked by Jay Desai on December 20, 2021

I want to filter the table based on some combination of conditions. Please refer the below code:

SELECT COUNT(*)
FROM #New
WHERE (
          (
              ClientSource_No <> 283
              AND Suppress_Fg <> 1
          )
          OR
          (
              ClientSource_No <> 289
              AND Suppress_Fg <> 1
          )
      );


SELECT COUNT(*)
FROM #New
WHERE (
          (
              ClientSource_No <> 283
              OR ClientSource_No <> 289
          )
          AND Suppress_Fg <> 1
      );

I tried to filter the table 2 different ways. I want filter the table based on 2 conditions

  1. when ClientSource_No = 283 and Suppress_Fg = 1 then exclude the record

  2. when ClientSource_No = 289 and Suppress_Fg = 1 then exclude the record.

When I execute above query it filtered out all records who has Suppress_Fg = 1.

I don’t want to do self join the table or use NOT EXITS and exclude those records.

2 Answers

I think this is the simplest way to express the conditions:

SELECT COUNT(*)
FROM #New
WHERE NOT ( ClientSource_No IN (283, 289) AND Suppress_Fg = 1 )

Or as:

WHERE lientSource_No NOT IN (283, 289) OR Suppress_Fg <> 1 

Answered by Gordon Linoff on December 20, 2021

You could phrase this as a not condition, like:

where not (ClientSource_No in (283, 289) and Suppress_Fg = 1)

On the other hand, the logic you wanted to use required or conditions rather than and:

where ClientSource_No not in (283, 289) or Suppress_Fg <> 1

Answered by GMB on December 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP