I believe the following query is self explanatory:
SELECT IF (SELECT COUNT(*) FROM mytable > 0, 'yes', 'no');
Why doesn't it work? And how should I correct it?
A subquery is a SELECT statement coded within another SELECT statement. A subquery can return a single value or a list of values. A subquery can return multiple columns. You can use a subquery in a WHERE, HAVING, FROM and SELECT clause.
You can place the Subquery in a number of SQL clauses: WHERE clause, HAVING clause, FROM clause. Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression operator. It could be equality operator or comparison operator such as =, >, =, <= and Like operator.
Learn MySQL from scratch for Data Science and AnalyticsIt is quite possible to use MySQL IF() function within SELECT statement by providing the name of the column along with a condition as the first argument of IF() function. To understand it, consider the following data from table 'Students'.
Answer: D. The sub-query always executes before the execution of the main query. Subqueries are completed first. The result of the subquery is used as input for the outer query.
If your query is more complex and this is only a reduced problem, I think this is the better solution for you
SELECT IF ( (SELECT COUNT(*) AS counter FROM myTable HAVING counter>0) , 'yes', 'no')
so you can do more complex check (i.e. counter > N or multiple conditions)
It this what you want?
SELECT IF(COUNT(*) > 0, 'yes', 'no') FROM mytable;
1:
SELECT
t1.*,
(SELECT IF(COUNT(*) > 0, 'yes', 'no') FROM mytable) AS col1
FROM
table t1;
2:
SELECT
t1.*,
t2.*
FROM
table t1,
(SELECT IF(COUNT(*) > 0, 'yes', 'no') AS col1 FROM mytable) t2
Enclose the subquery in parentheses:
SELECT IF ((SELECT COUNT(*) FROM mytable), 'yes', 'no');
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