0
`mysql> select * from movies;
+----------+-------+---------+
| movie_id | title | watched |
+----------+-------+---------+
|        1 | bo    |       0 |
|        2 | NEW   |       0 |
|        3 | NEW 2 |       0 |
+----------+-------+---------+
CREATE TABLE MOVIES (
  movie_id INTEGER NOT NULL AUTO_INCREMENT,
  title VARCHAR(50) NOT NULL,
  watched BOOLEAN NOT NULL,
  PRIMARY KEY (movie_id)
);

` I am having to store the "watched" field as a tiny int instead of typical boolean, I am trying to find a way of converting it back to boolean when reading from table, so I dont have to loop through all responses and convert manually.

ie. {movie_id: 1, title: 'bo', watched: 0} ---> {movie_id: 1, title: 'bo', watched: false}

I have tried select cast but am unfamiliar with the syntax

2
  • You have to read the records into a domain object at some point though - so why not just cast the values then rather than in the db layer? Commented Nov 20, 2022 at 1:27
  • "I am having to store the "watched" field as a tiny int instead of typical boolean" => When doing SHOW CREATE TABLE movies, on the table where you have this field defined as BOOLEAN, you will notice the type of the field watched to be a tinyint(1). Commented Nov 20, 2022 at 10:15

2 Answers 2

1

MySQL saves Boolean as 0 and 1 as it handles all Boolean that way.

It is very practical, then you can add true or false from a comparison in a SUM without CASE WHEN or a FILTER

You need still to make a condition to give bak True or False, but they only text of course

SELECT
  movie_id , title , 
 CASE WHEN watched = 0 THEN 'False' ELSE 'True' END IF
Sign up to request clarification or add additional context in comments.

Comments

0

This is similar to 'IF' in 'SELECT' statement - choose output value based on column values

Borrowing from the answer there,

SELECT movie_id, IF (watched > 0, true, false) as bwatched, ...

Note that this assumes your schema still includes "NOT NULL" for watched. Without that (or some extra code) NULL would become false.

The way "IF()" works is IF(expression , value / expression if true, v /e if false)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.