Cast for type conversion in SQL

WBOY
Release: 2024-08-22 14:31:03
Original
991 people have browsed it

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])
Copy after login
  • [datatype]is a valid data type in relational database management System(RDBMS) you wish to convert an expression to
  • ExpressionIt 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

    Cast for type conversion in SQL

  • Students Table

    Cast for type conversion in SQL

Example 1

  • we will use the CAST function to convert themarkscolumn from type FLOAT to INTEGER.
select name, cast(marks as int) from students;
Copy after login

or

select name, marks::int from students;
Copy after login
  • outputCast for type conversion in SQL

*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;
Copy after login
  • OutputCast for type conversion in SQL
  • 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.

The above is the detailed content of Cast for type conversion in SQL. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
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!