Who can please explain the difference between CASE
-statement, IF
-statement and IF
-function?
What is the difference in terms of usage and "how it works"?
The MySQL CASE statement is faster in comparison to PHP if statement. The PHP if statement takes too much time because it loads data and then process while CASE statement does not.
The difference is pretty basic. The IF statement is useful if you're trying to evaluate something to a TRUE/FALSE condition. The CASE statement is used when you have multiple possible conditions. You could accomplish the same thing with nested IF statements, but that gets messy.
Main Difference between If-else and Switch CaseThe if-else statement is used to choose between two options, but the switch case statement is used to choose between numerous options. If the condition inside the if block is false, the statement inside the else block is executed.
CASE statements are preferred because: SQL: They are ANSI standard, making it portable to other databases without need for alteration.
From the manual, it looks like the if
function is just a less flexible form of the case
expression. For example, you could write:
select if(username = 'darxysaq', 'high', 'low') as awesomeness
And the equivalent with case
:
select case when username = 'darxysaq' then 'high' else 'low' end as awesomeness
But case
is more flexible. It allows more than one branch, like:
select case when username = 'darxysaq' then 'high' when username = 'john skeet' then 'medium' else 'low' end as awesomeness
And it can act like a switch
:
select case username when 'darxysaq' then 'high' when 'john skeet' then 'medium' else 'low' end as awesomeness
Now the if
statement is an entirely different beast. It is a control statement in MySQL procedures. The statement form looks like:
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; //
Here's a SQL Fiddle with the statement version. It looks like Mr Bean isn't all that he's made up to be!
A final note: the case
expression is standard SQL and works in most databases. The if
function is not standard SQL and will not work in other databases, like SQL Server or PostgreSQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With