DEV Community

Cover image for Cast for type conversion in SQL
allan-pg
allan-pg

Posted on

1

Cast for type conversion in SQL

Introduction

SQL CAST() function converts a value (of any type) into a specified datatype. This function converts an expression of one data type to another.

Syntax:

cast(expression as [datatype])
Enter fullscreen mode Exit fullscreen mode
  • [datatype] is a valid data type in relational database management System(RDBMS) you wish to convert an expression to
  • Expression It is a valid expression where we want to convert a data type into the SQL.

Example

We will use students table with dummy data

  • Students Table columns

    columns in students table

  • Students Table

    Students Table

Example 1

  • we will use the CAST function to convert the marks column from type FLOAT to INTEGER.
select name, cast(marks as int)
from students;
Enter fullscreen mode Exit fullscreen mode

or

select name, marks::int
from students;
Enter fullscreen mode Exit fullscreen mode
  • output example 1 output

*Note you can use :: followed by data type instead of typing cast *

Example 2

Lets convert marks from a float to a char() of 3 characters. Try it out yourself before checking the answer

select name, cast(marks as char(3))
from students;
Enter fullscreen mode Exit fullscreen mode
  • Output example 2 output
  • In Example 2, we use the CAST function to convert the marks column from type FLOAT to CHAR (3). When we do it, we only hold the first 3 character. If there are more than three characters, everything after the first three characters is discarded.

Conclusion

CAST in SQL is a function to explicitly convert a value of one data type to another.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay