MySQL - if condition optimization - mysql

Just wondering, how this query will be handled by MySQL, will sum() calculated twice if sum(credits) != NULL or does MySQL has optimization in place for such queries.
select if(sum(credits)=NULL, 0, sum(credits)) from ......
Thanks

If won't work. The first condition is always false. The correct way to compare to NULL is IS NULL, not =.
Just use this construct:
select coalesce(sum(credits), 0)

Using IF
SELECT IF(sum(credits) IS NULL, 0 ,sum(credits)) .....
IF(expr1,expr2,expr3)
If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it returns expr3. IF() returns a numeric or string value, depending on the context in which it is used
Using IFNULL
SELECT IFNULL(sum(credits), 0) .....
Using COALESCE
SELECT COALESCE(sum(credits), 0) .....
Refer : MySQL Control Flow Functions

This is something we shouldn't worry about. With SQL we tell the DBMS what to do, not how to do it.
It is very, very likely that the DBMS will compute sum(credits) only once. It would seem rather stupid if not. However, this is not dictated by the SQL standard, so the DBMS programmers are free to choose how to code this. They could write the DBMS such that sum(credits) is computed twice. We cannot know whether they did or not, but as mentioned it is not likely and we shouldn't worry about it either.

Related

Syntax Error While Using Case Statement in Spark SQL

I want to run a case statement that runs different SELECT Statements Based on a condition in Spark SQL but not able to get the Syntax Right .
My SQL statement looks like this
registerTable(sql="SELECT CASE WHEN typedKeyword > '' THEN (SELECT * FROM `temp.sdf0` WHERE originalKeyword > ''AND keyword > '' AND deviceType = 'devicetype' ) ELSE (SELECT * FROM `temp.tes` WHERE originalKeyword > ''AND keyword > '' ) END ",alias="temp.test")
I don't know if CASE statement is supported in spark SQL so How can one achieve this
I've worked in nearly a dozen SQL and SQL-like dialects and I've never seen syntax like that. It looks like there's a core misunderstanding of what SQL clauses are supposed to do what.
The SELECT clause is for describing a projection of scalar elements. In many dialects you can issue subqueries - sometimes even correlated subqueries - in this clause, but you always must apply an operator that converts the result into a scalar value. For example:
SELECT (CASE WHEN EXISTS (SELECT foo FROM tbl) THEN 1 ELSE 0 END)
Here the "EXISTS" operator converts the uncorrelated subquery into a scalar boolean, so it's legal.
The lack of a FROM clause in the top level query is also a big red flag. It, or some analogue like Oracle's "dual", is legal in about half of the dialects I've seen, but if what you're trying to do is dynamically switch between two queries, you're almost certainly doing it wrong. juergen is right - what you probably meant to do is use 2 different queries.

In MySQL select query, checking for a string or checking for true in a where clause?

Consider the following table:
SELECT id, Bill_Freq, Paid_From, Paid_To, Paid_Dt, rev_code FROM psr_20160708091408;
The requirement is to fetch the row which has rev_code populated with the string **SUM**.
I've also noticed that for every row with rev_code populated as **SUM** its Bill_Freq won't be either null or zero.
So I wrote two queries to fetch the row with the lowest id
Query based on string check in where clause:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**";
Query based on true condition:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where bill_freq;
I haven't seen anyone use the second type, would like to know its reliability and circumstance of failure.
If by "second type" you mean a where clause with no explicit condition, then there is a good reason why you do not see it.
The SQL standard -- and most databases -- require explicit conditions in the where. MySQL allows the shorthand that you use but it really means:
where not billing_freq <=> 0
or equivalently:
where billing_freq <> 0 or billing_freq is null
(The <=> is the null-safe comparison operator.
The more important issue with your query is the min(). I presume that you actually want this:
select p.*
from psr_20160708091408 p
where rev_code = '**SUM**'
order by id
limit 1;
Also, you should use single quotes as string delimiters. That is the ANSI standard and there is rarely any reason to use double quotes.
Actually you can use the second type of query, but as your requirement is based on rev_code, it is always good to have condition with rev_code, because of 2 reasons
Bill_Freq having no NUlls or Zeros might be assumption based on current data
Even if it is true, in future, your application logic might change and it might have a scenario having NULL or zero, which will break your logic in future.
So my suggestion is to use first query with Rev_code
Please try to use below query
select
id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**" ORDER BY ASC LIMIT 0,1;
Thanks.
The requirement says it itself.
The requirement is to fetch the row which has rev_code populated with
the string '**SUM**'
In the scenario that bill_freq IS NOT NULL and rev_code is populated with
the string '**SUM**' then your logic will obviously fail.
Go for
where rev_code = "**SUM**";

In MySQL, which is more efficient: IFNULL or NULLIF?

These two MySQL functions do the same thing:
IFNULL(column_name, 'test') = 'test'
or
NULLIF(column_name, 'test') IS NULL
Which one is more efficient?
Purpose of NULLIF and IFNULL is not same, so performance comparison does not make any sense.
NULLIF is used to return null if the expression has a specific value, whereas IFNULL is used to return text if expression is null.
Example:
SELECT IFNULL(field,'empty') from table1;
Since null does not make much sense to end user.
insert into table1 (field) values (nullif(field,'empty'));
Since null has a special meaning in database.
They are both as efficient as each other - the functions have about the same overhead as each other.
But this is more efficient than either:
(column_name is null
or column_name = 'test')
Because the function doesn't need to be invoked.
You may find putting the more commonly encountered test first improves performance.
With questions like this, the simplest and more reliable way to discover relative performance is to just try them and compare query timings. Make sure you have production-sized and realistic-valued datasets so the test is fair.
they are used for different purpose, performance comparison doesn't make any sense.
select if(a,b,c); # a ? b : c # if a!=0 and a is not null then b else c
select ifnull(a,b); # a ? a : b # if a is not null then a else b
select nullif(a,b); # a=b ? null : a # if a=b then null else a
http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html

Is there a performance difference between `=` and `<=>`?

I've recently changed all my where conditions to use <=> instead of = because I need to check against nulls. Are there any performance concerns?
There is no real performance impact here is a test to verify for yourself
mysql> SELECT BENCHMARK(1000000, (SELECT SQL_NO_CACHE userId FROM Activity WHERE userId<=>42459204 LIMIT 1));
Make sure that you need to use <=>
NULL-safe equal. This operator
performs an equality comparison like
the = operator, but returns 1 rather
than NULL if both operands are NULL,
and 0 rather than NULL if one operand
is NULL.
If you just need to check the rvalue do
col=CONST AND CONST IS NOT NULL
or t1.col=t2.col
<=> is basically a shortcut to include OR (Val1 IS NULL AND Val2 IS NULL) or IS NOT DISTINCT FROM
It is an additional operation but the difference should be negligible unless you are SELECTing the data to be compared because otherwise the first SELECT returning NULL doesn't need to execute the second SELECT because the standard equality operator = will always yield false.
As #Dathan noted, make sure this is actually when you intend to do.

What does a WHERE clause of "sql was here" mean?

Can anyone help me understand or post any ideas concerning this where clause?
sql was here
I've changed the table name, but other than that, any idea what the developer was trying to do here?
There is nothing else after that, that's the where clause.
If (table.date_field = (select max(table2.exit_date) from table as table2)) is null the it'll return 1=1, which basically means there's no where clause at all.
Now let's look into that nasty expression. I can only assume that if "a = b" is not true then that's also equivalent to null, otherwise it seems like the first branch would always happen. It looks like it's trying to say "if the latest exit date is equal to the date field, select those, otherwise have no where clause". However, I don't think that this will work at all. It really looks like either way, each row will be selected.
The MySQL ifnull function returns the first argument if it is not null, otherwise the second argument. This looks like it tries to compare table.date_field to the max(table2.exit_date), and return true if the comarison was not possible due to nulls.
It looks to me like he is trying to find the row where table.date_field is equal to the maximum of table.exit_data. There is a check for null which I think would happen in any of these cases:
table is empty
all rows in table have exit_data set to NULL
table.date_field is NULL for the row in question
In any of these three cases, the row will be returned. I don't understand why he uses the string '1=1' instead of, to give some examples: 1=1, 1 or true, but it appears to work fine. In the first case I assume that there will be no rows in the result set anyway (depending on the rest of the query) so he was probably trying to handle one of the other two cases - I'd guess the last one.
This is only an explanation of what is happening. To understand why he is doing this, it would help if you gave a little more context.
MySQL is nonstandard in that true is really equal to the numeric value 1. Any expression that evaluates to true, or any nonzero value, satisfies the condition.
mysql> CREATE TABLE foo AS SELECT 1=1 AS f;
mysql> SHOW CREATE TABLE foo;
CREATE TABLE `foo` (
`f` INT NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=latin1
So the following WHERE clause is legal in MySQL, but not in most other SQL databases:
... WHERE 1;
Some people use 1=1 as a placeholder condition meaning true, but putting it in a string is meaningless because SQL expressions have no equivalent to an eval() function as other languages have. In this case, the leading character 1 in the string is implicitly cast to a numeric value 1, which is interpreted as true in MySQL. So it probably works as intended, but kind of by accident.
The use of IFNULL() is so that if either date_field or MAX(exit_date) is NULL, it returns the row. If you didn't use this function, then anything = NULL would evaluate as unknown, which means the row would not be returned.
It says basically if table.date_field = max exit date or if max exit_date is null or table.date_field is null return true. Will return false if max exit_date is not null and table.date_field is not null but they do not equal.