Syntax Error While Using Case Statement in Spark SQL - mysql

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.

Related

Use one conditional function with more than one execution path if condition is met

I have the following case statement,
case WHEN
DATE(DATE_SUB(DATE_ADD(startDate, INTERVAL 6 MONTH),INTERVAL 1 WEEK)) = DATE(NOW()) THEN
CONCAT('You should by now have held a probationary review meeting.','You must get approval from the owners.')
END AS 'emailSentence'
The emailSentence will hold the concatenation of the two sentences. This emailSentence is referenced externally by another program.
I would like to use a different alias such as emailSentence2 and refer to the second part of concat i.e. 'You must get approval from the owners.' all within the same case statement. That would mean getting rid of concat which is fine. Is there a way of doing this ? If there is a way of doing this without using a case statement i would be happy to hear that too, but it needs to be conditional statment/function.
I do realise i can use a different case statement with the same condition but that would mean multiple case statments making the sql bloated.
SQL has a very strict syntax. With * as the only exception, listing a column in a SELECT will always look like
select ... , expression [[as] alias], ...
case will be part of expression, so it cannot span multiple columns, and cannot add/return multiple columns.
Anecdotal, SQL doesn't care too much about the code being short. For example, doing something like select <expression> as value1, <expression> as value2, value1+value2 as value3 or select <expression> as value ... where value=0 is not allowed, you would have to repeat those expressions.
Nevertheless, if you really don't want to repeat that expression, you could use a left join instead and have the comparison (once) as the on-condition:
select ..., e.emailSentence, e.emailSentence2 -- or just e.*
from ...
left join (
select
'You should by now have held a probationary review meeting.' as emailSentence,
'You must get approval from the owners.' AS emailSentence2
) e on DATE(DATE_SUB(DATE_ADD(startDate, INTERVAL 6 MONTH),INTERVAL 1 WEEK)) = DATE(NOW())
To clarify: if the on-condition is not true, the values will be null, just as in the case-version.
This solution will have it's own limitations, but might be an option for you.

IF STATEMENT IN MYSQL INSERT is not working

Please, I do not understand why it is not working:
SET #key = (SELECT customer.key_stamp FROM customer WHERE customer.key_stamp = "0000");
CASE WHEN (#key > 0) THEN
INSERT INTO transaction
(transaction.to, transaction.key, transaction.type, transaction.cost_bitcoin, transaction.quantity)
VALUES ("0000", "f5rwsd", 2, 0.0075,
(500000 +
(
(SELECT bonus.amount
FROM bonus
WHERE 500000 BETWEEN bonus.min_quantity AND bonus.max_quantity
) / 500000
) * 100))
END;
I tried the CASE STATEMENT, but it still does not work, and i can't understand the issue.
Please help.
CASE is not a valid MySQL statement. (It's not a valid statement outside the context of a MySQL stored program.)
"Why it is not work"... is because it's not valid SQL.
A CASE expression can be used in a SQL statement where an expression is allowed. (In SQL, an expression returns a value of a particular datatype.)
As an example of using a CASE expression in a SQL statement, something like this:
SELECT CASE WHEN #key > 0 THEN 'somevalue' ELSE 'othervalue' END AS foo
in fact now i use just an sql functions, and it work now, all work, switch case mysql, if else statement mysql, and loops too, like while do, or LOOP ITERATE, all work, just need use it in sql functions, or sql procedure.

How to put a CASE statement in the GROUP BY clause

I've got a table with one column that is a comma separated list of possible values. I'd like to query, grouped by each individual possible value.
As a test, I've written this query:
SELECT
`Please_identify_which_of_the_following_classroom_hardware_you_c2`,
count(`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`) as count,
`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`
FROM
`data_Copy_of_Faculty_survey_on_technology_in_the_classroom_Respo`
GROUP BY
`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`,
CASE
WHEN `Please_identify_which_of_the_following_classroom_hardware_you_c2` LIKE '%Elmo%' THEN 'Elmo'
END
(Please excuse the column names, they're auto-generated)
I know the CASE statement isn't incredibly useful at this point, but I'm just trying to get the query to run. I'm getting an error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'THEN 'Elmo' END' at line 10
For the life of me I can't find what's wrong with the query. Any insight would be appreciated.
EDIT: I've tried with single and double quotes - same problem regardless of the quote used.
UPDATED: As Mark has pointed out, even if I get this query to parse, the results won't be what I'm looking for. I'm still curious why this doesn't parse, but the query is not the solution to my initial problem.
The reason you're seeing issues is that your GROUP BY attributes didn't align with the SELECT attributes.
As the MySql docs put it:
"SQL92 and earlier does not permit queries for which
the select list, HAVING condition, or ORDER BY list refer
to nonaggregated columns that are neither named in the GROUP BY
clause nor are functionally dependent on (uniquely determined by)
GROUP BY columns"
In other words, since the ...c2 attribute was not "functionally dependent on" your CASE ... END attribute, there was a mismatch between SELECT and GROUP BY, and thus an error.
One way to mitigate the error (and possibly make the query more readable), is to do the CASE once and then do the aggregates on the resulting relation.
SELECT c2, tec1, COUNT(tec1)
FROM
(SELECT
CASE
WHEN `Please_identify_which_of_the_following_classroom_hardware_you_c2` LIKE '%Elmo%'
THEN 'Elmo'
ELSE
`Please_identify_which_of_the_following_classroom_hardware_you_c2`
END AS c2,
`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`) AS tec1
FROM
`data_Copy_of_Faculty_survey_on_technology_in_the_classroom_Respo`) t
GROUP BY c2, tec1
Try This:
SELECT
CASE
WHEN `Please_identify_which_of_the_following_classroom_hardware_you_c2` LIKE '%Elmo%' THEN 'Elmo'
ELSE `Please_identify_which_of_the_following_classroom_hardware_you_c2`
END AS `Please_identify_which_of_the_following_classroom_hardware_you_c2`,
count(`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`) as count,
`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`
FROM
`data_Copy_of_Faculty_survey_on_technology_in_the_classroom_Respo`
GROUP BY
`_How_would_you_rate_your_overall_skill_in_using_educational_tec1`,
CASE
WHEN `Please_identify_which_of_the_following_classroom_hardware_you_c2` LIKE '%Elmo%' THEN 'Elmo'
ELSE `Please_identify_which_of_the_following_classroom_hardware_you_c2`
END

Along with which clauses in MySQL 'NOT' keyword can be used? Indeed specifically in MySQL

There is a keyword 'NOT' in MySQL.
For example, consider the below SQL query in MySQL :
SELECT * FROM Customers WHERE Country NOT LIKE '%land%';
See in above query 'NOT' keyword is used along with the LIKE keyword.
I want to know along with which clauses and keywords the 'NOT' keyword is used specifically in MySQL database queries.
Can someone please provide me help in this regard with example queries?
Thank you.
The NOT keyword can be used with any boolean expression (and hence actually with any numeric expression but let's not go there). For example:
where not (a = b)
where not (a is null)
where not (a in ('x', 'y', 'z'))
where not (a = 1 or b = 2 or c = 3)
That is the keyword not. There are at least three other infix operators that contain not: not in, not like, and is not null. For these, the not is part of the operator name, not a separate keyword.

Does MySQL "lazy evaluate" when having queries inside IF (conditional) statements? [duplicate]

I need to query data from a second table, but only if a rare set of conditions in the primary table is met:
SELECT ..., IF(a AND b AND c AND (SELECT 1 FROM tableb ...)) FROM tablea ...
a, b, and c conditions are almost always false, so my thinking is the subquery will never execute for most rows in the result set and thus be way faster than a join. But that would only true if the IF() statement short circuits.
Does it?
Thanks for any help you guys can provide.
The answer is YES.
The IF(cond,expr_true,expr_false) within a mysql query is short-circuited.
Here a test, using #variables to prove the fact:
SET #var:=5;
SELECT IF(1 = 0, (#var:=#var + 1), #var ); -- using ':=' operator to modify 'true' expr #var
SELECT IF(1 = 1, #var, (#var:=#var + 1) ); -- using ':=' operator to modify 'false' expr #var
SELECT #var;
The result is '5' from all three SELECT queries.
Had the IF() function NOT short circuited, the result would be a '5' from SELECT #1, and '6' from SELECT #2, and a '7' from the last "select #var".
This is because the 'true' expression is NEVER executed, in select #1 and nor is the false expression executed for select #2.
Note the ':=' operator is used to modify an #var, within an SQL query (select,from, and where clauses). You can get some really fancy/complex SQL from this. I've used #vars to apply 'procedural' logic within a SQL query.
-- J Jorgenson --
With J. Jorgenson's help I came up with my own test case. His example does not try to short circuit in the condition evaluation, but using his idea I came up with my own test and verified that MySQL does indeed short-circuit the IF() condition check.
SET #var:=5;
SELECT IF(1 = 0 AND (#var:=10), 123, #var); #Expected output: 5
SELECT IF(1 = 1 AND (#var:=10), #var, 123); #Expected output: 10
On the second example, MySQL is properly short-circuiting: #var never gets set to 10.
Thanks for the help J. Jorgenson!
It depends.
IF doesn't short-circuit such that it can be used to avoid truncation warnings with GROUP_CONCAT, for example in:
set ##group_concat_max_len = 5;
select if(true or #var:=group_concat('warns if evaluated'), 'actual result', #var);
the result will be 'actual result' but you'll get a warning:
Warning (Code 1260): Row 1 was cut by GROUP_CONCAT()
which is the same warning you get with less trivial GROUP_CONCAT expressions, such as distinct keys, and without the IF at all.
Try it in the SQL analyzer. If you want to be on the safe side and not have to trust the database to work one way (and not to change that behavior ever in new versions), just make two queries and do the IF programmatically.