Convert data types in PostgreSQL SELECT statement
PostgreSQL 8 and above allows data type conversion in SELECT statements. For example, to convert a varchar column to type int, you can use one of the following syntaxes:
<code class="language-sql">cast(varchar_col AS int) -- SQL 标准语法</code>
or
<code class="language-sql">varchar_col::int -- PostgreSQL 简写语法</code>
The two syntaxes can usually be used interchangeably unless specific syntax restrictions are encountered.
Also, consider the following forms:
<code class="language-sql">int4(varchar_col) -- 对某些类型名称有效 int '123' -- 无类型,带引号的字符串字面量</code>
It should be noted that the last form does not support array types. For array types, you need to use '{1,2,3}'::int[] or cast('{1,2,3}' AS int[]).
When converting a string to an int, the string should only contain optional symbols (/-) followed by digits. Leading and trailing spaces are ignored. For more details, please refer to the PostgreSQL documentation linked below.
The above is the detailed content of How Can I Cast Data Types in PostgreSQL SELECT Statements?. For more information, please follow other related articles on the PHP Chinese website!