×

SQL Cast Operator

While writing SQL queries, we can see many values which are to be converted into another datatype for accessing them. In SQL this conversion is generally done by CAST function.

CAST Function:

This function is used for converting an expression from one datatype to another datatype.

Generally, we use cast function to convert expressions from numeric to string datatype or string to numeric datatype.

Syntax for CAST Function:

CAST (expression/value AS resultant_datatype)

Where,

  • Expression/value - This is expression which is to be converted to another datatype.
  • AS - converting operator.
  • resultant_datatype – The datatype to which the expression should be converted.

Example:

select
 CAST (‘2022-06-28’ AS DATETIME) 
result;

This Statement gives the output in date and time format.

OUTPUT:

Result
2022-06-28 00:00:00.000

NOTE: Datatype conversion should be done between two compatible datatypes only.

When we try to convert a string “sarfn” into numeric datatype, we will be encountered with an error. So, cast function is only used between compatible datatypes.

Conversion of Decimal Number to integer datatype:

If we try to convert a Decimal number to an integer, the resultant will be the rounded value of the Decimal number.

Example:

select cast (7.44 as int) result;

OUTPUT:

Result
7

Conversion of String to a Datetime:

If we try to convert a String having a date value to date and time format, the resultant will be a standard format for date and time.

Example:

select cast (‘2022-06-28’ as datetime) result;

OUTPUT:

Result
2022-06-28 00:00:00.000

Datatype conversion Table

Serial.Nocurrent datatypeResultant   datatype Behaviour
1NumericNumericIt rounds off the value.
2NumericMoneyIt rounds off the value.
3NumericIntegerIt truncates the value.
4MoneyIntegerIt rounds off the value.
5MoneyNumericIt rounds off the value.
6DatetimeIntegerIt rounds off the value.
7FloatIntegerIt truncates the value.

TRY_CAST Function:

TRY_CAST function also works similar to CAST() function. This function returns a NULL value when the conversion fails. But in the case of CAST() function an error is raised.

Syntax:

TRY_CAST (expression/value AS datatype[(length)])
  • Expression/value - This is expression which is to be converted to another datatype.
  • AS - converting operator.
  • resultant_datatype – The datatype to which the expression should be converted.

 Example:

Select try_cast(“18 Main” AS float) result;

OUTPUT:

Result
NULL

For the above query if we use CAST() function in place of TRY_CAST() function, we will be raised with an error. This is the main difference between cast () and try_cast() function.

SQL CONVERT () Function:

This function also works same as cast function. Convert () function is specific to only SQL server, whereas CAST Function follows ANSI Standard.

Syntax:

CONVERT (final data type (Length), expression/value, style)

Where,

  • final data type: This is the data type to which the expression or value should be converted, after using CONVERT () function.
  • Length of the final data type: It is not mandatory to mention the length of final data type.
  • Expression/value: Expression or value should be converted to final data type. Expression can be of any data type like integer, varchar, binary.
  • Style: This field is also optional in the syntax of convert function. This part is for conversion between date or string format.
Without CenturyWith CenturyInput/OutputStandard
1101mm/dd/yyyyUS
2102yyyy.mm.ddANSI
3103dd/mm/yyyyBritish/French
5105dd-mm-yyyyItalian
7107Mon dd, yyyy--
8108hh:mm:ss--
11111yyyy/mm/ddJapan

Example:

select convert (integer, 89.98);

 OUTPUT:

Number of Records: 1
89
It shows the truncated value i.e 89.
select convert (varchar, ‘2022-06-29’, 102);

OUTPUT:

Number of Records: 1
2022-06-29

Differences between CAST () Function and CONVERT () Function:

CAST () FunctionCONVERT () Function
1. Cast function converts the expression or value from one data type to another data type.Convert function converts the expression or value from one data type to another data type.
2. Cast function follows ANSI standard.Convert function is only specific to SQL.
Syntax: CAST (expression/value AS resultant_datatype)Syntax: CONVERT (final data type (Length), expression/value, style)  
Example: select cast (24.31 AS integer) result;   OUTPUT: result -------------- 24Example: select convert (integer, 24.31);   OUTPUT: Number of records: 1 24  

Now let’s look the CAST () Function using Tables.

Consider an Employee Table.

Employee_NameEmployee_IDEmployee_AgeEmployee_Salary
Rishi301124300000.252
Dhruv301626300000.450
Ayaan301725350000.000

Consider a situation where the Salaries of all employees should be sum up to know the total amount given in a month for sales report purpose.

So, a rounded off amount is enough for sales report (including decimal points is not mandatory).

For this purpose, we can convert the Employee_Salary into integer data type which is a float data type initially.

The query for the above conversion is,

select Employee_name, cast (Employee_Salary AS Integer) Employee_salary (Integer) from Employee;

OUTPUT:

Employee_NameEmployee_salary (Integer)
Rishi300000
Dhruv300000
Ayaan350000

This is how we use CAST () Function in real-life examples.

In databases related to university, bank databases, and Account databases we can use CAST () Function.


Related Topics

Codd’s Rules in SQL

Codd’s Rules Dr. Edgar F. Codd, in 1985, laid down 13 fundamental rules after doing large-scale research on the Relational Model of databases. According to him, every database must follow these...

3 minutes read.

SQL Aggregate Functions

In this tutorial, we will learn and understand the SQL Aggregate Functions concept with the help of examples. SQL Aggregate Function is a function used to perform calculation operations on one...

4 minutes read.

SQL SELECT Database

In this tutorial, we will help you to understand and learn how to select the database in SQL with the help of examples. The database user or the administrator wants to...

3 minutes read.

SQL Wildcards

SQL WILDCARD CHARACTERS: SQL wild card character is used to substitute zero or more characters of a string. These characters are used with the “LIKE” operator. Wild Card Characters in SQL: %_[]^- “%” : It is...

3 minutes read.

SQL IN vs SQL EXISTS

SQL IN vs SQL EXISTS This article discusses in detail about the IN and the EXISTS operators in SQL. It is a common question between developers that what is the difference...

3 minutes read.

How to add column in table in SQL ?

How to add column in table in SQL  Introduction To add a column in already created table, one needs to use the ALTER command along with the ADD clause.If in the query,...

7 minutes read.

SQL HAVING Clause

In this tutorial, we will understand the HAVING clause concept in SQL with the help of examples. The HAVING Clause in the SQL is used as we cannot use the WHERE...

3 minutes read.

SQL INSERT INTO Values

This article will help you in getting a better understanding of a very important SQL INSERT INTO VALUES function. INSERT INTO statement is used to insert or add a new record...

4 minutes read.

TCL Commands in SQL

In Structured Query Language, TCL is an abbreviation for Transaction Control Language. A single unit of work in a database is formed after the consecutive execution of commands is known...

6 minutes read.

SQL Data Manipulation Language

Data Manipulation Language manipulates/make changes in data present in a table. It only affects data/records of table, not on the schema/structure of table. INSERT, UPDATE, DELETE are the commands of DML. INSERT: Stores...

2 minutes read.

DELETE VS DROP in SQL

This page contains all the information about the Delete command and Drop command concept and the difference between the DELETE and DROP commands in SQL. What is the DELETE command in...

3 minutes read.

SQL INSERT Table

In this tutorial, we will help you to understand and learn how to add records to the table in SQL with the help of examples. SQL INSERT query is used to...

5 minutes read.

SQL SELECT OR Operator

This SQL tutorial explains and helps us understand how to use the OR operator in the SELECT query with examples. The OR operator in the Structured Query Language is used to...

3 minutes read.

SQL Injection

SQL injection is a technique, this may destroy the database. It is one type of hacking technique. SQL IN WEB PAGES: Injection occurs when we ask for input like an id or...

3 minutes read.

DDL Commands in SQL

DDL stands for Data Definition Language. Data Definition Language is a bunch of SQL commands used to create, modify and delete Database schema but not the records or data. Data Definition...

5 minutes read.

SQL SELECT WHERE Clause

In this SQL section, we will help you understand the concept of the SQL SELECT WHERE clause with a few examples. The WHERE clause in SELECT query displays those records as...

5 minutes read.

space() function in SQL

 This function returns a string with a specified number of spaces. If we specify a number, it returns the strings having that specified number of spaces. SPACE Function is available...

2 minutes read.

SQL SET Keyword

This article will provide you a good understanding of the Set keyword in Structured Query Language. What is the SET keyword? The SET keyword is used to specify values for the variables....

3 minutes read.

SQL Primary Key

A field, which contains unique data in a table, is called a PRIMARY KEY (PK). It means, a PRIMARY KEY field must contain unique data in the table. A PRIMARY KEY...

4 minutes read.

Grant Command in SQL

What is DCL (Data Control Language)? Data Control Language (DCL) is a computer programming language with syntax intended to manage access to data kept in databases. It is a part of...

3 minutes read.