×

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

SQL Tutorial for Beginners

SQL tutorial provides basic and advanced concepts of Structured Query Language and how you deploy SQL to work with a relational database system. Our SQL tutorial is designed for beginners...

3 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.

How to use HAVING clause in SQL

In this article, we will learn about the HAVING clause concept and how to use it in SQL. What is the HAVING clause? In Structured Query Language, HAVING Clause used with GROUP...

7 minutes read.

How to use LIKE in SQL

In this SQL article, we will learn and understand how to use LIKE to the columns in the SQL tables. What is Like? Like is an operator in the SQL. It is...

7 minutes read.

SQL SELECT SUM

The SQL Sum() function is an aggregate function in SQL that returns the total values of an expression. The expression may be numerical, or it may be an expression. Syntax: SELECT SUM(columnname)...

3 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 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.

SQL Formatter

As a beginner, one does not focus much on Formatting the queries while writing their code. This leads to a great confusion while referring the code in future. For a...

5 minutes read.

Difference between Delete, Drop and Truncate in SQL

What is the Delete command in SQL? In DML (Data Manipulation Language), we use the delete command that allows us to delete the some entries and modify the databases in SQL....

4 minutes read.

How to Add Comments in SQL?

How to Add Comments in SQL Comments are text notes that are incorporated into the program to make the code easier to understand. In SQL, commenting is used to explain various sections...

2 minutes read.

Introduction to SQL

SQL Introduction SQL is Standard Query Language. This language is used to communicate or interact with database. In other words, SQL is used to access and manage data or information...

2 minutes read.

SQL CREATE TABLE

In SQL tutorial, we learned and created different databases. To stores data in databases, we need to create a table. To create the table, we need to use CREATE TABLE...

5 minutes read.

SQL DELETE

In this tutorial, you will learn about the SQL DELETE concept by using examples. In Structured Query Language (SQL), we fetch the data from the database table using SELECT Statement and...

3 minutes read.

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...

4 minutes read.

SQL Select Distinct

The SQL DISTINCT query is used to fetch unique values from the tables using the SELECT statement in the SQL. There may be a situation that arises when you want to...

4 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 Insert multiple rows

This article will deal with a new insertion method in SQL which inserts multiple rows at a time. Multiple records can be inserted at a time into a specific table with...

4 minutes read.

DML Commands in SQL

DML is an abbreviation of Data Manipulation Language. Data Manipulation Language commands in Structured Query Language manipulate the data in the database. DML commands are used to retrieve records, add records,...

4 minutes read.

SQL VIEW

The SQL VIEW concept helps to hide the difficulty of the records and provides limitations to access to the database. The SQL view is similar to the SQL tables. In SQL...

7 minutes read.

SQL FOREIGN KEY

In this article, we will learn about the FOREIGN KEY constraints and how to define a FOREIGN KEY constraint to build the relationship between two tables. In a Relational Databases Management...

4 minutes read.