Home  >  Article  >  Java  >  How to Cast Data Types from Varchar to Int in PostgreSQL SELECT Statement?

How to Cast Data Types from Varchar to Int in PostgreSQL SELECT Statement?

DDD
DDDOriginal
2024-10-24 16:45:02220browse

How to Cast Data Types from Varchar to Int in PostgreSQL SELECT Statement?

Casting Data Types in Postgres

Question: How can I cast a column's data type from varchar to int in a Postgres SELECT statement?

Answer:

Postgres offers several options for casting data types:

  • cast(varchar_col AS int): SQL standard syntax
  • varchar_col::int: Postgres syntax shorthand

Both variants are generally interchangeable, but the second may require additional parentheses in certain scenarios.

Additionally, you can use these syntax variations:

  • int4(varchar_col): Only works for specific type names (e.g., int4)
  • int '123': Must use an untyped, quoted string literal

Note that the varchar_col must contain only numerals and an optional leading sign. Leading or trailing whitespace is ignored.

Example:

<code class="sql">SELECT cast(passenger_name AS int), age FROM passengers;</code>

This query will cast the passenger_name column, which is a varchar, to an int before returning the result.

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

Statement:
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