Home > Database > Mysql Tutorial > How Can I Cast Data Types in PostgreSQL SELECT Statements?

How Can I Cast Data Types in PostgreSQL SELECT Statements?

Linda Hamilton
Release: 2025-01-13 20:26:44
Original
318 people have browsed it

How Can I Cast Data Types in PostgreSQL SELECT Statements?

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>
Copy after login

or

<code class="language-sql">varchar_col::int          -- PostgreSQL 简写语法</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template