JournalSQLFunctions and dates1 min

For Those Who Do Not Know CAST

There are many cases where we need to convert columns from one data type to another data type. To be able to use CAST, you must first take a quick look at data types in SQL.

  • CAST
  • data types
  • conversion
  • ::

Introduction

There are many cases where we need to convert columns from one data type to another data type. To be able to use CAST, you must first take a quick look at data types in SQL.

Most Commonly Used Data Types

You will find all the types you might need here:

https://www.techonthenet.com/postgresql/datatypes.php

Syntax

We can use CAST like this:

CAST ( column_name AS type )

Using CAST

We can convert from text to a date. For example, if we write:

SELECT CAST('2018-03-27' AS DATE)

The output will appear as:

date
2018-03-27T00:00:00.000Z

However, if you swap the day and month and write a different date format:

SELECT CAST('2018-27-03' AS DATE)

An error will appear saying:

date/time field value out of range: "2018-27-03"

In case the date format is different, we can convert to the date type using the TO_DATE function. You can find its explanation with examples here: For Those Who Do Not Know TO_DATE

And if we want to convert text containing a number to an integer type, we write:

SELECT CAST('220' AS INTEGER)

Whereas if we convert text containing both numbers and letters to an integer type:

SELECT CAST('220M' AS INTEGER)

We will get an error saying:

invalid input syntax for integer: "220M"

Because an integer cannot contain letters.

We can also convert to numeric if we want the number to contain decimal points:

SELECT CAST(220 AS NUMERIC)

The output will be:

220.0

Alternative Way to Use CAST

Instead of writing CAST to convert from one data type to another, we can use the :: operator, as shown in the example:

SELECT 220::NUMERIC

The expected output:

220.0

And this is much easier to write, and easier to read as well.