Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to convert an int or null to boolean value in an SQL query?

What is the best way to convert an int or null to boolean value in an SQL query, such that:

  • Any non-null value is TRUE in the results
  • Any null value is FALSE in the results
like image 891
Thomas Bratt Avatar asked Oct 07 '08 11:10

Thomas Bratt


People also ask

Can Int be converted to Boolean?

You cannot cast an integer to boolean in java. int is primitive type which has value within the range -2,147,483,648 to 2,147,483,647 whereas boolean has either true or false. So casting a number to boolean (true or false) doesn't makes sense and is not allowed in java.

How do I CAST to Boolean in SQL?

You can use CAST() to convert any integer or floating-point type to BOOLEAN : a value of 0 represents false , and any non-zero value is converted to true . You can cast DECIMAL values to BOOLEAN , with the same treatment of zero and non-zero values as the other numeric types. You cannot cast a BOOLEAN to a DECIMAL .

IS NULL Boolean SQL?

Boolean Data Type: Literals true , false and unknown The difference between the literals null and unknown is that unknown is of type Boolean while null can take any type. Putting a not null constraint on a column of the SQL type Boolean makes it a classical two-valued Boolean.

How do you change true to false in SQL?

You can update boolean value using UPDATE command. If you use the BOOLEAN data type, MySQL internally convert it into tinyint(1). It can takes true or false literal in which true indicates 1 to tinyint(1) and false indicates 0 to tinyint(1).


1 Answers

To my knowledge (correct me if I'm wrong), there is no concept of literal boolean values in SQL. You can have expressions evaluating to boolean values, but you cannot output them.

This said, you can use CASE WHEN to produce a value you can use in a comparison:

SELECT      CASE WHEN ValueColumn IS NULL THEN 'FALSE' ELSE 'TRUE' END BooleanOutput  FROM      table  
like image 138
Tomalak Avatar answered Sep 19 '22 14:09

Tomalak