×

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

How to use GROUP BY clause in SQL

In this SQL article, we will learn about the GROUP BY clause and how to use it in SQL. We will also discuss using the GROUP BY clause with the...

6 minutes read.

SQL INTERSECT

SQL intersect operator is used to combine two or more SELECT statements, but it only displays the data similar to the SELECT statement. The syntax for the INTERSECT operation: SELECT COLUMN_NAME1, COLUMN_NAME2,...

3 minutes read.

SQL Aliases

SQL Aliases: These are used to give a temporary name for a column or table. These are used to make tables or columns more readable. These are used to rename the table...

2 minutes read.

SQL SELECT BETWEEN Operator

This SQL tutorial explains and helps us understand how to use the BETWEEN operator in the SELECT query with examples. The SQL SELECT BETWEEN operator retrieves the data from the table...

2 minutes read.

Truncate function in SQL

The TRUNCATE is a numeric function in SQL which truncates the number according to the particular decimal points. Syntax of TRUNCATE Function SELECT TRUNCATE(X, D) AS Alias_Name; In the TRUNCATE syntax, X...

4 minutes read.

SQL UNION ALL Operator

This page has all the information about UNION ALL operator, which is used to join all the values from the SELECT queries. Similar records were not considered in the result in...

3 minutes read.

Where vs Having

Difference Between Where and Having The WHERE and HAVING clauses in SQL are used to filter records stored in tables in the databases. The dissimilarities between the WHERE and HAVING clause...

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.

SQL Data Types

In SQL DATA TYPES, each column holds value. Data types can be an integer type, character type, etc., and such data is stored in the database table. The data type is...

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

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.

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.

How to Update Table in SQL?

How to Update Table in SQL Introduction UPDATE query is used to update a record in a table. UPDATE is a DML command, which operates on the data of the table and not...

4 minutes read.

Update Query in SQL

Update is an SQL command that is used to modify the data that in already present in database. Update is a command of DML. DML means Data Manipulation Language. Basically,...

3 minutes read.

SQL Between Operator

SQL Between operator is a logical operator in the Structured Query Language. The Between operator is used to retrieve data within the range specified in the condition in the query. The...

7 minutes read.

SQL COPY Table

In this tutorial, we will learn how to copy tables in SQL with the help of examples. Using the SELECT INTO statement in the SQL we can copy one table into...

4 minutes read.

Types of SQL JOIN

The SQL JOIN combines one or more than one tables based on their relationship. The SQL JOIN involves a parent table and a child table relationship. There are different types of...

10 minutes read.

SQL Temporary Tables

Temporary Table: The Temporary tables are generally created in TempDB. If the last connection is terminated then the tables are deleted automatically. These are generally used to store and process the...

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.

SQL Count

Structured Query Language Count() Function is used with Structured Query Language SELECT Statement. SQL Count() function returns the number of items that match the specified criteria in the SELECT statement. Count()...

2 minutes read.