Monday, March 29, 2010

Control Flow Functions in Mysql

In this post i describe about how to use conditional operation in sql command for retrieving a record form table.
using these function record display according to it's condition.
  these operator are following:-

  1. Case
  2. If
  3. IfNull
  4. Nullif  
Case function:-
   syntax:-
                case condition when value_to_compare1 then result1 when value_to_compare2 then result2 else result3 end;

In above syntax  when condition value is equal to value_to_compare1 then result1 will output other check value_to_compare2 then result2 will output if both comparison fail then result3 execute.

example:-
CASE var WHEN NULL THEN SELECT 'Hi'; ELSE SELECT 'friend.'; END CASE;


If:-
Syntax:-
           select if(condition,true,false) from table ;
In above syntax if condition is true then true comes in result other wise false.


example:-
      select if(id=vlaue,emp_name,emp_dept) from emp where id=value;


IFNULL
    syntax:
           ifnull(value1,value2)
    
ivalue1 is not NULLIFNULL() returns value1; otherwise it returns value2.
 IFNULL() returns a numeric or string 
example:-SELECT IFNULL(1,0);
Nullif:-

   syntax:- nullif(value1,value2);
if value1=value2 then return null other vise value1






No comments:

Post a Comment