Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require if in where condition SQL

Tags:

sql

I want to fetch the data based on the key_column in the table. I am having a procedure where i am passing the key character. If the key is 'A' only those records with key as 'A' should get selected . For any other key character other than 'A', I need all the records except the rows with the key_Column value 'A'

sample code:

select * from tab1
where 
if (@key_Char = 'A') Then key_Column=@key_Char 
ELSE key_Column <>@key_Char 
like image 463
nandyec28 Avatar asked Nov 01 '12 06:11

nandyec28


People also ask

Can I use if statement in WHERE clause?

IF… ELSE clause is very handy and whenever you need to perform any conditional operation, you can achieve your results using it. But there are some limitations in IF… ELSE, and one of the limitations is that you cannot use it in WHERE clause.

Can we write SQL query in if condition?

We can use SQL IF statement without ELSE as well. In the following, the expression evaluates to TRUE; therefore, it prints the message. If the expression evaluates to FALSE, it does not return any output. We should use ELSE statement so that if an evaluation is not TRUE, we can set default output.

How do I add an IF condition in SQL query?

IF condition in SQL IF() function is passed with two parameters, one for true and other for false. The function returns one value if a condition is TRUE, and another value if the condition is FALSE.

Can I use having instead of WHERE in SQL?

To sum up this tutorial, remember the simple rule: If you need to work with aggregate functions, use GROUP BY and HAVING. And if you need to apply general conditions, use WHERE.


1 Answers

You can try this

select * from tab1
where (@key_Char = 'A' AND key_Column='A') OR
      (@key_Char <> 'A' AND key_Column <> 'A')
like image 147
Yograj Gupta Avatar answered Oct 15 '22 09:10

Yograj Gupta