Andrea Borzi Andrea Borzi - 2 years ago 100
SQL Question

What does this SQL statement produce?

I am having trouble finding documentation about this specific statement

SELECT IF (count(f.id)=0,1,0) as flgNew
FROM table f ON ...
WHERE ...


the table is joined with other tables and should return 1 if the entry in
f
is found or 0 if it has not been found.

So what does IF (count(f.id)=0,1,0) do?

Answer Source

It's basically the same as the following CASE statement:

SELECT CASE WHEN count(f.id) = 0
            THEN 1
            ELSE 0
       END AS flgNew
...

It checks to see if the expression count(f.id) = 0 is true, and returns the value 1 if it is, and 0 if it is not.

You can read more on the IF() function in the official docs here:

https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#function_if

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download