SQL CAST Function



  SQL > SQL Commands > CAST Function

In many cases, a database will automatically convert one data type into another when needed. On the other hand, there are instances when that is not the case, or when you want to explicitly specify what data type to change into. In these cases, you can use the CAST function. The syntax of the CAST function is as follows:

CAST (expression AS [data type])

where [data type] is a valid data type in the RDBMS you are working with.

Let's go through some examples to see how the CAST function is used. Let's assume we have the following table:

Table Student_Score
StudentIDinteger
First_Namechar(20)
Scorefloat

and this table contains the following rows:

Table Student_Score
StudentIDFirst_NameScore
1Jenny85.2
2Bob92.5
3Alice90
4James120.1

Example 1

SQL:

SELECT First_Name, CAST(Score AS Integer) Int_Score FROM Student_Score

Result:

First_NameInt_Score
Jenny85
Bob92
Alice90
James120

In Example 1, we use the CAST function to convert the Score column from type FLOAT to INTEGER. When we do this, different RDMBS have different rules on how to handle the numbers after the decimal point. In the above example, we assume that the numbers after the decimal point are always truncated.

Example 2

SQL:

SELECT First_Name, CAST(Score AS char(3)) Char_Score FROM Student_Score

Result:

First_NameChar_Score
Jenny85.
Bob92.
Alice90  
James120

In Example 2, we use the CAST function to convert the SCORE column from type FLOAT to CHAR(3). When we do this, we only take the first 3 characters. So, if there are more than 3 characters, everything after the first 3 characters is discarded.

Next: SQL CONVERT Function




Copyright © 2013 1keydata.com   All Rights Reserved.     Privacy Policy


SQL SELECT
SQL DISTINCT
SQL WHERE
SQL AND OR
SQL IN
SQL BETWEEN
SQL Wildcard
SQL LIKE
SQL ORDER BY
SQL Functions
SQL Average
SQL COUNT
SQL MAX
SQL MIN
SQL SUM
SQL GROUP BY
SQL HAVING
SQL ALIAS
SQL AS
SQL JOIN
SQL INNER JOIN
SQL OUTER JOIN
SQL LEFT OUTER JOIN
SQL CROSS JOIN
SQL SELECT UNIQUE
SQL ROUND
SQL CAST
SQL CONVERT
SQL CONCATENATE
SQL SUBSTRING
SQL INSTR
SQL TRIM
SQL LENGTH
SQL REPLACE
SQL DATEADD
SQL DATEDIFF
SQL DATEPART
SQL GETDATE
SQL SYSDATE

SQL CREATE TABLE
SQL Data Types
SQL CONSTRAINT
SQL NOT NULL
SQL DEFAULT
SQL UNIQUE
SQL CHECK
PRIMARY KEY
FOREIGN KEY
SQL View
SQL CREATE VIEW
SQL Index
SQL CREATE INDEX
SQL ALTER TABLE
SQL DROP TABLE
SQL TRUNCATE TABLE
SQL USE
SQL CREATE DATABASE
SQL DROP DATABASE
SQL INSERT INTO
SQL INSERT INTO SELECT
SQL UPDATE
SQL DELETE FROM

SQL Video Tutorial
SQL Jobs

Site Map
Resources