MySQL - CASE vs IF Statement vs IF function - mysql

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"?

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.

Related

check if select statement is true in a function in pl/sql

so i have a table called cars designed like this: ID, Model, Category, Availability.
The categories are standard and luxury.
im trying to write a function that returns either a boolean or an int like this :
function(id)
if category == luxury;
return 1;
else return 0;
i did this select statement but i dont know if i can use it
SELECT (CASE WHEN Category = 'Luxury' THEN 1 ELSE 0 END) AS is_equal
FROM CARS
WHERE ID = 'TM63DTI';
I have to do it in pl/sql. its for a school project and im stuck at this point. I dont have an error with this select statement, i just dont really know how to use it. Maybe suggest an idea of how i can approach this.
PL/SQL means "Oracle", not "MySQL". I suggest you fix tags.
So, if it really is Oracle, then one option might be this:
create or replace function f_category
(par_id in cars.id%type)
return boolean
is
l_is_equal number;
begin
select case when category = 'Luxury' then 1
else 0
end
into l_is_equal
from cars
where id = par_id;
return l_is_equal = 1;
end;
/
Though, it is kind of difficult to use a function that returns Boolean in SQL, so - perhaps you'd also want to consider option that returns a number instead. It is simple to convert previous function to a new version:
create or replace function f_category
(par_id in cars.id%type)
return number
is
l_is_equal number;
begin
select case when category = 'Luxury' then 1
else 0
end
into l_is_equal
from cars
where id = par_id;
return l_is_equal;
end;
/
Now you can use it in SQL as e.g.
select f_category(par_id => 123) from dual;
or
select *
from cars
where f_category(id) = 1;

Need a single SELECT query in php

I am having three parameters $page, $date, $search. i need a single select sql query where i have to check all the three variables one by one whether any of these variables is having some value or not or if all of the three variables is having some value. According to which it will match from the database and give the result. Please help me out.
You can make where clause as follows in your Select query.(Below is MS SQL format, you can modify CASE statement equivalent with MY SQL)
SELECT * FROM TABLE (if more than one table, you can use join)
WHERE TABLE.search_COLUMN = case when #search <> '' then #search else TABLE.search_COLUMN end
AND
TABLE.page_value_COLUMN = case when #page_value <> '' then #page_value else TABLE.page_value_COLUMN end
AND
TABLE.date_‌​value_COLUMN = case when #date_‌​value <> '' then #date_‌​value else TABLE.date_‌​value_COLUMN end

using if statement in mysql query

I would like to use if statement in sql query :
what I want :
if(tractions_delivery.send_date_id !=0 ){
date_send_commodities.id = tractions_delivery.send_date_id
}
my query :
from
tractions_delivery,user_address,province,city,date_send_commodities,users
WHERE
tractions_delivery.tr_id = $tr_id
AND
tractions_delivery.address_id = user_address.id
AND
user_address.province_id = province.id
AND
user_address.city_id = city.id
AND
//not work
(tractions_delivery.send_date_id IS NOT 0 date_send_commodities.id = tractions_delivery.send_date_id)
AND
users.id = user_address.user_id
You could use the CASE-statement
SELECT
*
FROM
tractions_delivery,
user_address,
province,
city,
date_send_commodities,users
WHERE
tractions_delivery.tr_id = $tr_id AND
tractions_delivery.address_id = user_address.id AND
user_address.province_id = province.id AND
user_address.city_id = city.id AND
CASE WHEN tractions_delivery.send_date_id != 0 THEN date_send_commodities.id = tractions_delivery.send_date_id ELSE 1=1 END AND
users.id = user_address.user_id
You can only use if statements in stored procedures or functions. If you just write a sql statement unfortunately you cannot use if statements around the query. But you can use logic in the query itself, e.g.:
SELECT CASE WHEN col1 = col2 THEN'col1 equals col2' else 'col1 doesnt equal col2' ELSE
FROM table1
So around doesnt work, but in the field list you can create CASE WHEN ELSE END logic.
CASE or IF() operators can be of help.
Examples,
SELECT (CASE 1 WHEN 1 THEN 'One' WHEN 2 THEN 'Two' ELSE 'More' END) 'Result';
OR
SELECT IF(1=1, 'One', 'Two') 'Result';
These CASE and IF() operators can be used in the SELECT clause to conditionally interpret column values and return in the resultset.
Note: Do not confuse CASE operator here with 'CASE conditional syntax block' that ends with END CASE.

Scalar-valued function doesn't return expected result

I have created a scalar-valued function in Microsoft SSMS, it is as follows:
CREATE FUNCTION [dbo].[fGetCurrentBalFromName]
(
#Name NVarchar,
#CliFl Bit
)
RETURNS Money
AS
BEGIN
DECLARE #CurrentBal Money
select #CurrentBal=SUM(tt.Debt) from
(select case t.Clientfl when 1 then dbo.fGetClientNameFromId(t.AgentID)
else dbo.fGetSupplierNameFromId(t.AgentID)
end as Cli,
t.Clientfl,
case t.Clientfl when 1 then
case t.Incomfl
when 1 then t.Amount
else (-1)*t.Amount
end
else
case t.Incomfl
when 1 then (-1)*t.Amount
else t.Amount
end
end as Debt
from [Store].[dbo].[Money] t) tt where tt.Cli=#Name and tt.Clientfl=#CliFl
group by tt.Cli
RETURN #CurrentBal
END
When I execute
Select dbo.fGetCurrentBalFromName('Вали',1)
I get no(NULL) result.
But when I try to execute the query alone without parameters
select SUM(tt.Debt) from
(select case t.Clientfl when 1 then dbo.fGetClientNameFromId(t.AgentID)
else dbo.fGetSupplierNameFromId(t.AgentID)
end as Cli,
t.Clientfl,
case t.Clientfl when 1 then
case t.Incomfl
when 1 then t.Amount
else (-1)*t.Amount
end
else
case t.Incomfl
when 1 then (-1)*t.Amount
else t.Amount
end
end as Debt
from [Store].[dbo].[Money] t) tt where tt.Cli='Вали' and tt.Clientfl=1
group by tt.Cli
I get exactly what I want.
So what is the mistake I had done creating the scalar-valued function.
Any help will be appreciated!
You need to specify the size of the parameter #Name.
#Name NVarchar
Without size it defaults to 1 character.
Try something like this.
#Name NVarchar(100)
SQL Fiddle

CASE statement within a REPLACE statement in SQL Server 2008?

I have 3 variables which will be conditional when #path is not NULL i.e
#serverName,#analysisDB,#cubeName. Hence I used a CASE statement in the above SELECT statement. Similarly, for #path is not NULL the #cubename also needs to be conditional for LVL5.L5_CubeName (see REPLACE statement) but its inside a REPLACE statement and the CASE block becomes too complicated for the same. How do I write it if I want to do something like
CASE WHEN #path!='' THEN #cubeName ELSE LVL5.L5_CubeName in the REPLACE statement
SELECT LVL5.L5_Id,
CASE WHEN #path!='' THEN #serverName ELSE LVL5.L5_ServerName END [AnalysisServer],
CASE WHEN #path!='' THEN #analysisDB ELSE LVL5.L5_AnalysisDatabase END [AnalysisDatabase],
REPLACE(REPLACE(REPLACE(LVL5.L5_MDXQuery,'##Level1',ISNULL(#lvl1DataVal,'')),
'##Level2',ISNULL(#lvl2DataVal,'')),'##CubeName',ISNULL(#cubeName,'')) [MDXQuery],
LVL5.L5_ReplaceMDX [ReplaceMDX],
LVL5.L5_RefreshDate [RefreshDate],
LVL5.L5_ReportAttribute [ReportAttribute],
LVL5.L5_ReportTitle [ReportTitle]
FROM Report_SR_Level5 [LVL5]
WHERE L4_ID = #L4_ID ORDER BY LVL5.L5_DisplayOrder
Something like this:
CASE WHEN #path is not null or #path != ''
THEN REPLACE(REPLACE(REPLACE(LVL5.L5_MDXQuery,'##Level1',
ISNULL(#lvl1DataVal,'')),'##Level2',ISNULL(#lvl2DataVal,'')),'##CubeName',
ISNULL(#cubeName,'')) [MDXQuery]
ELSE Somethingelse END cubedata