Home > Enterprise >  How can I make a boolean from a SELECT statement in MYSQL?
How can I make a boolean from a SELECT statement in MYSQL?

Time:07-05

I have the following statement that returns 2 ids but how can I return true or false instead?

SELECT id FROM tablename WHERE datetime > NOW();

I also know there is this but I dont know how to adapt it to my case:

SELECT CASE WHEN 2 > 1 THEN 'True' ELSE 'False' END;

CodePudding user response:

As you have suggested, you may use a CASE expression here:

SELECT id, CASE WHEN datetime > NOW() THEN 'True' ELSE 'False' END AS outcome
FROM tablename;

You also could make the above more concise by using the IF() function:

SELECT id, IF(datetime > NOW(), 'True', 'False') AS outcome
FROM tablename;

CodePudding user response:

MySQL doesn't have an explicit boolean type, instead it treats ints as true/false. Non-zero and non-null values (eg, 1) is evaluated as true, 0 is evaluated as false.

Depending on the version of MySQL that you're using, you may have access to what the docs refer to as Boolean Literals, so TRUE and FALSE. These just evaluate to 1 and 0 respectively.

  • Related