// conversion reference

SQL CAST to SIGNED

CAST('42' AS SIGNED) parses text into a 64-bit integer. These are MySQL's only integer cast targets: CAST(x AS INT) is a syntax error there.

类别
Conversion
Returns
integer
In this category
13 of 39

语法

CAST(expression AS SIGNED)
CAST(expression AS UNSIGNED)

Each block is a separate form. The support table and the examples show which engine takes which.

引擎支持

引擎Support备注
SQL Server Not built in no SIGNED/UNSIGNED targets; use INT or BIGINT
PostgreSQL Not built in no unsigned integer types; use integer or bigint
MySQL 是 Supported under this name.
SQLite Not built in use CAST(... AS INTEGER)
Oracle Not built in use NUMBER or INTEGER

示例

MySQL

SELECT CAST(order_ref AS SIGNED) AS ref
FROM uploads;

MySQL

SELECT CAST('42abc' AS SIGNED) AS prefix_parsed;

值得了解

  • CAST('42abc' AS SIGNED) parses the leading numeric prefix and returns 42 with a warning; CAST('abc' AS SIGNED) returns 0. Validate imports before trusting the cast.
  • Casting a negative number to UNSIGNED wraps instead of failing: CAST(-1 AS UNSIGNED) is 18446744073709551615, in strict mode too. Arithmetic is different: CAST(1 AS UNSIGNED) - 2 raises 'BIGINT UNSIGNED value is out of range'.
  • Fractions round, not truncate: CAST(2.5 AS SIGNED) is 3 and CAST(-2.5 AS SIGNED) is -3. Text fractions do truncate: CAST('2.7' AS SIGNED) is 2.
  • No other engine has unsigned integer types or these targets. The portable spelling is CAST(x AS INTEGER) or BIGINT, which MySQL in turn does not accept.

Questions about SIGNED / UNSIGNED

Why does 0 - 1 fail on my unsigned column?

MySQL treats unsigned subtraction below zero as an out-of-range error. Cast an operand to SIGNED, enable the NO_UNSIGNED_SUBTRACTION SQL mode, or store signed values if the result can go negative.

How do I get the integer out of '12kg'?

CAST('12kg' AS SIGNED) gives 12 because MySQL parses the numeric prefix. That convenience does not exist on the other engines; strip the suffix first.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: MySQL.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.