Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert BIGINT UNSIGNED to INT

I know it is unorthodox and potentially dangerous to want to convert something from a larger to a smaller sized data type. However, in this case, it is extremely unlikely that the value of the BIGINT UNSIGNED column is ever larger than the maximum size of an INT column.

So, using MySQL, I'm reading the table structure. While reading the information_schema.columns.ordinal_position column, I realized that it is of type BIGINT UNSIGNED. Now, I want this as an INT instead for my processing purposes. I want to cast/convert the type in SQL.

CAST and CONVERT only allow me to change the sign of the data type, apparently.

SELECT CAST(ordinal_position AS SIGNED)
FROM information_schema.columns

I want the column specifically returned as an INT. E.g. chop the column at the maximum value of an INT and return that value.

For now I will just change the datatype after I pull the value back. But I'd like to know how to do it in SQL.

like image 416
Josh M. Avatar asked Jul 21 '12 19:07

Josh M.


People also ask

How do you convert BIGINT to INT?

BigInteger. intValue() converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int.

Is BIGINT signed or unsigned?

A large integer. The signed range is -9223372036854775808 to 9223372036854775807 . The unsigned range is 0 to 18446744073709551615 . SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE .

How do you convert BIGINT to float?

math. BigInteger. floatValue() converts this BigInteger to a float value. If the value returned by this function is too big for a magnitude to represent as a float then it will be converted to Float.

What does BIGINT 20 mean?

The "BIGINT(20)" specification isn't a digit limit. It just means that when the data is displayed, if it uses less than 20 digits it will be left-padded with zeros.


1 Answers

this article seems to have a solution:

Create the function that will perform the conversion:

CREATE FUNCTION BigToInt (n BIGINT) RETURNS INTEGER RETURN n;

As you can see, the function is very short and simple: It takes a BIGINT and immediately returns it as an ordinary integer. However, one consequence of this is that some of the data will be truncated down to the largest possible value for Int.

(presumably you can add "UNSIGNED" to the signature - if not you can still combine it with the cast you already have that removes the unsigned part).

like image 51
andrew cooke Avatar answered Oct 04 '22 04:10

andrew cooke