mysql
  1. mysql-cast

CAST - (MySQL Misc)

In MySQL, the CAST function is used to convert a value of one data type to another data type. This is useful when you need to perform calculations or comparisons on data that is stored in a different format than what you need.

Syntax

The basic syntax for using the CAST function in MySQL is as follows:

CAST(expression AS type);

Here, "expression" is the value or column that you want to convert, and "type" is the data type to which you want to convert the expression.

Example

Let's say we have a table called "sales" that contains a column called "revenue" which is stored as a string. We want to calculate the total revenue for all sales, but since "revenue" is stored as a string, we need to convert it to a numeric type first. We can do this using the CAST function, as shown below:

SELECT SUM(CAST(revenue AS DECIMAL(10,2))) AS total_revenue FROM sales;

In this example, we're using the CAST function to convert the "revenue" column to a DECIMAL data type with precision 10 and scale 2. We're then using the SUM function to calculate the total revenue for all sales.

Output

When we run the query above, we'll get a result set that looks something like this:

+---------------+
| total_revenue |
+---------------+
|      1456.98  |
+---------------+

This tells us that the total revenue for all sales is 1456.98.

Explanation

In the example above, we used the CAST function to convert the "revenue" column from a string to a DECIMAL data type. This allowed us to perform calculations on the data and ultimately calculate the total revenue for all sales.

Use

The CAST function is useful when you need to work with data that is stored in a different format than what you need. This could be because the data was entered in a different format, or because the data was imported from a different system.

Important Points

  • The CAST function can convert data of many different types, including strings, numeric types, and date/time types.
  • When using the CAST function, be sure to choose the correct data type for your needs to ensure that the converted value is accurate.
  • The CAST function can be used in conjunction with other functions, such as SUM and AVG, to perform calculations on the converted data.

Summary

In this tutorial, we discussed the CAST function in MySQL. We covered the syntax, example, output, explanation, use, and important points of the CAST function. With this knowledge, you can now use the CAST function to convert data of one data type to another in MySQL.

Published on: