Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Can I negate a condition in a where clause?

I want to check if a boolean is true, then decide in the WHERE clause what condition to use.

Say the boolean variable is @checkbool:

SELECT *
FROM TableA A
WHERE
    --if @checkbool is true, run this
    A.Id = 123

    --if @checkbool is false, run this
    A.Id <> 123

Is there a way to negate a condition? Like in C++ you can do if !(condition).

If not, what is the best way to solve this problem?

Thank you!

like image 798
Lok Avatar asked Aug 08 '13 20:08

Lok


People also ask

How do you negate a condition in SQL?

Combining AND, OR and NOT in SQL By using SQL NOT, you can negate a specified condition, which means the value must be the opposite of the defined condition to be selected. The syntax for defining an SQL NOT condition is simple: Just like AND and OR, SQL NOT is usually used in the WHERE clause.

How do I use the SQL not condition?

This SQL tutorial explains how to use the SQL NOT condition with syntax and examples. The SQL NOT condition (sometimes called the NOT Operator) is used to negate a condition in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement. This is the condition to negate.

What is a where clause in SQL?

FROM table_name WHERE condition; The WHERE clause appears immediately after the FROM clause. The WHERE clause contains one or more logical expressions that evaluate each row in the table. If a row that causes the condition evaluates to true, it will be included in the result set; otherwise, it will be excluded.

What is the use of not in SQL?

Description. The SQL NOT condition (sometimes called the NOT Operator) is used to negate a condition in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.


2 Answers

SQL's equivalent of ! in C is NOT. However, in your case you want something else: you need to build a condition that decides between the two choices based on the value of @checkbool, like this:

SELECT *
FROM TableA A
WHERE (    (@checkbool) AND (A.Id =  123))
   OR ((NOT @checkbool) AND (A.Id <> 123))
like image 100
Sergey Kalinichenko Avatar answered Oct 04 '22 04:10

Sergey Kalinichenko


Here is one solution:

IF @Checkbool = 1
     SELECT * FROM Table A WHERE A.Id = 123
ELSE
     SELECT * FROM Table A WHERE A.Id <> 123

Here is another using just the WHERE Clause:

SELECT * 
FROM Table A 
WHERE
     (@Checkbool = 1 AND A.Id = 123)
     OR
     (@Checkbool = 0 AND A.Id <> 123)

Everything you put in the where clause needs to be in the form of an expression. Thus, the solution in this case is to write the condition in the form of an expression.

Hope this helps. :)

like image 36
Mikhael Loo Avatar answered Oct 04 '22 06:10

Mikhael Loo