Home > Java > javaTutorial > body text

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

DDD
Release: 2024-10-24 16:45:02
Original
219 people have browsed it

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

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!

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
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!