[MySQL]CASE vs IF Statement vs IF function

Dazz_heyDay ·2023년 8월 11일
0

SQL

목록 보기
20/20
post-thumbnail

If Function

: less flexible from of the case expression

select if(username = 'darxysaq', 'high', 'low') as awesomeness

Case

select case 
		when username = 'darxysaq' then 'high' 
        else 'low' 
        end as awesomeness

Case allows more than one branch.

select case 
       when username = 'darxysaq' then 'high' 
       when username = 'john skeet' then 'medium' 
       else 'low' 
       end as awesomeness

If Statement

:if statement is an entirely different beast.

  • The IF-THEN-ELSE statement is used to execute code when a condition is TRUE, or execute different code if the condition evaluates to FALSE.
IF condition1 THEN
   {...statements to execute when condition1 is TRUE...}

[ ELSEIF condition2 THEN
   {...statements to execute when condition1 is FALSE and condition2 is TRUE...} ]

[ ELSE
   {...statements to execute when both condition1 and condition2 are FALSE...} ]

END IF;
CREATE FUNCTION GetAwesomeness (username varchar(50))
RETURNS varchar(20)
BEGIN
   IF username = 'darxysaq' THEN
      return 'high';
   ELSEIF username = 'john skeet' THEN
      return 'medium';
   ELSE
     return 'low';
   END IF;
END; //
profile
Why.Not.Now

0개의 댓글