Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql if function - subquery as a condition [closed]

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?

like image 766
shealtiel Avatar asked Dec 12 '12 12:12

shealtiel


People also ask

Is subquery allowed in WHERE clause in MySQL?

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.

Can a subquery have WHERE conditions?

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.

Can we use if statement in SELECT query in MySQL?

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'.

Is subquery always executed first?

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.


3 Answers

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)

like image 103
Luca Rainone Avatar answered Oct 13 '22 00:10

Luca Rainone


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
like image 28
Devart Avatar answered Oct 12 '22 23:10

Devart


Enclose the subquery in parentheses:

SELECT IF ((SELECT COUNT(*) FROM mytable), 'yes', 'no');
like image 44
MichaelRushton Avatar answered Oct 12 '22 22:10

MichaelRushton