13

I am transitioning from SQL Server to MySQL 5.1 and seem to be tripped up trying to create a table using a select statement so that the column is a bit.

Ideally the following would work:

CREATE TABLE myNewTable AS
SELECT cast(myIntThatIsZeroOrOne as bit) AS myBit
FROM myOldtable

However sql is very unhappy at casting as a bit. How can I tell it to select an int column (which I know only has 0s and 1s) as a bit?

Aaron Silverman
  • 22,070
  • 21
  • 83
  • 103
  • Why exactly you need to cast it to bit? Can't your use [TINY]INT? According to manual casting to BIT is not possible. – Mchl Aug 02 '11 at 22:22

3 Answers3

19

You cannot!

CAST and CONVERT only work to:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

No room for: BIT, BITINT, TINYINT, MEDIUMINT, BIGINT, SMALLINT, ...

However, you can create your own function cast_to_bit(n):

DELIMITER $$

CREATE FUNCTION cast_to_bit (N INT) RETURNS bit(1)
BEGIN
    RETURN N;
END

To try it yourself, you can create view with several conversions like:

CREATE VIEW view_bit AS
    SELECT
        cast_to_bit(0),
        cast_to_bit(1),
        cast_to_bit(FALSE),
        cast_to_bit(TRUE),
        cast_to_bit(b'0'),
        cast_to_bit(b'1'),
        cast_to_bit(2=3),
        cast_to_bit(2=2)

... and then describe it!

DESCRIBE view_bit;

Ta-dah!! Everyone is bit(1) now!!!

5

Try CONV(N,from_base,to_base)

Converts numbers between different number bases. Returns a string representation of the number N, converted from base from_base to base to_base. Returns NULL if any argument is NULL. The argument N is interpreted as an integer, but may be specified as an integer or a string. The minimum base is 2 and the maximum base is 36. If to_base is a negative number, N is regarded as a signed number. Otherwise, N is treated as unsigned. CONV() works with 64-bit precision.

for example.

select CONV(9, 10, 2);
A J
  • 3,970
  • 14
  • 38
  • 53
Charlie
  • 51
  • 1
  • 2
  • A bit is either zero or one, there is no base representation. I think you confused it with byte. – kurast May 30 '14 at 18:56
  • the base representation of a BIT column is 2. BIT(n) is a series of up to (n) 1-bit digits that can be either zero or one. so you could CONV to base 2, but I don't think it would work because it sounds like the result is an INT. – Ber Aug 07 '16 at 01:23
4

Try using case:

CREATE TABLE myNewTable AS
SELECT (case myIntThatIsZeroOrOne when 1 then true else false end) AS myBit
FROM myOldtable
Michael Logutov
  • 2,551
  • 4
  • 28
  • 32