YogeshChauhan . com

Casting in PostgreSQL

in Postgres on April 25, 2020

There are many cases that you want to convert a value of one data type into another.

PostgreSQL provides you with the CAST operator that allows you to do this. You can convert string to integers, casting to Boolean, casting string to date and so on.

Syntax:


CAST (expression AS data type);

One more Syntax:


Expression :: type

Examples

String to integer Casting


SELECT
   CAST ('1' AS INTEGER);

//output
1

If it's not possible to convert, it will raise an error.

Using the 2nd syntax, let's cast float to int.


select 1.0::integer;

//output 
1

timestamp to date casting Syntax


SELECT  expression ::TIMESTAMP::DATE;

example


SELECT  expression ::TIMESTAMP::DATE;

//output
2020-03-18

Type DOUBLE doesn't exist in Postgres. So, you need to use DOUBLE PRECISION.

For example,


SELECT CAST ('1100.100' AS DOUBLE PRECISION);

//output
1100.1

You can also do something like this:


SELECT CAST ( 2 AS numeric ) + 4.0;

//output
6.0

If the cast is marked AS IMPLICIT then it can be invoked implicitly in any context, whether assignment or internally in an expression. So, you can write the above query without casting..


SELECT 2 + 4.0;

//output
6.0
amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 14 How to add Google Map in WordPress using ACF? May 13 How to add a select dropdown in React? May 12 What are Controlled Components in React? May 11 How to create a full screen loader using CSS and JavaScript? May 11 How to hide and show menu on scroll using JavaScript and CSS? May 10 @use rule in SCSS (Sass)

You might also like these

How to create a sidebar using pure CSS?CSSIN Operator in PostgreSQLPostgresEXISTS and NOT EXISTS in PostgresPostgresLearn how to add Scroll Indicator using CSS and JavaScript?CSSFull and Partial ROLLUP in Postgresql with ExamplesPostgresHow to Create a Copy of a Table in SQL and MySQL?SQL/MySQL