If I want to take a string and create a table (this fails in strict mode),
CREATE TABLE g
AS SELECT CAST('2147483699' AS int);
How do I tell it that I want a bigint type? I'll also get an int(10)
type. SELECT
ing from it is humorous too,
+---------------------------+
| CAST('2147483699' AS int) |
+---------------------------+
| 2147483647 |
+---------------------------+
The data is actually wrong, and it silently failed. I know that's a known issue with this database having really poor defaults, but I how can I create the table as a bigint?
CREATE TABLE g
AS SELECT CAST('2147483699' AS bigint);
Doing that I get this error,
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'bigint)' at line 2
How do I cast an interger to a bigint?
PostgreSQL
With PostgreSQL, it's pretty simple. In addition to throwing an exception if you cast to an int
, you cast to a bigint
using
SELECT CAST('2147483699' AS bigint);
int8
------------
2147483699
Best Answer
Silently? Let's try:
MariaDB 10.1.32, default sql_mode (non-strict)
And the warning is:
Yes, selecting from the table is interesting, but not surprising given the warning.
(I don't have a MariaDB 10.2 instance at the moment, but testing on dbfiddle.uk indicates it too fails, though again not silently.)
MariaDB 10.3.6, default sql_mode (strict)
No warnings.
select * from g;
Gives:
And the column is indeed created as bigint(10).
MySQL 8.0, both the default strict and non-strict sql_mode
Computer says no.
Conclusion
Can MariaDB or MySQL cast as bigint? As we have seen, yes, MariaDB 10.3 can (though it's not GA yet ... but surely any day now it will be). However, it can only cast as bigint implicitly. You can't explicitly cast as bigint, just like you can't cast as varchar (but see MDEV-11283), text, float, tinyint etcetera. There are only a limited number of datatypes you can cast to. This is not well documented, but CAST appears to support only the same datatypes as listed for the CONVERT function.