Home > Java > javaTutorial > body text

How to Cast Data Types within SELECT Statements in PostgreSQL?

Patricia Arquette
Release: 2024-10-24 17:25:02
Original
612 people have browsed it

How to Cast Data Types within SELECT Statements in PostgreSQL?

Casting Data Types in Postgres SELECT Statements

In Postgres 8, it is possible to convert a column's data type to another within a SELECT statement.

Convert Varchar to Int

To cast a varchar column to an int, use the following syntax:

<code class="sql">cast(varchar_col AS int)  -- SQL standard
varchar_col::int          -- Postgres syntax shorthand</code>
Copy after login

These options are nearly universally applicable. The latter form may require additional nested parentheses in certain situations, while the former may be necessary in functional notation contexts.

Example

<code class="sql">SELECT cast(age_str AS int) AS age_int
FROM customer_info;</code>
Copy after login

Additional Notes

  • PostgreSQL allows four other casting variants:

    • int4(varchar_col) (works for specific type names)
    • int '123' (untyped quoted string literals)
  • The string value must follow specific formatting:

    • Optional leading sign ( /-)
    • Digits only
    • Leading/trailing whitespaces are ignored
  • See the Postgres manual for more details on casting.

The above is the detailed content of How to Cast Data Types within SELECT Statements in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!