SQL implicit conversion
When types collide, the engine converts one side without telling you. '123' + 1 is 124 on all five engines, but a text column plus 1 is an error on PostgreSQL, and 'abc' + 1 is 1 on MySQL and SQLite.
- Returns
depends on the winning type- In this category
- 18 of 39
語法
mixing types in expressions, comparisons and joins
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | 是 | strictest: text + integer is an error; cast explicitly |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | Supported under this name. |
| Oracle | 是 | Supported under this name. |
範例
Any engine
SELECT '123' + 1 AS n;
SQL Server
-- customer_code is varchar: the literal matches, so the index seek stays SELECT * FROM orders WHERE customer_code = '10248';
小知識
- PostgreSQL treats a quoted literal as type unknown and resolves it from context, so '123' + 1 is 124. A value that is already text is different: '123'::text + 1, or a text column plus 1, fails with 'operator does not exist: text + integer'.
- SQLite and MySQL read the leading digits: '123abc' + 1 is 124 and 'abc' + 1 is 1. MySQL records a warning; SQLite says nothing. SQL Server and Oracle raise a conversion error for 'abc' + 1.
- An implicit conversion on the column side, as in WHERE varchar_col = 10248, converts every row's value and loses the index seek on SQL Server and MySQL. Quote the literal so it matches the column type.
- On SQL Server, + between two strings is concatenation: '1' + '1' is '11'. With one number involved, data type precedence converts the string to int, so '123' + 1 and 1 + '123' are both 124.
Questions about Implicit conversion
Why is my index suddenly unused?
A type mismatch between column and literal forces a per-row conversion of the column. Match the literal's type to the column (quotes around the value for varchar columns) and the seek returns.
Which engine is strictest about types?
PostgreSQL: once a value has a type, mixing it with an incompatible type is an error rather than a conversion. SQL Server and Oracle convert but error on unparseable text; MySQL and SQLite convert anything, falling back to 0.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.